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.Linq; using UnityEditor.IMGUI.Controls; using UnityEngine; using UnityEngine.Scripting; namespace UnityEditor { [UsedByNativeCode] internal class PackageImport : EditorWindow { [SerializeField] private ImportPackageItem[] m_ImportPackageItems; [SerializeField] private string m_PackageName; [SerializeField] private string m_PackageIconPath; [SerializeField] TreeViewState m_TreeViewState; [NonSerialized] PackageImportTreeView m_Tree; public ImportPackageItem[] packageItems { get { return m_ImportPackageItems; } } private static Texture2D s_PackageIcon; private static Texture2D s_Preview; private static string s_LastPreviewPath; readonly static HashSet<char> s_InvalidPathChars = new HashSet<char>(System.IO.Path.GetInvalidPathChars()); internal class Constants { public GUIStyle ConsoleEntryBackEven = "CN EntryBackEven"; public GUIStyle ConsoleEntryBackOdd = "CN EntryBackOdd"; public GUIStyle title = "LargeBoldLabel"; public GUIStyle subtitle = "BoldLabel"; public GUIStyle stepInfo = "Label"; public GUIStyle bottomBarBg = "ProjectBrowserBottomBarBg"; public GUIStyle topBarBg = "OT TopBar"; public GUIStyle textureIconDropShadow = "ProjectBrowserTextureIconDropShadow"; public Color lineColor; public Constants() { lineColor = EditorGUIUtility.isProSkin ? new Color(0.1f, 0.1f, 0.1f) : new Color(0.4f, 0.4f, 0.4f); } } static Constants ms_Constants; // Invoked from menu [UsedByNativeCode] public static void ShowImportPackage(string packagePath, ImportPackageItem[] items, string packageIconPath, int productId, string packageName, string packageVersion, int uploadId) { if (!ValidateInput(items)) return; var origin = new AssetOrigin(productId, packageName, packageVersion, uploadId); PackageImportWizard.instance.StartImport(packagePath, items, packageIconPath, origin); } public PackageImport() { minSize = new Vector2(350, 350); } void OnDisable() { DestroyCreatedIcons(); } void DestroyCreatedIcons() { if (s_Preview != null) { DestroyImmediate(s_Preview); s_Preview = null; s_LastPreviewPath = null; } if (s_PackageIcon != null) { DestroyImmediate(s_PackageIcon); s_PackageIcon = null; } } internal void Init(string packagePath, ImportPackageItem[] items, string packageIconPath) { DestroyCreatedIcons(); m_TreeViewState = null; m_Tree = null; m_ImportPackageItems = items; m_PackageName = System.IO.Path.GetFileNameWithoutExtension(packagePath); m_PackageIconPath = packageIconPath; Repaint(); } private bool ShowTreeGUI(ImportPackageItem[] items) { if (items.Length == 0) return false; for (int i = 0; i < items.Length; i++) { if (!items[i].isFolder && items[i].assetChanged) return true; } return false; } internal override void OnResized() { m_Tree?.OnWindowResized(); base.OnResized(); } public void OnGUI() { if (ms_Constants == null) ms_Constants = new Constants(); if (m_TreeViewState == null) m_TreeViewState = new TreeViewState(); if (m_Tree == null) m_Tree = new PackageImportTreeView(this, m_TreeViewState, new Rect()); if (m_ImportPackageItems != null && ShowTreeGUI(m_ImportPackageItems)) { TopArea(); TopButtonsArea(); m_Tree.OnGUI(GUILayoutUtility.GetRect(1, 9999, 1, 99999)); BottomArea(); } else { GUILayout.Label("Nothing to import!", EditorStyles.boldLabel); GUILayout.Label("All assets from this package are already in your project.", "WordWrappedLabel"); GUILayout.FlexibleSpace(); // Background GUILayout.BeginVertical(ms_Constants.bottomBarBg); GUILayout.Space(8); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("OK")) { Close(); GUIUtility.ExitGUI(); } GUILayout.Space(10); GUILayout.EndHorizontal(); GUILayout.Space(5); GUILayout.EndVertical(); } } void TopArea() { const float margin = 10f; const float imageSize = 64; if (s_PackageIcon == null && !string.IsNullOrEmpty(m_PackageIconPath)) LoadTexture(m_PackageIconPath, ref s_PackageIcon); bool hasPackageIcon = s_PackageIcon != null; float totalTopHeight = hasPackageIcon ? (margin + imageSize + margin) : 52f; Rect r = GUILayoutUtility.GetRect(position.width, totalTopHeight); // Background GUI.Label(r, GUIContent.none, ms_Constants.topBarBg); Rect titleRect; if (hasPackageIcon) { Rect iconRect = new Rect(r.x + margin, r.y + margin, imageSize, imageSize); DrawTexture(iconRect, s_PackageIcon, true); var textContentWidth = r.width - iconRect.width; var textContentX = iconRect.xMax + margin; if (!PackageImportWizard.instance.IsMultiStepWizard) titleRect = new Rect(textContentX, iconRect.yMin, textContentWidth, iconRect.height); else { titleRect = new Rect(textContentX, iconRect.yMin, textContentWidth, iconRect.height / 3); // Subtitle var subtitleRect = new Rect(textContentX + 1f, iconRect.yMin + iconRect.height * 0.50f, textContentWidth, iconRect.height / 4); var subtitleText = PackageImportWizard.instance.IsProjectSettingStep ? "Import Settings Overrides" : "Import Content"; GUI.Label(subtitleRect, EditorGUIUtility.TrTextContent(subtitleText), ms_Constants.subtitle); // "Step x of y" label var stepInfoRect = new Rect(textContentX, iconRect.yMin + iconRect.height * 0.75f, textContentWidth, iconRect.height / 4); var stepInfoText = PackageImportWizard.instance.IsProjectSettingStep ? "Step 2 of 2" : "Step 1 of 2"; GUI.Label(stepInfoRect, EditorGUIUtility.TrTextContent(stepInfoText), ms_Constants.stepInfo); } } else { titleRect = new Rect(r.x + 5f, r.yMin, r.width, r.height); } // Title GUI.Label(titleRect, m_PackageName, ms_Constants.title); } void TopButtonsArea() { GUILayout.BeginVertical(); GUILayout.Space(8); GUILayout.BeginHorizontal(); GUILayout.Space(10); if (GUILayout.Button(EditorGUIUtility.TrTextContent("All"), GUILayout.Width(50))) { m_Tree.SetAllEnabled(PackageImportTreeView.EnabledState.All); } if (GUILayout.Button(EditorGUIUtility.TrTextContent("None"), GUILayout.Width(50))) { m_Tree.SetAllEnabled(PackageImportTreeView.EnabledState.None); } GUILayout.Space(10); GUILayout.EndHorizontal(); GUILayout.Space(5); GUILayout.EndVertical(); } void BottomArea() { // Background GUILayout.BeginVertical(ms_Constants.bottomBarBg); GUILayout.Space(8); GUILayout.BeginHorizontal(); GUILayout.Space(10); GUILayout.FlexibleSpace(); if (GUILayout.Button(EditorGUIUtility.TrTextContent("Cancel"))) { PackageImportWizard.instance.CancelImport(); } var isSecondStep = PackageImportWizard.instance.IsMultiStepWizard && PackageImportWizard.instance.IsProjectSettingStep; if (isSecondStep && GUILayout.Button(EditorGUIUtility.TrTextContent("Back"))) { PackageImportWizard.instance.DoPreviousStep(m_ImportPackageItems); } var buttonText = isSecondStep || !PackageImportWizard.instance.IsMultiStepWizard ? "Import" : "Next"; if (GUILayout.Button(EditorGUIUtility.TrTextContent(buttonText))) { if (m_ImportPackageItems != null) PackageImportWizard.instance.DoNextStep(m_ImportPackageItems); else PackageImportWizard.instance.CloseImportWindow(); } GUILayout.Space(10); GUILayout.EndHorizontal(); GUILayout.Space(5); GUILayout.EndVertical(); } // Reuses old texture if it's created static void LoadTexture(string filepath, ref Texture2D texture) { if (!texture) texture = new Texture2D(128, 128); byte[] fileContents = null; try { fileContents = System.IO.File.ReadAllBytes(filepath); } catch { // ignore } if (filepath == "" || fileContents == null || !texture.LoadImage(fileContents)) { Color[] pixels = texture.GetPixels(); for (int i = 0; i < pixels.Length; ++i) pixels[i] = new Color(0.5f, 0.5f, 0.5f, 0f); texture.SetPixels(pixels); texture.Apply(); } } public static void DrawTexture(Rect r, Texture2D tex, bool useDropshadow) { if (tex == null) return; // Clamp size (preserve aspect ratio) float texwidth = tex.width; float texheight = tex.height; if (texwidth >= texheight && texwidth > r.width) { texheight = texheight * r.width / texwidth; texwidth = r.width; } else if (texheight > texwidth && texheight > r.height) { texwidth = texwidth * r.height / texheight; texheight = r.height; } // Center float x = r.x + Mathf.Round((r.width - texwidth) / 2.0f); float y = r.y + Mathf.Round((r.height - texheight) / 2.0f); r = new Rect(x, y, texwidth, texheight); // Dropshadow if (useDropshadow && Event.current.type == EventType.Repaint) { Rect borderPosition = new RectOffset(1, 1, 1, 1).Remove(ms_Constants.textureIconDropShadow.border.Add(r)); ms_Constants.textureIconDropShadow.Draw(borderPosition, GUIContent.none, false, false, false, false); } GUI.DrawTexture(r, tex, ScaleMode.ScaleToFit, true); } public static Texture2D GetPreview(string previewPath) { if (previewPath != s_LastPreviewPath) { s_LastPreviewPath = previewPath; LoadTexture(previewPath, ref s_Preview); } return s_Preview; } static bool ValidateInput(ImportPackageItem[] items) { string errorMessage; if (!IsAllFilePathsValid(items, out errorMessage)) { errorMessage += "\nDo you want to import the valid file paths of the package or cancel importing?"; return EditorUtility.DisplayDialog("Invalid file path found", errorMessage, "Import", "Cancel importing"); } return true; } static bool IsAllFilePathsValid(ImportPackageItem[] assetItems, out string errorMessage) { foreach (var item in assetItems) { if (item.isFolder) continue; char invalidChar; int invalidCharIndex; if (HasInvalidCharInFilePath(item.destinationAssetPath, out invalidChar, out invalidCharIndex)) { errorMessage = string.Format("Invalid character found in file path: '{0}'. Invalid ascii value: {1} (at character index {2}).", item.destinationAssetPath, (int)invalidChar, invalidCharIndex); return false; } } errorMessage = ""; return true; } static bool HasInvalidCharInFilePath(string filePath, out char invalidChar, out int invalidCharIndex) { for (int i = 0; i < filePath.Length; ++i) { char c = filePath[i]; if (s_InvalidPathChars.Contains(c)) { invalidChar = c; invalidCharIndex = i; return true; } } invalidChar = ' '; invalidCharIndex = -1; return false; } public static bool HasInvalidCharInFilePath(string filePath) { char invalidChar; int invalidCharIndex; return HasInvalidCharInFilePath(filePath, out invalidChar, out invalidCharIndex); } } [Serializable] internal sealed class PackageImportWizard : ScriptableSingleton<PackageImportWizard> { [SerializeField] private PackageImport m_ImportWindow; [SerializeField] private string m_PackagePath; [SerializeField] private string m_PackageIconPath; [SerializeField] private string m_PackageName; [SerializeField] private ImportPackageItem[] m_InitialImportItems; [SerializeField] private List<ImportPackageItem> m_AssetContentItems; [SerializeField] private List<ImportPackageItem> m_ProjectSettingItems; [SerializeField] private bool m_IsMultiStepWizard; public bool IsMultiStepWizard => m_IsMultiStepWizard; [SerializeField] private bool m_IsProjectSettingStep; public bool IsProjectSettingStep => m_IsProjectSettingStep; private AssetOrigin m_AssetOrigin; public void StartImport(string packagePath, ImportPackageItem[] items, string packageIconPath, AssetOrigin origin) { ClearImportData(); m_PackagePath = packagePath; m_PackageIconPath = packageIconPath; m_PackageName = System.IO.Path.GetFileNameWithoutExtension(packagePath); m_AssetOrigin = origin; m_InitialImportItems = items; foreach (var item in items) { // We don't want to add `ProjectVersion.txt` since it would override the project Editor version and if it's a lower version, it would be downgraded if (item.destinationAssetPath == "ProjectSettings/ProjectVersion.txt") continue; if (item.destinationAssetPath.StartsWith("ProjectSettings/")) m_ProjectSettingItems.Add(item); else m_AssetContentItems.Add(item); } m_IsMultiStepWizard = m_AssetContentItems.Any() && m_ProjectSettingItems.Any(); if (m_AssetContentItems.Any()) ShowImportWindow(m_AssetContentItems.ToArray()); else if (m_ProjectSettingItems.Any()) { m_IsProjectSettingStep = true; ShowImportWindow(m_ProjectSettingItems.ToArray()); } } public void DoNextStep(ImportPackageItem[] importPackageItems) { if (IsProjectSettingStep) m_ProjectSettingItems = new List<ImportPackageItem>(importPackageItems); else m_AssetContentItems = new List<ImportPackageItem>(importPackageItems); if (!IsMultiStepWizard || IsProjectSettingStep) FinishImport(); else { m_IsProjectSettingStep = true; ShowImportWindow(m_ProjectSettingItems.ToArray()); } } public void DoPreviousStep(ImportPackageItem[] importPackageItems) { if (!IsProjectSettingStep || !IsMultiStepWizard) return; m_ProjectSettingItems = new List<ImportPackageItem>(importPackageItems); m_IsProjectSettingStep = false; ShowImportWindow(m_AssetContentItems.ToArray()); } public void CancelImport() { PackageUtility.ImportPackageAssetsCancelledFromGUI(m_PackageName, m_InitialImportItems); CloseImportWindow(); } public void CloseImportWindow() { if (m_ImportWindow != null) { ClearImportData(); m_ImportWindow.Close(); GUIUtility.ExitGUI(); } } private void ShowImportWindow(ImportPackageItem[] items) { m_ImportWindow = PackageImport.GetWindow<PackageImport>(true, "Import Unity Package"); m_ImportWindow.Init(m_PackagePath, items, m_PackageIconPath); } private void FinishImport() { PackageUtility.ImportPackageAssetsWithOrigin(m_AssetOrigin, m_AssetContentItems.Concat(m_ProjectSettingItems).ToArray()); CloseImportWindow(); } private void ClearImportData() { m_PackagePath = string.Empty; m_PackageIconPath = string.Empty; m_PackageName = string.Empty; m_InitialImportItems = null; m_AssetContentItems = new List<ImportPackageItem>(); m_ProjectSettingItems = new List<ImportPackageItem>(); m_IsMultiStepWizard = false; m_IsProjectSettingStep = false; } } }
UnityCsReference/Editor/Mono/GUI/PackageImport.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUI/PackageImport.cs", "repo_id": "UnityCsReference", "token_count": 9326 }
300
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using UnityEngine.Serialization; namespace UnityEditor { /// *undocumented* [System.Serializable] internal class SplitterState : ISerializationCallbackReceiver { const int defaultSplitSize = 6; public int ID; public float splitterInitialOffset; public int currentActiveSplitter = -1; public float[] realSizes; public float[] relativeSizes; // these should always add up to 1 public float[] minSizes; public float[] maxSizes; public float lastTotalSize = 0; public float splitSize; public float xOffset; [SerializeField] int m_Version; #pragma warning disable CS0649 [SerializeField] [FormerlySerializedAs("realSizes")] int[] oldRealSizes; [SerializeField] [FormerlySerializedAs("minSizes")] int[] oldMinSizes; [SerializeField] [FormerlySerializedAs("maxSizes")] int[] oldMaxSizes; [SerializeField] [FormerlySerializedAs("splitSize")] int oldSplitSize; #pragma warning restore CS0649 #region Old Constructors // In the past, pixelsPerPoint was always 1, so points could be stored as ints. With the introduction of high-dpi // and arbitrary scaling, the implementation has been changed to store floats. For backwards compatibility, the // old constructors remain available but are NOT recommended anymore, since they imply a conversion from int[] to // float[]. Consider using the static functions FromAbsolute and FromRelative instead. public SplitterState(params float[] relativeSizes) { InitFromRelative(relativeSizes, null, null, 0); } static System.Converter<int, float> s_ConverterDelegate = CastIntToFloat; static float CastIntToFloat(int input) { return (float)input; } public SplitterState(int[] realSizes, int[] minSizes, int[] maxSizes) { InitFromAbsolute( System.Array.ConvertAll(realSizes, s_ConverterDelegate), minSizes == null ? null : System.Array.ConvertAll(minSizes, s_ConverterDelegate), maxSizes == null ? null : System.Array.ConvertAll(maxSizes, s_ConverterDelegate)); } public SplitterState(float[] relativeSizes, int[] minSizes, int[] maxSizes) { InitFromRelative( relativeSizes, minSizes == null ? null : System.Array.ConvertAll(minSizes, s_ConverterDelegate), maxSizes == null ? null : System.Array.ConvertAll(maxSizes, s_ConverterDelegate), 0); } public SplitterState(float[] relativeSizes, int[] minSizes, int[] maxSizes, int splitSize) { InitFromRelative( relativeSizes, minSizes == null ? null : System.Array.ConvertAll(minSizes, s_ConverterDelegate), maxSizes == null ? null : System.Array.ConvertAll(maxSizes, s_ConverterDelegate), splitSize); } #endregion // Old Constructors SplitterState(bool useless) {} // A parameterless constructor would conflict with the obsolete params constructor. public static SplitterState FromAbsolute(float[] realSizes, float[] minSizes, float[] maxSizes) { var state = new SplitterState(false); state.InitFromAbsolute(realSizes, minSizes, maxSizes); return state; } public static SplitterState FromRelative(params float[] relativeSizes) { var state = new SplitterState(false); state.InitFromRelative(relativeSizes, null, null, 0); return state; } public static SplitterState FromRelative(float[] relativeSizes, float[] minSizes, float[] maxSizes) { var state = new SplitterState(false); state.InitFromRelative(relativeSizes, minSizes, maxSizes, 0); return state; } public static SplitterState FromRelative(float[] relativeSizes, float[] minSizes, float[] maxSizes, int splitSize) { var state = new SplitterState(false); state.InitFromRelative(relativeSizes, minSizes, maxSizes, splitSize); return state; } public bool IsValid() { return realSizes != null && minSizes != null && maxSizes != null && relativeSizes != null && realSizes.Length > 0 && minSizes.Length > 0 && maxSizes.Length > 0 && relativeSizes.Length > 0 && realSizes.Length == minSizes.Length && minSizes.Length == maxSizes.Length && maxSizes.Length == relativeSizes.Length; } void InitFromAbsolute(float[] realSizes, float[] minSizes, float[] maxSizes) { this.realSizes = realSizes; this.minSizes = minSizes ?? new float[realSizes.Length]; this.maxSizes = maxSizes ?? new float[realSizes.Length]; relativeSizes = new float[realSizes.Length]; splitSize = splitSize == 0 ? defaultSplitSize : splitSize; RealToRelativeSizes(); } void InitFromRelative(float[] relativeSizes, float[] minSizes, float[] maxSizes, int splitSize) { this.relativeSizes = relativeSizes; this.minSizes = minSizes == null ? new float[relativeSizes.Length] : minSizes; this.maxSizes = maxSizes == null ? new float[relativeSizes.Length] : maxSizes; realSizes = new float[relativeSizes.Length]; this.splitSize = splitSize == 0 ? defaultSplitSize : splitSize; NormalizeRelativeSizes(); } public void NormalizeRelativeSizes() { float check = 1.0f; // try to avoid rounding issues float total = 0; int k; // distribute space relatively for (k = 0; k < relativeSizes.Length; k++) total += relativeSizes[k]; for (k = 0; k < relativeSizes.Length; k++) { relativeSizes[k] = relativeSizes[k] / total; check -= relativeSizes[k]; } relativeSizes[relativeSizes.Length - 1] += check; } public void RealToRelativeSizes() { if (relativeSizes.Length == 0) return; float check = 1.0f; // try to avoid rounding issues float total = 0; int k; // distribute space relatively for (k = 0; k < realSizes.Length; k++) total += realSizes[k]; if (total > 0.001f) { for (k = 0; k < realSizes.Length; k++) { relativeSizes[k] = realSizes[k] / total; check -= relativeSizes[k]; } relativeSizes[relativeSizes.Length - 1] += check; } else { // Distribute evenly float relativeSize = 1f / relativeSizes.Length; for (k = 0; k < relativeSizes.Length; k++) relativeSizes[k] = relativeSize; } } public void RelativeToRealSizes(float totalSpace) { int k; float spaceToShare = totalSpace; for (k = 0; k < relativeSizes.Length; k++) { realSizes[k] = GUIUtility.RoundToPixelGrid(relativeSizes[k] * totalSpace); if (realSizes[k] < minSizes[k]) realSizes[k] = minSizes[k]; spaceToShare -= realSizes[k]; } if (spaceToShare < 0) { for (k = 0; k < relativeSizes.Length; k++) { if (realSizes[k] > minSizes[k]) { float spaceInThisOne = realSizes[k] - minSizes[k]; float spaceToTake = -spaceToShare < spaceInThisOne ? -spaceToShare : spaceInThisOne; spaceToShare += spaceToTake; realSizes[k] -= spaceToTake; if (spaceToShare >= 0) break; } } } int last = realSizes.Length - 1; if (last >= 0) { realSizes[last] += spaceToShare; // try to avoid rounding issues if (realSizes[last] < minSizes[last]) // but never ignore min size! realSizes[last] = minSizes[last]; } } public void DoSplitter(int i1, int i2, float diff) { // TODO: This does not handle all cases properly. Theres a hope we will not encounter those cases in the editor. // Needs to be fixed once its passed to users. float h1 = realSizes[i1]; float h2 = realSizes[i2]; float m1 = minSizes[i1]; float m2 = minSizes[i2]; float x1 = maxSizes[i1]; float x2 = maxSizes[i2]; bool diffed = false; if (m1 == 0) m1 = 16; if (m2 == 0) m2 = 16; // min constraint if (h1 + diff < m1) { diff -= m1 - h1; realSizes[i2] += realSizes[i1] - m1; realSizes[i1] = m1; if (realSizes[i2] < m2) { if (i2 != realSizes.Length - 1) DoSplitter(i2, i2 + 1, diff); else realSizes[i2] = m2; } if (i1 != 0) DoSplitter(i1 - 1, i2, diff); else // can't resize more... splitterInitialOffset -= diff; diffed = true; } else if (h2 - diff < m2) { diff -= h2 - m2; realSizes[i1] += realSizes[i2] - m2; realSizes[i2] = m2; if (realSizes[i1] < m1) { if (i1 != 0) DoSplitter(i1 - 1, i2, diff); else realSizes[i1] = m1; } if (i2 != realSizes.Length - 1) DoSplitter(i1, i2 + 1, diff); else // can't resize more... splitterInitialOffset -= diff; diffed = true; } // max constraint if (!diffed) { if ((x1 != 0) && (h1 + diff > x1)) { diff -= realSizes[i1] - x1; realSizes[i2] += realSizes[i1] - x1; realSizes[i1] = x1; if (i1 != 0) DoSplitter(i1 - 1, i2, diff); else // can't resize more... splitterInitialOffset -= diff; diffed = true; } else if ((x2 != 0) && (h2 - diff > x2)) { diff -= h2 - x2; realSizes[i1] += realSizes[i2] - x2; realSizes[i2] = x2; if (i2 != realSizes.Length - 1) DoSplitter(i1, i2 + 1, diff); else // can't resize more... splitterInitialOffset -= diff; diffed = true; } } // normal case - we have space for resizing if (!diffed) { realSizes[i1] += diff; realSizes[i2] -= diff; } } public void OnBeforeSerialize() { m_Version = 1; } static void ConvertOldArray(int[] oldArray, ref float[] newArray) { if ((newArray == null || newArray.Length == 0) && oldArray != null && oldArray.Length > 0) newArray = System.Array.ConvertAll(oldArray, s_ConverterDelegate); } public void OnAfterDeserialize() { if (m_Version == 0) { // Case 1241206: Convert int to float ConvertOldArray(oldMaxSizes, ref maxSizes); ConvertOldArray(oldMinSizes, ref minSizes); ConvertOldArray(oldRealSizes, ref realSizes); splitSize = oldSplitSize; } m_Version = 1; } } class SplitterGUILayout { static int splitterHash = "Splitter".GetHashCode(); /// *undocumented* internal class GUISplitterGroup : GUILayoutGroup { public SplitterState state; public override void SetHorizontal(float x, float width) { if (!isVertical) { int k; state.xOffset = x; float alignedWidth = GUIUtility.RoundToPixelGrid(width); if (alignedWidth != state.lastTotalSize) { state.RelativeToRealSizes(alignedWidth); state.lastTotalSize = alignedWidth; // maintain constraints while resizing for (k = 0; k < state.realSizes.Length - 1; k++) state.DoSplitter(k, k + 1, 0); } k = 0; foreach (GUILayoutEntry i in entries) { float thisSize = state.realSizes[k]; i.SetHorizontal(GUIUtility.RoundToPixelGrid(x), GUIUtility.RoundToPixelGrid(thisSize)); x += thisSize + spacing; k++; } } else { base.SetHorizontal(x, width); } } public override void SetVertical(float y, float height) { rect.y = y; rect.height = height; RectOffset padding = style.padding; if (isVertical) { // If we have a skin, adjust the sizing to take care of padding (if we don't have a skin the vertical margins have been propagated fully up the hierarchy)... if (style != GUIStyle.none) { float topMar = padding.top, bottomMar = padding.bottom; if (entries.Count != 0) { topMar = Mathf.Max(topMar, ((GUILayoutEntry)entries[0]).marginTop); bottomMar = Mathf.Max(bottomMar, ((GUILayoutEntry)entries[entries.Count - 1]).marginBottom); } y += topMar; height -= bottomMar + topMar; } // Set the positions int k; float alignedHeight = GUIUtility.RoundToPixelGrid(height); if (alignedHeight != state.lastTotalSize) { state.RelativeToRealSizes(alignedHeight); state.lastTotalSize = alignedHeight; // maintain constraints while resizing for (k = 0; k < state.realSizes.Length - 1; k++) state.DoSplitter(k, k + 1, 0); } k = 0; foreach (GUILayoutEntry i in entries) { float thisSize = state.realSizes[k]; i.SetVertical(GUIUtility.RoundToPixelGrid(y), GUIUtility.RoundToPixelGrid(thisSize)); y += thisSize + spacing; k++; } } else { // If we have a GUIStyle here, we need to respect the subelements' margins if (style != GUIStyle.none) { foreach (GUILayoutEntry i in entries) { float topMar = Mathf.Max(i.marginTop, padding.top); float thisY = y + topMar; float thisHeight = height - Mathf.Max(i.marginBottom, padding.bottom) - topMar; if (i.stretchHeight != 0) i.SetVertical(thisY, thisHeight); else i.SetVertical(thisY, Mathf.Clamp(thisHeight, i.minHeight, i.maxHeight)); } } else { // If not, the subelements' margins have already been propagated upwards to this group, so we can safely ignore them float thisY = y - marginTop; float thisHeight = height + marginVertical; foreach (GUILayoutEntry i in entries) { if (i.stretchHeight != 0) i.SetVertical(thisY + i.marginTop, thisHeight - i.marginVertical); else i.SetVertical(thisY + i.marginTop, Mathf.Clamp(thisHeight - i.marginVertical, i.minHeight, i.maxHeight)); } } } } } public static void BeginSplit(SplitterState state, GUIStyle style, bool vertical, params GUILayoutOption[] options) { float pos; var g = (GUISplitterGroup)GUILayoutUtility.BeginLayoutGroup(style, null, typeof(GUISplitterGroup)); state.ID = GUIUtility.GetControlID(splitterHash, FocusType.Passive); switch (Event.current.GetTypeForControl(state.ID)) { case EventType.Layout: { g.state = state; g.resetCoords = false; g.isVertical = vertical; g.ApplyOptions(options); break; } case EventType.MouseDown: { if ((Event.current.button == 0) && (Event.current.clickCount == 1)) { float cursor = GUIUtility.RoundToPixelGrid(g.isVertical ? g.rect.y : g.rect.x); pos = GUIUtility.RoundToPixelGrid(g.isVertical ? Event.current.mousePosition.y : Event.current.mousePosition.x); for (int i = 0; i < state.relativeSizes.Length - 1; i++) { Rect splitterRect = g.isVertical ? new Rect(state.xOffset + g.rect.x, cursor + state.realSizes[i] - state.splitSize / 2, g.rect.width, state.splitSize) : new Rect(state.xOffset + cursor + state.realSizes[i] - state.splitSize / 2, g.rect.y, state.splitSize, g.rect.height); if (GUIUtility.HitTest(splitterRect, Event.current)) { state.splitterInitialOffset = pos; state.currentActiveSplitter = i; GUIUtility.hotControl = state.ID; Event.current.Use(); break; } cursor = GUIUtility.RoundToPixelGrid(cursor + state.realSizes[i]); } } break; } case EventType.MouseDrag: { if ((GUIUtility.hotControl == state.ID) && (state.currentActiveSplitter >= 0)) { pos = g.isVertical ? Event.current.mousePosition.y : Event.current.mousePosition.x; GUIUtility.RoundToPixelGrid(pos); float diff = pos - state.splitterInitialOffset; if (diff != 0) { state.splitterInitialOffset = pos; state.DoSplitter(state.currentActiveSplitter, state.currentActiveSplitter + 1, diff); } Event.current.Use(); } break; } case EventType.MouseUp: { if (GUIUtility.hotControl == state.ID) { GUIUtility.hotControl = 0; state.currentActiveSplitter = -1; state.RealToRelativeSizes(); Event.current.Use(); } break; } case EventType.Repaint: { float cursor = GUIUtility.RoundToPixelGrid(g.isVertical ? g.rect.y : g.rect.x); for (var i = 0; i < state.relativeSizes.Length - 1; i++) { var splitterRect = g.isVertical ? new Rect(state.xOffset + g.rect.x, cursor + state.realSizes[i] - state.splitSize / 2, g.rect.width, state.splitSize) : new Rect(state.xOffset + cursor + state.realSizes[i] - state.splitSize / 2, g.rect.y, state.splitSize, g.rect.height); EditorGUIUtility.AddCursorRect(splitterRect, g.isVertical ? MouseCursor.ResizeVertical : MouseCursor.SplitResizeLeftRight, state.ID); cursor += state.realSizes[i]; } } break; } } public static void BeginHorizontalSplit(SplitterState state, params GUILayoutOption[] options) { BeginSplit(state, GUIStyle.none, false, options); } public static void BeginVerticalSplit(SplitterState state, params GUILayoutOption[] options) { BeginSplit(state, GUIStyle.none, true, options); } public static void BeginHorizontalSplit(SplitterState state, GUIStyle style, params GUILayoutOption[] options) { BeginSplit(state, style, false, options); } public static void BeginVerticalSplit(SplitterState state, GUIStyle style, params GUILayoutOption[] options) { BeginSplit(state, style, true, options); } public static void EndVerticalSplit() { GUILayoutUtility.EndLayoutGroup(); } public static void EndHorizontalSplit() { GUILayoutUtility.EndLayoutGroup(); } } }
UnityCsReference/Editor/Mono/GUI/Splitter.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUI/Splitter.cs", "repo_id": "UnityCsReference", "token_count": 12778 }
301
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor.IMGUI.Controls; using UnityEngine; using UnityEngine.SceneManagement; namespace UnityEditor { internal class GameObjectTreeViewItem : TreeViewItem { int m_ColorCode; Object m_ObjectPPTR; Scene m_UnityScene; // Lazy initialized together with icon. bool m_LazyInitializationDone; bool m_ShowPrefabModeButton; Texture2D m_OverlayIcon; Texture2D m_SelectedIcon; public GameObjectTreeViewItem(int id, int depth, TreeViewItem parent, string displayName) : base(id, depth, parent, displayName) { } public override string displayName { get { // Lazy initilize displayName if (base.displayName == null) { if (SubSceneGUI.IsUsingSubScenes()) { var subSceneHeaderName = SubSceneGUI.GetSubSceneHeaderText((GameObject)objectPPTR); if (subSceneHeaderName != null) { base.displayName = subSceneHeaderName; return base.displayName; } } if (m_ObjectPPTR != null) displayName = objectPPTR.name; else displayName = "deleted gameobject"; } return base.displayName; } set { base.displayName = value; } } virtual public int colorCode { get { return m_ColorCode; } set { m_ColorCode = value; } } virtual public Object objectPPTR { get { return m_ObjectPPTR; } set { m_ObjectPPTR = value; } } virtual public bool lazyInitializationDone { get { return m_LazyInitializationDone; } set { m_LazyInitializationDone = value; } } virtual public bool showPrefabModeButton { get { return m_ShowPrefabModeButton; } set { m_ShowPrefabModeButton = value; } } virtual public Texture2D overlayIcon { get { return m_OverlayIcon; } set { m_OverlayIcon = value; } } virtual public Texture2D selectedIcon { get { return m_SelectedIcon; } set { m_SelectedIcon = value; } } public bool isSceneHeader { get; set; } public Scene scene { get { return m_UnityScene; } set { m_UnityScene = value; } } } } // UnityEditor
UnityCsReference/Editor/Mono/GUI/TreeView/GameObjectTreeViewItem.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUI/TreeView/GameObjectTreeViewItem.cs", "repo_id": "UnityCsReference", "token_count": 1219 }
302
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEditorInternal; namespace UnityEditor.IMGUI.Controls { // TreeViewDataSource is a base abstract class for a data source for a TreeView. // Usage: // Override FetchData () and build the entire tree with m_RootItem as root. // Configure showRootItem and rootIsCollapsable as wanted // // Note: if dealing with very large trees use LazyTreeViewDataSource instead: it assumes that tree only contains visible items. internal abstract class TreeViewDataSource : ITreeViewDataSource { protected readonly TreeViewController m_TreeView; // TreeView using this data source protected TreeViewItem m_RootItem; protected IList<TreeViewItem> m_Rows; protected bool m_NeedRefreshRows = true; protected TreeViewItem m_FakeItem; public bool showRootItem { get; set; } public bool rootIsCollapsable { get; set; } public bool alwaysAddFirstItemToSearchResult { get; set; } // is only used in searches when showRootItem is false. It Doesn't make sense for visible roots public TreeViewItem root { get { return m_RootItem; } } public System.Action onVisibleRowsChanged; protected List<int> expandedIDs { get {return m_TreeView.state.expandedIDs; } set { m_TreeView.state.expandedIDs = value; } } public TreeViewDataSource(TreeViewController treeView) { m_TreeView = treeView; showRootItem = true; rootIsCollapsable = false; m_RootItem = null; onVisibleRowsChanged = null; } virtual public void OnInitialize() { } // Implement this function and build entire tree with m_RootItem as root public abstract void FetchData(); public virtual void ReloadData() { m_FakeItem = null; FetchData(); } virtual public TreeViewItem FindItem(int id) { return TreeViewUtility.FindItem(id, m_RootItem); } virtual public bool IsRevealed(int id) { IList<TreeViewItem> rows = GetRows(); return TreeViewController.GetIndexOfID(rows, id) >= 0; } virtual public void RevealItem(int id) { if (IsRevealed(id)) return; // Reveal (expand parents up to root) TreeViewItem item = FindItem(id); if (item != null) { TreeViewItem parent = item.parent; while (parent != null) { SetExpanded(parent, true); parent = parent.parent; } } } virtual public void RevealItems(int[] ids) { HashSet<int> expandedSet = new HashSet<int>(expandedIDs); int orgSize = expandedSet.Count; // Add all parents above id foreach (var id in ids) { if (IsRevealed(id)) continue; // Reveal (expand parents up to root) TreeViewItem item = FindItem(id); if (item != null) { TreeViewItem parent = item.parent; while (parent != null) { expandedSet.Add(parent.id); parent = parent.parent; } } } if (orgSize != expandedSet.Count) { // Bulk set expanded ids (is sorted in SetExpandedIDs) SetExpandedIDs(expandedSet.ToArray()); // Refresh immediately if any Item was expanded if (m_NeedRefreshRows) FetchData(); } } virtual public void OnSearchChanged() { m_NeedRefreshRows = true; } //---------------------------- // Visible Item section protected void GetVisibleItemsRecursive(TreeViewItem item, IList<TreeViewItem> items) { if (item != m_RootItem || showRootItem) items.Add(item); if (item.hasChildren && IsExpanded(item)) foreach (TreeViewItem child in item.children) GetVisibleItemsRecursive(child, items); } protected void SearchRecursive(TreeViewItem item, string search, IList<TreeViewItem> searchResult) { if (item.displayName.ToLower().Contains(search)) searchResult.Add(item); if (item.children != null) foreach (TreeViewItem child in item.children) SearchRecursive(child, search, searchResult); } virtual protected List<TreeViewItem> ExpandedRows(TreeViewItem root) { var result = new List<TreeViewItem>(); GetVisibleItemsRecursive(m_RootItem, result); return result; } // Searches the current tree by displayName. virtual protected List<TreeViewItem> Search(TreeViewItem root, string search) { var result = new List<TreeViewItem>(); if (showRootItem) { SearchRecursive(root, search, result); result.Sort(new TreeViewItemAlphaNumericSort()); } else { int startIndex = alwaysAddFirstItemToSearchResult ? 1 : 0; if (root.hasChildren) { for (int i = startIndex; i < root.children.Count; ++i) { SearchRecursive(root.children[i], search, result); } result.Sort(new TreeViewItemAlphaNumericSort()); if (alwaysAddFirstItemToSearchResult) result.Insert(0, root.children[0]); } } return result; } virtual public int rowCount { get { return GetRows().Count; } } virtual public int GetRow(int id) { var rows = GetRows(); for (int row = 0; row < rows.Count; ++row) { if (rows[row].id == id) return row; } return -1; } virtual public TreeViewItem GetItem(int row) { return GetRows()[row]; } // Get the flattend tree of visible items. virtual public IList<TreeViewItem> GetRows() { InitIfNeeded(); return m_Rows; } virtual public void InitIfNeeded() { // Cached for large trees... if (m_Rows == null || m_NeedRefreshRows) { if (m_RootItem != null) { if (m_TreeView.isSearching) m_Rows = Search(m_RootItem, m_TreeView.searchString.ToLower()); else m_Rows = ExpandedRows(m_RootItem); } else { Debug.LogError("TreeView root item is null. Ensure that your TreeViewDataSource sets up at least a root item."); m_Rows = new List<TreeViewItem>(); } m_NeedRefreshRows = false; // TODO: This should be named something like: 'onVisibleRowsReloaded' if (onVisibleRowsChanged != null) onVisibleRowsChanged(); // Expanded state has changed ensure that we repaint m_TreeView.Repaint(); } } public bool isInitialized { get { return m_RootItem != null && m_Rows != null; } } //---------------------------- // Expanded/collapsed section virtual public int[] GetExpandedIDs() { return expandedIDs.ToArray(); } virtual public void SetExpandedIDs(int[] ids) { expandedIDs = new List<int>(ids); expandedIDs.Sort(); m_NeedRefreshRows = true; OnExpandedStateChanged(); } virtual public bool IsExpanded(int id) { return expandedIDs.BinarySearch(id) >= 0; } virtual public bool SetExpanded(int id, bool expand) { bool expanded = IsExpanded(id); if (expand != expanded) { if (expand) { System.Diagnostics.Debug.Assert(!expandedIDs.Contains(id)); expandedIDs.Add(id); expandedIDs.Sort(); } else { expandedIDs.Remove(id); } m_NeedRefreshRows = true; OnExpandedStateChanged(); return true; } return false; } virtual public void SetExpandedWithChildren(int id, bool expand) { SetExpandedWithChildren(FindItem(id), expand); } virtual public void SetExpandedWithChildren(TreeViewItem fromItem, bool expand) { if (fromItem == null) { Debug.LogError("item is null"); return; } HashSet<int> parents = new HashSet<int>(); TreeViewUtility.GetParentsBelowItem(fromItem, parents); // Get existing expanded in hashset HashSet<int> oldExpandedSet = new HashSet<int>(expandedIDs); if (expand) oldExpandedSet.UnionWith(parents); else oldExpandedSet.ExceptWith(parents); // Bulk set expanded ids (is sorted in SetExpandedIDs) SetExpandedIDs(oldExpandedSet.ToArray()); } virtual public void SetExpanded(TreeViewItem item, bool expand) { SetExpanded(item.id, expand); } virtual public bool IsExpanded(TreeViewItem item) { return IsExpanded(item.id); } virtual public bool IsExpandable(TreeViewItem item) { // Ignore expansion (foldout arrow) when showing search results if (m_TreeView.isSearching) return false; return item.hasChildren; } virtual public bool CanBeMultiSelected(TreeViewItem item) { return true; } virtual public bool CanBeParent(TreeViewItem item) { return true; } virtual public List<int> GetNewSelection(TreeViewItem clickedItem, TreeViewSelectState selectState) { // Get ids from items var visibleRows = GetRows(); List<int> allIDs = new List<int>(visibleRows.Count); for (int i = 0; i < visibleRows.Count; ++i) allIDs.Add(visibleRows[i].id); bool allowMultiselection = CanBeMultiSelected(clickedItem); return InternalEditorUtility.GetNewSelection(clickedItem.id, allIDs, selectState.selectedIDs, selectState.lastClickedID, selectState.keepMultiSelection, selectState.useShiftAsActionKey, allowMultiselection); } virtual public void OnExpandedStateChanged() { if (m_TreeView.expandedStateChanged != null) m_TreeView.expandedStateChanged(); } //---------------------------- // Renaming section virtual public bool IsRenamingItemAllowed(TreeViewItem item) { return true; } //---------------------------- // Insert tempoary Item section // Fake Item should be inserted into the m_VisibleRows (not the tree itself). virtual public void InsertFakeItem(int id, int parentID, string name, Texture2D icon) { Debug.LogError("InsertFakeItem missing implementation"); } virtual public bool HasFakeItem() { return m_FakeItem != null; } virtual public void RemoveFakeItem() { if (!HasFakeItem()) return; var visibleRows = GetRows(); int index = TreeViewController.GetIndexOfID(visibleRows, m_FakeItem.id); if (index != -1) { visibleRows.RemoveAt(index); } m_FakeItem = null; } } }
UnityCsReference/Editor/Mono/GUI/TreeView/TreeViewDataSource.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUI/TreeView/TreeViewDataSource.cs", "repo_id": "UnityCsReference", "token_count": 6402 }
303
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; namespace UnityEditor { public sealed partial class EditorGUI { internal class VUMeter { static Texture2D s_VerticalVUTexture; static Texture2D s_HorizontalVUTexture; const float VU_SPLIT = 0.9f; public struct SmoothingData { public float lastValue; public float peakValue; public float peakValueTime; } public static Texture2D verticalVUTexture { get { if (s_VerticalVUTexture == null) s_VerticalVUTexture = EditorGUIUtility.LoadIcon("VUMeterTextureVertical"); return s_VerticalVUTexture; } } public static Texture2D horizontalVUTexture { get { if (s_HorizontalVUTexture == null) s_HorizontalVUTexture = EditorGUIUtility.LoadIcon("VUMeterTextureHorizontal"); return s_HorizontalVUTexture; } } public static void HorizontalMeter(Rect position, float value, float peak, Texture2D foregroundTexture, Color peakColor) { if (Event.current.type != EventType.Repaint) return; Color temp = GUI.color; // Draw background EditorStyles.progressBarBack.Draw(position, false, false, false, false); // Draw foreground GUI.color = new Color(1f, 1f, 1f, GUI.enabled ? 1 : 0.5f); float width = position.width * value - 2; if (width < 2) width = 2; Rect newRect = new Rect(position.x + 1, position.y + 1, width, position.height - 2); Rect uvRect = new Rect(0, 0, value, 1); GUI.DrawTextureWithTexCoords(newRect, foregroundTexture, uvRect); // Draw peak indicator GUI.color = peakColor; float peakpos = position.width * peak - 2; if (peakpos < 2) peakpos = 2; newRect = new Rect(position.x + peakpos, position.y + 1, 1, position.height - 2); GUI.DrawTexture(newRect, EditorGUIUtility.whiteTexture, ScaleMode.StretchToFill); // Reset color GUI.color = temp; } public static void VerticalMeter(Rect position, float value, float peak, Texture2D foregroundTexture, Color peakColor) { if (Event.current.type != EventType.Repaint) return; Color temp = GUI.color; // Draw background EditorStyles.progressBarBack.Draw(position, false, false, false, false); // Draw foreground GUI.color = new Color(1f, 1f, 1f, GUI.enabled ? 1 : 0.5f); float height = (position.height - 2) * value; if (height < 2) height = 2; Rect newRect = new Rect(position.x + 1, (position.y + position.height - 1) - height, position.width - 2, height); Rect uvRect = new Rect(0, 0, 1, value); GUI.DrawTextureWithTexCoords(newRect, foregroundTexture, uvRect); // Draw peak indicator GUI.color = peakColor; float peakpos = (position.height - 2) * peak; if (peakpos < 2) peakpos = 2; newRect = new Rect(position.x + 1, (position.y + position.height - 1) - peakpos, position.width - 2, 1); GUI.DrawTexture(newRect, EditorGUIUtility.whiteTexture, ScaleMode.StretchToFill); // Reset color GUI.color = temp; } // Auto smoothing version public static void HorizontalMeter(Rect position, float value, ref SmoothingData data, Texture2D foregroundTexture, Color peakColor) { if (Event.current.type != EventType.Repaint) return; float renderValue, renderPeak; SmoothVUMeterData(ref value, ref data, out renderValue, out renderPeak); HorizontalMeter(position, renderValue, renderPeak, foregroundTexture, peakColor); } // Auto smoothing version public static void VerticalMeter(Rect position, float value, ref SmoothingData data, Texture2D foregroundTexture, Color peakColor) { if (Event.current.type != EventType.Repaint) return; float renderValue, renderPeak; SmoothVUMeterData(ref value, ref data, out renderValue, out renderPeak); VerticalMeter(position, renderValue, renderPeak, foregroundTexture, peakColor); } static void SmoothVUMeterData(ref float value, ref SmoothingData data, out float renderValue, out float renderPeak) { if (value <= data.lastValue) { value = Mathf.Lerp(data.lastValue, value, Time.smoothDeltaTime * 7.0f); } else { value = Mathf.Lerp(value, data.lastValue, Time.smoothDeltaTime * 2.0f); data.peakValue = value; data.peakValueTime = Time.realtimeSinceStartup; } if (value > 1.0f / VU_SPLIT) value = 1.0f / VU_SPLIT; if (data.peakValue > 1.0f / VU_SPLIT) data.peakValue = 1.0f / VU_SPLIT; renderValue = value * VU_SPLIT; renderPeak = data.peakValue * VU_SPLIT; data.lastValue = value; } } // VUMeter } // UnityGUI } // UnityEditor
UnityCsReference/Editor/Mono/GUI/VUMeter.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUI/VUMeter.cs", "repo_id": "UnityCsReference", "token_count": 3132 }
304
// 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.Runtime.InteropServices; using System; using UnityEngine.Scripting; using FrameCapture = UnityEngine.Apple.FrameCapture; using FrameCaptureDestination = UnityEngine.Apple.FrameCaptureDestination; using UnityEngine.UIElements; namespace UnityEditor { // This is what we (not users) derive from to create various views. (Main Toolbar, etc.) [StructLayout(LayoutKind.Sequential)] internal partial class GUIView : View, IWindowModel { internal static event Action<GUIView> positionChanged = null; int m_DepthBufferBits = 0; int m_AntiAliasing = 1; bool m_ResetPanelRenderingOnAssetChange = true; bool m_AutoRepaintOnSceneChange = false; private IWindowBackend m_WindowBackend; protected EventInterests m_EventInterests; internal bool SendEvent(Event e) { int depth = SavedGUIState.Internal_GetGUIDepth(); if (depth > 0) { SavedGUIState oldState = SavedGUIState.Create(); var retval = Internal_SendEvent(e); oldState.ApplyAndForget(); return retval; } { var retval = Internal_SendEvent(e); return retval; } } // Call into C++ here to move the underlying NSViews around internal override void SetWindow(ContainerWindow win) { ContainerWindow oldWindow = this.window; base.SetWindow(win); // Sets this.window(m_Window) to win try { bool isPlayModeView = false; if (this is HostView h) isPlayModeView = h.actualView is PlayModeView; Internal_Init(m_DepthBufferBits, m_AntiAliasing, isPlayModeView); } catch { parent?.RemoveChild(this); throw; } if (!win) { // Tell the native ContainerWindow we were attached to that we // are no longer attached to it. Internal_UnsetWindow(oldWindow); } else { Internal_SetWindow(win); } Internal_SetAutoRepaint(m_AutoRepaintOnSceneChange); Internal_SetPosition(windowPosition); Internal_SetWantsMouseMove(m_EventInterests.wantsMouseMove); Internal_SetWantsMouseEnterLeaveWindow(m_EventInterests.wantsMouseMove); windowBackend?.SizeChanged(); } internal void RecreateContext() { Internal_Recreate(m_DepthBufferBits, m_AntiAliasing); } Vector2 IWindowModel.size => windowPosition.size; protected VisualElement visualTree => (VisualElement)(windowBackend?.visualTree); public EventInterests eventInterests { get { return m_EventInterests; } set { m_EventInterests = value; windowBackend?.EventInterestsChanged(); Internal_SetWantsMouseMove(wantsMouseMove); Internal_SetWantsMouseEnterLeaveWindow(wantsMouseEnterLeaveWindow); } } Action IWindowModel.onGUIHandler => OldOnGUI; public bool wantsMouseMove { get { return m_EventInterests.wantsMouseMove; } set { m_EventInterests.wantsMouseMove = value; windowBackend?.EventInterestsChanged(); Internal_SetWantsMouseMove(wantsMouseMove); } } public bool wantsMouseEnterLeaveWindow { get { return m_EventInterests.wantsMouseEnterLeaveWindow; } set { m_EventInterests.wantsMouseEnterLeaveWindow = value; windowBackend?.EventInterestsChanged(); Internal_SetWantsMouseEnterLeaveWindow(wantsMouseEnterLeaveWindow); } } public bool autoRepaintOnSceneChange { get { return m_AutoRepaintOnSceneChange; } set { m_AutoRepaintOnSceneChange = value; Internal_SetAutoRepaint(m_AutoRepaintOnSceneChange); } } public int depthBufferBits { get { return m_DepthBufferBits; } set { m_DepthBufferBits = value; } } public int antiAliasing { get { return m_AntiAliasing; } set { m_AntiAliasing = value; } } [Obsolete("AA is not supported on GUIViews", false)] public int antiAlias { get { return 1; } set { throw new NotSupportedException("AA is not supported on GUIViews"); } } public bool resetPanelRenderingOnAssetChange { get => m_ResetPanelRenderingOnAssetChange; set { if (m_ResetPanelRenderingOnAssetChange != value) { m_ResetPanelRenderingOnAssetChange = value; windowBackend?.ResetPanelRenderingOnAssetChangeChanged(); } } } internal IWindowBackend windowBackend { get { return m_WindowBackend; } set { if (m_WindowBackend != null) m_WindowBackend.OnDestroy(this); m_WindowBackend = value; m_WindowBackend?.OnCreate(this); // When the native side has triggered OnBackingScaleFactorChanged, it will not send it again even if we are adding view to a hostView. // (Docking, domain reload) // It also occurs that the event is sent when the backend is not yet set in the view // lets trigger the sizeChanged and OnBackingScaleFactorChanged to remedy any scenario windowBackend?.SizeChanged(); } } IWindowBackend IWindowModel.windowBackend { get { return windowBackend; } set { windowBackend = value; } } protected virtual void OnEnable() { windowBackend = EditorWindowBackendManager.GetBackend(this); } protected virtual void OnDisable() { windowBackend = null; } internal void ValidateWindowBackendForCurrentView() { if (!EditorWindowBackendManager.IsBackendCompatible(windowBackend, this)) { //We create a new compatible backend windowBackend = EditorWindowBackendManager.GetBackend(this); } } protected virtual void OldOnGUI() {} // Without leaving this in here for MonoBehaviour::DoGUI(), GetMethod(MonoScriptCache::kGUI) will return null. // In that case, commands are not delegated (e.g., keyboard-based delete in Hierarchy/Project) protected virtual void OnGUI() {} protected virtual void OnBackingScaleFactorChanged() { windowBackend?.OnBackingScaleFactorChanged(); } protected override void SetPosition(Rect newPos) { Rect oldWinPos = windowPosition; base.SetPosition(newPos); if (oldWinPos == windowPosition) { Internal_SetPosition(windowPosition); return; } Internal_SetPosition(windowPosition); windowBackend?.SizeChanged(); positionChanged?.Invoke(this); Repaint(); } protected override void OnDestroy() { Internal_Close(); base.OnDestroy(); } [RequiredByNativeCode] internal string GetViewName() { var hostView = this as HostView; if (hostView != null && hostView.actualView != null) return hostView.actualView.GetType().Name; return GetType().Name; } [RequiredByNativeCode] internal static string GetTypeNameOfMostSpecificActiveView() { var currentView = current; if (currentView == null) return string.Empty; var hostView = currentView as HostView; if (hostView != null && hostView.actualView != null) return hostView.actualView.GetType().FullName; return currentView.GetType().FullName; } public static void BeginOffsetArea(Rect screenRect, GUIContent content, GUIStyle style) { GUILayoutGroup g = EditorGUILayoutUtilityInternal.BeginLayoutArea(style, typeof(GUILayoutGroup)); switch (Event.current.type) { case EventType.Layout: g.resetCoords = false; g.minWidth = g.maxWidth = screenRect.width; g.minHeight = g.maxHeight = screenRect.height; g.rect = Rect.MinMaxRect(0, 0, g.rect.xMax, g.rect.yMax); break; } GUI.BeginGroup(screenRect, content, style); } public static void EndOffsetArea() { GUILayoutUtility.EndLayoutGroup(); GUI.EndGroup(); } // we already have renderdoc integration done in GUIView but in cpp // for metal we need a bit more convoluted logic and we can push more things to cs internal void CaptureMetalScene() { if (FrameCapture.IsDestinationSupported(FrameCaptureDestination.DevTools)) { FrameCapture.BeginCaptureToXcode(); RenderCurrentSceneForCapture(); FrameCapture.EndCapture(); } else if (FrameCapture.IsDestinationSupported(FrameCaptureDestination.GPUTraceDocument)) { string path = EditorUtility.SaveFilePanel("Save Metal GPU Capture", "", PlayerSettings.productName + ".gputrace", "gputrace"); if (System.String.IsNullOrEmpty(path)) return; FrameCapture.BeginCaptureToFile(path); RenderCurrentSceneForCapture(); FrameCapture.EndCapture(); System.Console.WriteLine("Metal capture saved to " + path); System.Diagnostics.Process.Start(System.IO.Path.GetDirectoryName(path)); } } static readonly Action<TextElement> k_QueryMarkDirty = MarkDirtyRepaint; static void MarkDirtyRepaint(TextElement v) { v.MarkDirtyRepaint(); } internal void RepaintUITKText() { visualTree.Query<TextElement>().ForEach(k_QueryMarkDirty); } [RequiredByNativeCode] private void SetActiveWindowAsPresented() { if ((this is HostView h) && h.actualView) { h.actualView.m_IsPresented = true; } } } } //namespace
UnityCsReference/Editor/Mono/GUIView.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUIView.cs", "repo_id": "UnityCsReference", "token_count": 5311 }
305
// Unity 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 System.Runtime.InteropServices; using UnityEngine; using UnityEditor.Experimental; #pragma warning disable 649 #pragma warning disable 169 namespace UnityEditor { [Serializable] [NativeHeader("Editor/Src/GlobalObjectId.h")] public struct GlobalObjectId : IEquatable<GlobalObjectId>, IComparable<GlobalObjectId> { internal SceneObjectIdentifier m_SceneObjectIdentifier; internal GUID m_AssetGUID; internal int m_IdentifierType; internal enum IdentifierType { NullIdentifier = 0, ImportedAsset = 1, SceneObject = 2, SourceAsset = 3, BuiltInAsset = 4 }; public ulong targetObjectId { get { return m_SceneObjectIdentifier.TargetObject; } } public ulong targetPrefabId { get { return m_SceneObjectIdentifier.TargetPrefab; } } public GUID assetGUID { get { return m_AssetGUID; } } public int identifierType { get { return m_IdentifierType; } } // Converts an Object reference to a global unique ID [FreeFunction] extern public static GlobalObjectId GetGlobalObjectIdSlow(UnityEngine.Object targetObject); [FreeFunction] extern public static void GetGlobalObjectIdsSlow(UnityEngine.Object[] objects, [Out] GlobalObjectId[] outputIdentifiers); // Converts an Object reference to a global unique ID public static GlobalObjectId GetGlobalObjectIdSlow(int instanceId) { return GetGlobalObjectIdFromInstanceIdSlow(instanceId); } public static void GetGlobalObjectIdsSlow(int[] instanceIds, [Out] GlobalObjectId[] outputIdentifiers) { GetGlobalObjectIdsFromInstanceIdsSlow(instanceIds, outputIdentifiers); } // Converts an Object reference to a global unique ID [FreeFunction] extern static GlobalObjectId GetGlobalObjectIdFromInstanceIdSlow(int instanceId); [FreeFunction] extern static void GetGlobalObjectIdsFromInstanceIdsSlow(int[] instanceIds, [Out] GlobalObjectId[] outputIdentifiers); override public string ToString() { return string.Format("GlobalObjectId_V1-{0}-{1}-{2}-{3}", m_IdentifierType, m_AssetGUID, m_SceneObjectIdentifier.TargetObject, m_SceneObjectIdentifier.TargetPrefab); } public bool Equals(GlobalObjectId other) { return m_SceneObjectIdentifier.Equals(other.m_SceneObjectIdentifier) && m_AssetGUID == other.m_AssetGUID && m_IdentifierType == other.m_IdentifierType; } public int CompareTo(GlobalObjectId other) { if (m_AssetGUID != other.m_AssetGUID) return m_AssetGUID.CompareTo(other.assetGUID); if (!m_SceneObjectIdentifier.Equals(other.m_SceneObjectIdentifier)) return m_SceneObjectIdentifier.CompareTo(other.m_SceneObjectIdentifier); if (m_IdentifierType != other.m_IdentifierType) return m_IdentifierType.CompareTo(m_IdentifierType); return 0; } public static bool TryParse(string stringValue, out GlobalObjectId id) { id = new GlobalObjectId(); string[] tokens = stringValue.Split('-'); if (tokens.Length != 5 || !string.Equals(tokens[0], "GlobalObjectId_V1", StringComparison.Ordinal)) return false; if (!int.TryParse(tokens[1], out var identifierType) || !GUID.TryParse(tokens[2], out var assetGUID) || !ulong.TryParse(tokens[3], out var targetObject) || !ulong.TryParse(tokens[4], out var targetPrefab)) return false; id.m_IdentifierType = identifierType; id.m_AssetGUID = assetGUID; id.m_SceneObjectIdentifier = new SceneObjectIdentifier { TargetObject = targetObject, TargetPrefab = targetPrefab }; return true; } // Converting one object at a time is incredibly slow. (Have to iterate whole scene to grab one object...) // Always prefer using batch API when multiple objects need to be looked up. [FreeFunction] extern public static UnityEngine.Object GlobalObjectIdentifierToObjectSlow(GlobalObjectId id); [FreeFunction] extern public static void GlobalObjectIdentifiersToObjectsSlow(GlobalObjectId[] identifiers, [Out] UnityEngine.Object[] outputObjects); // Converting one object at a time is incredibly slow. (Have to iterate whole scene to grab one object...) // Always prefer using batch API when multiple objects need to be looked up. [FreeFunction] extern public static int GlobalObjectIdentifierToInstanceIDSlow(GlobalObjectId id); [FreeFunction] extern public static void GlobalObjectIdentifiersToInstanceIDsSlow(GlobalObjectId[] identifiers, [Out] int[] outputInstanceIDs); } }
UnityCsReference/Editor/Mono/GlobalObjectId.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GlobalObjectId.bindings.cs", "repo_id": "UnityCsReference", "token_count": 2042 }
306
// 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 UnityEditor.Snap; namespace UnityEditor.IMGUI.Controls { public abstract class PrimitiveBoundsHandle { [Flags] public enum Axes { None = 0, X = 1 << 0, Y = 1 << 1, Z = 1 << 2, All = X | Y | Z } protected enum HandleDirection { PositiveX, NegativeX, PositiveY, NegativeY, PositiveZ, NegativeZ } private static readonly float s_DefaultMidpointHandleSize = 0.03f; private static readonly int[] s_NextAxis = new[] { 1, 2, 0 }; internal static GUIContent editModeButton { get { if (s_EditModeButton == null) { s_EditModeButton = new GUIContent( EditorGUIUtility.IconContent("EditCollider").image, EditorGUIUtility.TrTextContent("Edit bounding volume.\n\n - Hold Alt after clicking control handle to pin center in place.\n - Hold Shift after clicking control handle to scale uniformly.").text ); } return s_EditModeButton; } } private static GUIContent s_EditModeButton; public static float DefaultMidpointHandleSizeFunction(Vector3 position) { return HandleUtility.GetHandleSize(position) * s_DefaultMidpointHandleSize; } private int[] m_ControlIDs = new int[6] { 0, 0, 0, 0, 0, 0 }; private Bounds m_Bounds; private Bounds m_BoundsOnClick; public Vector3 center { get { return m_Bounds.center; } set { m_Bounds.center = value; } } public Axes axes { get; set; } public Color handleColor { get; set; } public Color wireframeColor { get; set; } public Handles.CapFunction midpointHandleDrawFunction { get; set; } public Handles.SizeFunction midpointHandleSizeFunction { get; set; } [Obsolete("Use parameterless constructor instead.")] public PrimitiveBoundsHandle(int controlIDHint) : this() {} public PrimitiveBoundsHandle() { handleColor = Color.white; wireframeColor = Color.white; axes = Axes.X | Axes.Y | Axes.Z; midpointHandleDrawFunction = Handles.DotHandleCap; midpointHandleSizeFunction = DefaultMidpointHandleSizeFunction; } public void SetColor(Color color) { handleColor = color; wireframeColor = color; } public void DrawHandle() { for (int i = 0, count = m_ControlIDs.Length; i < count; ++i) m_ControlIDs[i] = GUIUtility.GetControlID(GetHashCode(), FocusType.Passive); // wireframe (before handles so handles are rendered top most) using (new Handles.DrawingScope(Handles.color * wireframeColor)) DrawWireframe(); // unless holding alt to pin center, exit before drawing control handles when holding alt, since alt-click will rotate scene view if (Event.current.alt) { bool exit = true; foreach (var id in m_ControlIDs) { if (id == GUIUtility.hotControl) { exit = false; break; } } if (exit) return; } // bounding box extents Vector3 minPos = m_Bounds.min; Vector3 maxPos = m_Bounds.max; // handles int prevHotControl = GUIUtility.hotControl; bool isCameraInsideBox = Camera.current != null && m_Bounds.Contains(Handles.inverseMatrix.MultiplyPoint(Camera.current.transform.position)); EditorGUI.BeginChangeCheck(); using (new Handles.DrawingScope(Handles.color * handleColor)) { if (Handles.color.a > 0) MidpointHandles(ref minPos, ref maxPos, isCameraInsideBox); } bool changed = EditorGUI.EndChangeCheck(); // detect if any handles got hotControl if (prevHotControl != GUIUtility.hotControl && GUIUtility.hotControl != 0) { m_BoundsOnClick = m_Bounds; } // update if changed if (changed) { // determine which handle changed to apply any further modifications m_Bounds.center = (maxPos + minPos) * 0.5f; m_Bounds.size = maxPos - minPos; for (int i = 0, count = m_ControlIDs.Length; i < count; ++i) { if (GUIUtility.hotControl == m_ControlIDs[i]) m_Bounds = OnHandleChanged((HandleDirection)i, m_BoundsOnClick, m_Bounds); } // shift scales uniformly if (Event.current.shift) { int hotControl = GUIUtility.hotControl; Vector3 size = m_Bounds.size; int scaleAxis = 0; if (hotControl == m_ControlIDs[(int)HandleDirection.PositiveY] || hotControl == m_ControlIDs[(int)HandleDirection.NegativeY]) { scaleAxis = 1; } if (hotControl == m_ControlIDs[(int)HandleDirection.PositiveZ] || hotControl == m_ControlIDs[(int)HandleDirection.NegativeZ]) { scaleAxis = 2; } if (Mathf.Approximately(m_BoundsOnClick.size[scaleAxis], 0f)) { if (m_BoundsOnClick.size == Vector3.zero) size = Vector3.one * size[scaleAxis]; } else { var scaleFactor = size[scaleAxis] / m_BoundsOnClick.size[scaleAxis]; var nextAxis = s_NextAxis[scaleAxis]; size[nextAxis] = scaleFactor * m_BoundsOnClick.size[nextAxis]; nextAxis = s_NextAxis[nextAxis]; size[nextAxis] = scaleFactor * m_BoundsOnClick.size[nextAxis]; } m_Bounds.size = size; } // alt scales from the center if (Event.current.alt) m_Bounds.center = m_BoundsOnClick.center; } } protected abstract void DrawWireframe(); protected virtual Bounds OnHandleChanged(HandleDirection handle, Bounds boundsOnClick, Bounds newBounds) { return newBounds; } protected Vector3 GetSize() { Vector3 size = m_Bounds.size; // zero out size on disabled axes for (int axis = 0; axis < 3; ++axis) { if (!IsAxisEnabled(axis)) size[axis] = 0f; } return size; } protected void SetSize(Vector3 size) { m_Bounds.size = new Vector3(Mathf.Abs(size.x), Mathf.Abs(size.y), Mathf.Abs(size.z)); } protected bool IsAxisEnabled(Axes axis) { return (axes & axis) == axis; } protected bool IsAxisEnabled(int vector3Axis) { switch (vector3Axis) { case 0: return IsAxisEnabled(Axes.X); case 1: return IsAxisEnabled(Axes.Y); case 2: return IsAxisEnabled(Axes.Z); default: throw new ArgumentOutOfRangeException("vector3Axis", "Must be 0, 1, or 2"); } } private void MidpointHandles(ref Vector3 minPos, ref Vector3 maxPos, bool isCameraInsideBox) { Vector3 xAxis = Vector3.right; Vector3 yAxis = Vector3.up; Vector3 zAxis = Vector3.forward; Vector3 middle = (maxPos + minPos) * 0.5f; Vector3 localPos, newPos; if (IsAxisEnabled(Axes.X)) { // +X localPos = new Vector3(maxPos.x, middle.y, middle.z); newPos = MidpointHandle(m_ControlIDs[(int)HandleDirection.PositiveX], localPos, yAxis, zAxis, isCameraInsideBox); maxPos.x = Mathf.Max(newPos.x, minPos.x); // -X localPos = new Vector3(minPos.x, middle.y, middle.z); newPos = MidpointHandle(m_ControlIDs[(int)HandleDirection.NegativeX], localPos, yAxis, -zAxis, isCameraInsideBox); minPos.x = Mathf.Min(newPos.x, maxPos.x); } if (IsAxisEnabled(Axes.Y)) { // +Y localPos = new Vector3(middle.x, maxPos.y, middle.z); newPos = MidpointHandle(m_ControlIDs[(int)HandleDirection.PositiveY], localPos, xAxis, -zAxis, isCameraInsideBox); maxPos.y = Mathf.Max(newPos.y, minPos.y); // -Y localPos = new Vector3(middle.x, minPos.y, middle.z); newPos = MidpointHandle(m_ControlIDs[(int)HandleDirection.NegativeY], localPos, xAxis, zAxis, isCameraInsideBox); minPos.y = Mathf.Min(newPos.y, maxPos.y); } if (IsAxisEnabled(Axes.Z)) { // +Z localPos = new Vector3(middle.x, middle.y, maxPos.z); newPos = MidpointHandle(m_ControlIDs[(int)HandleDirection.PositiveZ], localPos, yAxis, -xAxis, isCameraInsideBox); maxPos.z = Mathf.Max(newPos.z, minPos.z); // -Z localPos = new Vector3(middle.x, middle.y, minPos.z); newPos = MidpointHandle(m_ControlIDs[(int)HandleDirection.NegativeZ], localPos, yAxis, xAxis, isCameraInsideBox); minPos.z = Mathf.Min(newPos.z, maxPos.z); } } private Vector3 MidpointHandle(int id, Vector3 localPos, Vector3 localTangent, Vector3 localBinormal, bool isCameraInsideBox) { Color oldColor = Handles.color; AdjustMidpointHandleColor(localPos, localTangent, localBinormal, isCameraInsideBox); if (Handles.color.a > 0f && midpointHandleDrawFunction != null) { Vector3 localDir = Vector3.Cross(localTangent, localBinormal).normalized; var size = midpointHandleSizeFunction == null ? 0f : midpointHandleSizeFunction(localPos); localPos = UnityEditorInternal.Slider1D.Do(id, localPos, localDir, size, midpointHandleDrawFunction, EditorSnapSettings.scale); } Handles.color = oldColor; return localPos; } private void AdjustMidpointHandleColor(Vector3 localPos, Vector3 localTangent, Vector3 localBinormal, bool isCameraInsideBox) { float alphaMultiplier = 1f; // if inside the box then ignore back facing alpha multiplier (otherwise all handles will look disabled) if (!isCameraInsideBox && axes == (Axes.X | Axes.Y | Axes.Z)) { // use tangent and binormal to calculate normal in case handle matrix is skewed Vector3 worldTangent = Handles.matrix.MultiplyVector(localTangent); Vector3 worldBinormal = Handles.matrix.MultiplyVector(localBinormal); Vector3 worldDir = Vector3.Cross(worldTangent, worldBinormal).normalized; // adjust color if handle is back facing float cosV; if (Camera.current.orthographic) cosV = Vector3.Dot(-Camera.current.transform.forward, worldDir); else cosV = Vector3.Dot((Camera.current.transform.position - Handles.matrix.MultiplyPoint(localPos)).normalized, worldDir); if (cosV < -0.0001f) alphaMultiplier *= Handles.backfaceAlphaMultiplier; } Handles.color *= new Color(1f, 1f, 1f, alphaMultiplier); } } }
UnityCsReference/Editor/Mono/Handles/BoundsHandle/PrimitiveBoundsHandle.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Handles/BoundsHandle/PrimitiveBoundsHandle.cs", "repo_id": "UnityCsReference", "token_count": 6442 }
307
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; namespace UnityEditor { public sealed partial class Handles { internal struct ScaleHandleIds { public static ScaleHandleIds @default { get { return new ScaleHandleIds( GUIUtility.GetControlID(s_xScaleHandleHash, FocusType.Passive), GUIUtility.GetControlID(s_yScaleHandleHash, FocusType.Passive), GUIUtility.GetControlID(s_zScaleHandleHash, FocusType.Passive), GUIUtility.GetControlID(s_xyzScaleHandleHash, FocusType.Passive) ); } } public readonly int x, y, z, xyz; public int this[int index] { get { switch (index) { case 0: return x; case 1: return y; case 2: return z; case 3: return xyz; } return -1; } } public bool Has(int id) { return x == id || y == id || z == id || xyz == id; } public ScaleHandleIds(int x, int y, int z, int xyz) { this.x = x; this.y = y; this.z = z; this.xyz = xyz; } public override int GetHashCode() { return x ^ y ^ z ^ xyz; } public override bool Equals(object obj) { if (!(obj is ScaleHandleIds)) return false; var o = (ScaleHandleIds)obj; return o.x == x && o.y == y && o.z == z && o.xyz == xyz; } } internal struct ScaleHandleParam { [Flags] public enum Handle { None = 0, X = 1 << 0, Y = 1 << 1, Z = 1 << 2, XYZ = 1 << 3, All = ~None } public enum Orientation { Signed, Camera } static ScaleHandleParam s_Default = new ScaleHandleParam((Handle)(-1), Vector3.zero, Vector3.one, Vector3.one, 1, Orientation.Signed); public static ScaleHandleParam Default { get { return s_Default; } set { s_Default = value; } } public readonly Vector3 axisOffset; public readonly Vector3 axisSize; public readonly Vector3 axisLineScale; public readonly float xyzSize; public readonly Handle handles; public readonly Orientation orientation; public bool ShouldShow(int axis) { return (handles & (Handle)(1 << axis)) != 0; } public bool ShouldShow(Handle handle) { return (handles & handle) != 0; } public ScaleHandleParam(Handle handles, Vector3 axisOffset, Vector3 axisSize, Vector3 axisLineScale, float xyzSize, Orientation orientation) { this.axisOffset = axisOffset; this.axisSize = axisSize; this.axisLineScale = axisLineScale; this.xyzSize = xyzSize; this.handles = handles; this.orientation = orientation; } } static Vector3 s_DoScaleHandle_AxisHandlesOctant = Vector3.one; static int[] s_DoScaleHandle_AxisDrawOrder = { 0, 1, 2 }; static float s_CurrentMultiplier; static Vector3 s_InitialScale; internal static float handleLength { get; set;} internal static bool proportionalScale { get; set; } public static Vector3 DoScaleHandle(Vector3 scale, Vector3 position, Quaternion rotation, float size) { return DoScaleHandle(ScaleHandleIds.@default, scale, position, rotation, size, ScaleHandleParam.Default, false); } internal static Vector3 DoScaleHandle(Vector3 scale, Vector3 position, Quaternion rotation, float size, bool isProportionalScale) { return DoScaleHandle(ScaleHandleIds.@default, scale, position, rotation, size, ScaleHandleParam.Default, isProportionalScale); } internal static Vector3 DoScaleHandle(ScaleHandleIds ids, Vector3 scale, Vector3 position, Quaternion rotation, float handleSize, ScaleHandleParam param, bool isProportionalScale = false) { // Calculate the camera view vector in Handle draw space // this handle the case where the matrix is skewed var handlePosition = matrix.MultiplyPoint3x4(position); var drawToWorldMatrix = matrix * Matrix4x4.TRS(position, rotation, Vector3.one); var invDrawToWorldMatrix = drawToWorldMatrix.inverse; var viewVectorDrawSpace = GetCameraViewFrom(handlePosition, invDrawToWorldMatrix); var isDisabled = !GUI.enabled; var isHot = ids.Has(GUIUtility.hotControl); var axisOffset = param.axisOffset; var axisLineScale = param.axisLineScale; // When an axis is hot, draw the line from the center to the handle // So ignore the offset if (isHot) { axisLineScale += axisOffset; axisOffset = Vector3.zero; } var isCenterIsHot = ids.xyz == GUIUtility.hotControl; VertexSnapping.HandleMouseMove(ids.xyz); switch (Event.current.type) { case EventType.MouseDown: s_InitialScale = scale == Vector3.zero ? Vector3.one : scale; s_CurrentMultiplier = 1.0f; break; case EventType.MouseDrag: if (isProportionalScale) proportionalScale = true; break; case EventType.MouseUp: proportionalScale = false; break; } CalcDrawOrder(viewVectorDrawSpace, s_DoScaleHandle_AxisDrawOrder); for (var ii = 0; ii < 3; ++ii) { int i = s_DoScaleHandle_AxisDrawOrder[ii]; int axisIndex = i; if (!param.ShouldShow(i)) continue; if (!currentlyDragging) { switch (param.orientation) { case ScaleHandleParam.Orientation.Signed: s_DoScaleHandle_AxisHandlesOctant[i] = 1; break; case ScaleHandleParam.Orientation.Camera: s_DoScaleHandle_AxisHandlesOctant[i] = viewVectorDrawSpace[i] > 0.01f ? -1 : 1; break; } } var id = ids[i]; var isThisAxisHot = isHot && id == GUIUtility.hotControl; var axisDir = GetAxisVector(i); var axisColor = isProportionalScale ? constrainProportionsScaleHandleColor : GetColorByAxis(i); var offset = axisOffset[i]; var cameraLerp = id == GUIUtility.hotControl ? 0 : GetCameraViewLerpForWorldAxis(viewVectorDrawSpace, axisDir); // If we are here and is hot, then this axis is hot and must be opaque cameraLerp = isHot ? 0 : cameraLerp; color = isDisabled ? Color.Lerp(axisColor, staticColor, staticBlend) : axisColor; axisDir *= s_DoScaleHandle_AxisHandlesOctant[i]; if (cameraLerp <= kCameraViewThreshold) { color = GetFadedAxisColor(color, cameraLerp, id); if (isHot && !isThisAxisHot) color = isProportionalScale ? selectedColor : s_DisabledHandleColor; if (isCenterIsHot) color = selectedColor; color = ToActiveColorSpace(color); if (isProportionalScale) axisIndex = 0; scale = UnityEditorInternal.SliderScale.DoAxis( id, scale, axisIndex, position, rotation * axisDir, rotation, handleSize * param.axisSize[axisIndex], EditorSnapSettings.scale, offset, axisLineScale[axisIndex], s_InitialScale, isProportionalScale); } } if (param.ShouldShow(ScaleHandleParam.Handle.XYZ) && (ids.xyz == GUIUtility.hotControl || !isHot)) { color = isProportionalScale ? constrainProportionsScaleHandleColor : ToActiveColorSpace(centerColor); if (isDisabled) color = Color.Lerp(color, staticColor, staticBlend); proportionalScale = false; EditorGUI.BeginChangeCheck(); s_CurrentMultiplier = ScaleValueHandle(ids.xyz, s_CurrentMultiplier, position, rotation, handleSize * param.xyzSize, CubeHandleCap, EditorSnapSettings.scale); if (EditorGUI.EndChangeCheck()) { scale = s_InitialScale * s_CurrentMultiplier; } } return scale; } } }
UnityCsReference/Editor/Mono/Handles/ScaleHandle.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Handles/ScaleHandle.cs", "repo_id": "UnityCsReference", "token_count": 5342 }
308
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; namespace UnityEditor { internal interface IBuildTarget { // The DesktopPluginImporterExtension.OnPlatformSettingsGUI method and the PlayerSettingsEditor.GraphicsAPIsGUI method // use this property to determine what name to display for a build target. This is often the same as the TargetName // property but is different for several targets, such as "Embedded Linux" instead of "EmbeddedLinux". string DisplayName { get; } // The BuildTargetConverter.TryConvertToRuntimePlatform method uses this property to convert a build target into a // runtime platform. This method is used only for testing. RuntimePlatform RuntimePlatform { get; } // This property contains the canonical name of the build target. Many methods throughout the editor code base make // use of this property. string TargetName { get; } // This property is used as a suffix for il2cpp profiles. Should a more suited place for it exist, move it string RootSystemType { get; } // This function allows to retrieve BuildPlatformProperties derived from IPlatformProperties as quick access IBuildPlatformProperties BuildPlatformProperties { get; } // This function allows to retrieve GraphicsPlatformProperties derived from IPlatformProperties as quick access IGraphicsPlatformProperties GraphicsPlatformProperties { get; } // This function allows to retrieve PlayerConnectionPlatformProperties derived from IPlatformProperties as quick access IPlayerConnectionPlatformProperties PlayerConnectionPlatformProperties { get; } // This function allows to retrieve IconPlatformProperties derived from IPlatformProperties as quick access IIconPlatformProperties IconPlatformProperties { get; } // This function allows to retrieve UIPlatformProperties derived from IPlatformProperties as quick access IUIPlatformProperties UIPlatformProperties { get; } // This function allows to retrieve AudioPlatformProperties derived from IPlatformProperties as quick access IAudioPlatformProperties AudioPlatformProperties { get; } // This function allows to retrieve AudioPlatformProperties derived from IPlatformProperties as quick access IVRPlatformProperties VRPlatformProperties { get; } // This function allows to retrieve properties of a give type, derived from IPlatformProperties // if they are available. bool TryGetProperties<T>(out T properties) where T: IPlatformProperties; // This functions allows to access the old BuildTarget enum value for a build target when instantiated. int GetLegacyId { get; } } }
UnityCsReference/Editor/Mono/IBuildTarget.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/IBuildTarget.cs", "repo_id": "UnityCsReference", "token_count": 820 }
309
// 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; namespace UnityEditor { [CustomEditor(typeof(IHVImageFormatImporter))] [CanEditMultipleObjects] internal class IHVImageFormatImporterInspector : AssetImporterEditor { public override bool showImportedObject { get { return false; } } SerializedProperty m_IsReadable; SerializedProperty m_sRGBTexture; SerializedProperty m_FilterMode; SerializedProperty m_WrapU; SerializedProperty m_WrapV; SerializedProperty m_WrapW; SerializedProperty m_StreamingMipmaps; SerializedProperty m_StreamingMipmapsPriority; SerializedProperty m_IgnoreMipmapLimit; SerializedProperty m_MipmapLimitGroupName; internal class Styles { // copy pasted from TextureImporterInspector.TextureSettingsGUI() public static readonly GUIContent readWrite = EditorGUIUtility.TrTextContent("Read/Write", "Enable to be able to access the raw pixel data from code."); public static readonly GUIContent sRGBTexture = EditorGUIUtility.TrTextContent("sRGB (Color Texture)", "Texture content is stored in gamma space. Non-HDR color textures should enable this flag (except if used for IMGUI)."); public static readonly GUIContent wrapMode = EditorGUIUtility.TrTextContent("Wrap Mode"); public static readonly GUIContent filterMode = EditorGUIUtility.TrTextContent("Filter Mode"); public static readonly GUIContent streamingMipmaps = EditorGUIUtility.TrTextContent("Streaming Mipmaps", "Only load larger mipmaps as needed to render the current game cameras."); public static readonly GUIContent streamingMipmapsPriority = EditorGUIUtility.TrTextContent("Mip Map Priority", "Mip map streaming priority when there's contention for resources. Positive numbers represent higher priority. Valid range is -128 to 127."); public static readonly int[] filterModeValues = { (int)FilterMode.Point, (int)FilterMode.Bilinear, (int)FilterMode.Trilinear }; public static readonly GUIContent[] filterModeOptions = { EditorGUIUtility.TrTextContent("Point (no filter)"), EditorGUIUtility.TrTextContent("Bilinear"), EditorGUIUtility.TrTextContent("Trilinear") }; } public override void OnEnable() { base.OnEnable(); m_IsReadable = serializedObject.FindProperty("m_IsReadable"); m_sRGBTexture = serializedObject.FindProperty("m_sRGBTexture"); m_FilterMode = serializedObject.FindProperty("m_TextureSettings.m_FilterMode"); m_WrapU = serializedObject.FindProperty("m_TextureSettings.m_WrapU"); m_WrapV = serializedObject.FindProperty("m_TextureSettings.m_WrapV"); m_WrapW = serializedObject.FindProperty("m_TextureSettings.m_WrapW"); m_StreamingMipmaps = serializedObject.FindProperty("m_StreamingMipmaps"); m_StreamingMipmapsPriority = serializedObject.FindProperty("m_StreamingMipmapsPriority"); m_IgnoreMipmapLimit = serializedObject.FindProperty("m_IgnoreMipmapLimit"); m_MipmapLimitGroupName = serializedObject.FindProperty("m_MipmapLimitGroupName"); } // alas it looks impossible to share code so we copy paste from TextureImporterInspector.TextureSettingsGUI() bool m_ShowPerAxisWrapModes = false; public void TextureSettingsGUI() { // NOTE: once we get ability to have 3D/Volume texture shapes, should pass true for isVolume based on m_TextureShape // Also, always consider we may have a volume if we don't know the target. bool isVolume = assetTarget == null; TextureInspector.WrapModePopup(m_WrapU, m_WrapV, m_WrapW, isVolume, ref m_ShowPerAxisWrapModes, assetTarget == null); Rect rect = EditorGUILayout.GetControlRect(); EditorGUI.BeginProperty(rect, Styles.filterMode, m_FilterMode); EditorGUI.BeginChangeCheck(); FilterMode filter = (FilterMode)EditorGUI.IntPopup(rect, Styles.filterMode, m_FilterMode.intValue, Styles.filterModeOptions, Styles.filterModeValues); if (EditorGUI.EndChangeCheck()) m_FilterMode.intValue = (int)filter; EditorGUI.EndProperty(); } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUILayout.PropertyField(m_IsReadable, Styles.readWrite); EditorGUILayout.PropertyField(m_sRGBTexture, Styles.sRGBTexture); EditorGUI.BeginChangeCheck(); TextureSettingsGUI(); if (EditorGUI.EndChangeCheck()) { // copy pasted from TextureImporterInspector.TextureSettingsGUI() foreach (AssetImporter importer in targets) { Texture tex = AssetDatabase.LoadMainAssetAtPath(importer.assetPath) as Texture; if (tex != null) { TextureUtil.SetFilterModeNoDirty(tex, (FilterMode)m_FilterMode.intValue); if (!m_WrapU.hasMultipleDifferentValues && !m_WrapV.hasMultipleDifferentValues && !m_WrapW.hasMultipleDifferentValues) { TextureUtil.SetWrapModeNoDirty(tex, (TextureWrapMode)m_WrapU.intValue, (TextureWrapMode)m_WrapV.intValue, (TextureWrapMode)m_WrapW.intValue); } } } SceneView.RepaintAll(); } EditorGUILayout.PropertyField(m_StreamingMipmaps, Styles.streamingMipmaps); if (m_StreamingMipmaps.boolValue && !m_StreamingMipmaps.hasMultipleDifferentValues) { EditorGUI.indentLevel++; EditorGUILayout.PropertyField(m_StreamingMipmapsPriority, Styles.streamingMipmapsPriority); EditorGUI.indentLevel--; } TextureImporterInspector.DoMipmapLimitsGUI(m_IgnoreMipmapLimit, m_MipmapLimitGroupName); serializedObject.ApplyModifiedProperties(); ApplyRevertGUI(); } } }
UnityCsReference/Editor/Mono/ImportSettings/IHVImageFormatImporterInspector.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/ImportSettings/IHVImageFormatImporterInspector.cs", "repo_id": "UnityCsReference", "token_count": 2721 }
310
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Text.RegularExpressions; using System.Linq; using Object = UnityEngine.Object; namespace UnityEditor { internal class AssetBundleNameGUI { static private readonly GUIContent kAssetBundleName = EditorGUIUtility.TrTextContent("AssetBundle"); static private readonly int kAssetBundleNameFieldIdHash = "AssetBundleNameFieldHash".GetHashCode(); static private readonly int kAssetBundleVariantFieldIdHash = "AssetBundleVariantFieldHash".GetHashCode(); private static class Styles { public static GUIStyle label = "ControlLabel"; public static GUIStyle popup = "MiniPopup"; public static GUIStyle textField = "textField"; } private bool m_ShowAssetBundleNameTextField = false; private bool m_ShowAssetBundleVariantTextField = false; public void OnAssetBundleNameGUI(IEnumerable<Object> assets) { float oldLabelWidth = EditorGUIUtility.labelWidth; EditorGUIUtility.labelWidth = 90f; Rect bundleRect = EditorGUILayout.GetControlRect(true, EditorGUI.kSingleLineHeight); Rect variantRect = bundleRect; bundleRect.width *= 0.8f; variantRect.xMin += bundleRect.width + EditorGUI.kSpacing; int id = GUIUtility.GetControlID(kAssetBundleNameFieldIdHash, FocusType.Passive, bundleRect); bundleRect = EditorGUI.PrefixLabel(bundleRect, id, kAssetBundleName, Styles.label); if (m_ShowAssetBundleNameTextField) AssetBundleTextField(bundleRect, id, assets, false); else AssetBundlePopup(bundleRect, id, assets, false); id = GUIUtility.GetControlID(kAssetBundleVariantFieldIdHash, FocusType.Passive, variantRect); if (m_ShowAssetBundleVariantTextField) AssetBundleTextField(variantRect, id, assets, true); else AssetBundlePopup(variantRect, id, assets, true); EditorGUIUtility.labelWidth = oldLabelWidth; } private void ShowNewAssetBundleField(bool isVariant) { m_ShowAssetBundleNameTextField = !isVariant; m_ShowAssetBundleVariantTextField = isVariant; EditorGUIUtility.editingTextField = true; } private void AssetBundleTextField(Rect rect, int id, IEnumerable<Object> assets, bool isVariant) { EditorGUI.BeginChangeCheck(); string temp = EditorGUI.DelayedTextFieldInternal(rect, id, GUIContent.none, "", null, Styles.textField); if (EditorGUI.EndChangeCheck()) { SetAssetBundleForAssets(assets, temp, isVariant); ShowAssetBundlePopup(); } // editing was cancelled if (EditorGUI.IsEditingTextField() == false && Event.current.type != EventType.Layout) ShowAssetBundlePopup(); } private void ShowAssetBundlePopup() { m_ShowAssetBundleNameTextField = false; m_ShowAssetBundleVariantTextField = false; } private void AssetBundlePopup(Rect rect, int id, IEnumerable<Object> assets, bool isVariant) { List<string> displayedOptions = new List<string>(); displayedOptions.Add("None"); displayedOptions.Add(""); // seperator // Anyway to optimize this by caching GetAssetBundleNameFromAssets() and GetAllAssetBundleNames() when they actually change? // As we can change the assetBundle name by script, the UI needs to detect this kind of change. bool mixedValue; IEnumerable<string> assetBundleFromAssets = GetAssetBundlesFromAssets(assets, isVariant, out mixedValue); string[] assetBundles = isVariant ? AssetDatabase.GetAllAssetBundleVariants() : AssetDatabase.GetAllAssetBundleNamesWithoutVariant(); displayedOptions.AddRange(assetBundles); displayedOptions.Add(""); // seperator int newAssetBundleIndex = displayedOptions.Count; displayedOptions.Add("New..."); // These two options are invalid for variant, so skip them for variant. int removeUnusedIndex = -1; int filterSelectedIndex = -1; if (!isVariant) { removeUnusedIndex = displayedOptions.Count; displayedOptions.Add("Remove Unused Names"); filterSelectedIndex = displayedOptions.Count; if (assetBundleFromAssets.Count() != 0) displayedOptions.Add("Filter Selected Name" + (mixedValue ? "s" : "")); } int selectedIndex = 0; string firstAssetBundle = assetBundleFromAssets.FirstOrDefault(); if (!String.IsNullOrEmpty(firstAssetBundle)) selectedIndex = displayedOptions.IndexOf(firstAssetBundle); EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = mixedValue; selectedIndex = EditorGUI.DoPopup(rect, id, selectedIndex, EditorGUIUtility.TempContent(displayedOptions.ToArray()), Styles.popup); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { if (selectedIndex == 0) // None SetAssetBundleForAssets(assets, null, isVariant); else if (selectedIndex == newAssetBundleIndex) // New... ShowNewAssetBundleField(isVariant); else if (selectedIndex == removeUnusedIndex) // Remove Unused Names AssetDatabase.RemoveUnusedAssetBundleNames(); else if (selectedIndex == filterSelectedIndex) // Filter Selected Name(s) FilterSelected(assetBundleFromAssets); else SetAssetBundleForAssets(assets, displayedOptions[selectedIndex], isVariant); } } private void FilterSelected(IEnumerable<string> assetBundleNames) { var searchFilter = new SearchFilter(); searchFilter.assetBundleNames = assetBundleNames.Where(name => !String.IsNullOrEmpty(name)).ToArray(); if (ProjectBrowser.s_LastInteractedProjectBrowser != null) ProjectBrowser.s_LastInteractedProjectBrowser.SetSearch(searchFilter); else Debug.LogWarning("No Project Browser found to apply AssetBundle filter."); } private IEnumerable<string> GetAssetBundlesFromAssets(IEnumerable<Object> assets, bool isVariant, out bool isMixed) { var assetBundles = new HashSet<string>(); string lastAssetBundle = null; isMixed = false; foreach (Object obj in assets) { if (obj is MonoScript) continue; AssetImporter importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(obj)); if (importer == null) continue; string currentAssetBundle = isVariant ? importer.assetBundleVariant : importer.assetBundleName; if (lastAssetBundle != null && lastAssetBundle != currentAssetBundle) isMixed = true; lastAssetBundle = currentAssetBundle; if (!String.IsNullOrEmpty(currentAssetBundle)) assetBundles.Add(currentAssetBundle); } return assetBundles; } private void SetAssetBundleForAssets(IEnumerable<Object> assets, string name, bool isVariant) { bool assetBundleNameChanged = false; foreach (Object obj in assets) { if (obj is MonoScript) continue; AssetImporter importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(obj)); if (importer == null) continue; if (isVariant) importer.assetBundleVariant = name; else importer.assetBundleName = name; assetBundleNameChanged = true; } if (assetBundleNameChanged) { EditorApplication.Internal_CallAssetBundleNameChanged(); } } } }
UnityCsReference/Editor/Mono/Inspector/AssetBundleNameGUI.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/AssetBundleNameGUI.cs", "repo_id": "UnityCsReference", "token_count": 3839 }
311
// 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.Globalization; using System.Collections.Generic; namespace UnityEditor { internal class AvatarAutoMapper { private enum Side { None, Left, Right } private struct BoneMappingItem { public int parent; public int bone; public int minStep; public int maxStep; public float lengthRatio; public Vector3 dir; public Side side; public bool optional; public bool alwaysInclude; public string[] keywords; private int[] children; public BoneMappingItem(int parent, int bone, int minStep, int maxStep, float lengthRatio, Vector3 dir, Side side, bool optional, bool alwaysInclude, params string[] keywords) { this.parent = parent; this.bone = bone; this.minStep = minStep; this.maxStep = maxStep; this.lengthRatio = lengthRatio; this.dir = dir; this.side = side; this.optional = optional; this.alwaysInclude = alwaysInclude; this.keywords = keywords; this.children = null; } public BoneMappingItem(int parent, int bone, int minStep, int maxStep, float lengthRatio, Side side, bool optional, bool alwaysInclude, params string[] keywords) : this(parent, bone, minStep, maxStep, lengthRatio, Vector3.zero, side, optional, alwaysInclude, keywords) {} public BoneMappingItem(int parent, int bone, int minStep, int maxStep, float lengthRatio, Vector3 dir, Side side, params string[] keywords) : this(parent, bone, minStep, maxStep, lengthRatio, dir, side, false, false, keywords) {} public BoneMappingItem(int parent, int bone, int minStep, int maxStep, float lengthRatio, Side side, params string[] keywords) : this(parent, bone, minStep, maxStep, lengthRatio, Vector3.zero, side, false, false, keywords) {} public int[] GetChildren(BoneMappingItem[] mappingData) { if (children == null) { List<int> list = new List<int>(); for (int i = 0; i < mappingData.Length; i++) if (mappingData[i].parent == bone) list.Add(i); children = list.ToArray(); } return children; } } private class BoneMatch : IComparable<BoneMatch> { public BoneMatch parent; public List<BoneMatch> children = new List<BoneMatch>(); public bool doMap = false; public BoneMatch humanBoneParent { get { BoneMatch p = parent; while (p.parent != null && (p.item.bone < 0)) p = p.parent; return p; } } public BoneMappingItem item; public Transform bone; public float score; public float siblingScore; public float totalSiblingScore { get { return score + siblingScore; } } public List<string> debugTracker = new List<string>(); public BoneMatch(BoneMatch parent, Transform bone, BoneMappingItem item) { this.parent = parent; this.bone = bone; this.item = item; } public int CompareTo(BoneMatch other) { if (other == null) return 1; return other.totalSiblingScore.CompareTo(totalSiblingScore); } } private struct QueuedBone { public Transform bone; public int level; public QueuedBone(Transform bone, int level) { this.bone = bone; this.level = level; } } private static bool kDebug = false; private static string[] kShoulderKeywords = {"shoulder", "collar", "clavicle"}; private static string[] kUpperArmKeywords = {"up"}; private static string[] kLowerArmKeywords = {"lo", "fore", "elbow"}; private static string[] kHandKeywords = {"hand", "wrist"}; private static string[] kUpperLegKeywords = {"up", "thigh"}; private static string[] kLowerLegKeywords = {"lo", "calf", "knee", "shin"}; private static string[] kFootKeywords = {"foot", "ankle"}; private static string[] kToeKeywords = {"toe", "!end", "!top", "!nub"}; private static string[] kNeckKeywords = {"neck"}; private static string[] kHeadKeywords = {"head"}; private static string[] kJawKeywords = {"jaw", "open", "!teeth", "!tongue", "!pony", "!braid", "!end", "!top", "!nub"}; private static string[] kEyeKeywords = {"eye", "ball", "!brow", "!lid", "!pony", "!braid", "!end", "!top", "!nub"}; private static string[] kThumbKeywords = {"thu", "!palm", "!wrist", "!end", "!top", "!nub"}; private static string[] kIndexFingerKeywords = {"ind", "point", "!palm", "!wrist", "!end", "!top", "!nub"}; private static string[] kMiddleFingerKeywords = {"mid", "long", "!palm", "!wrist", "!end", "!top", "!nub"}; private static string[] kRingFingerKeywords = {"rin", "!palm", "!wrist", "!end", "!top", "!nub"}; private static string[] kLittleFingerKeywords = {"lit", "pin", "!palm", "!wrist", "!end", "!top", "!nub"}; private static BoneMappingItem[] s_MappingDataBody = new BoneMappingItem[] { new BoneMappingItem(-1, (int)HumanBodyBones.Hips, 1, 3, 0.0f, Side.None), new BoneMappingItem((int)HumanBodyBones.Hips, (int)HumanBodyBones.RightUpperLeg, 1, 2, 0.0f, Vector3.right, Side.Right, kUpperLegKeywords), new BoneMappingItem((int)HumanBodyBones.RightUpperLeg, (int)HumanBodyBones.RightLowerLeg, 1, 2, 3.0f, -Vector3.up, Side.Right, kLowerLegKeywords), new BoneMappingItem((int)HumanBodyBones.RightLowerLeg, (int)HumanBodyBones.RightFoot, 1, 2, 1.0f, -Vector3.up, Side.Right, kFootKeywords), new BoneMappingItem((int)HumanBodyBones.RightFoot, (int)HumanBodyBones.RightToes, 1, 2, 0.5f, Vector3.forward, Side.Right, true, true, kToeKeywords), new BoneMappingItem((int)HumanBodyBones.Hips, (int)HumanBodyBones.Spine, 1, 3, 0.0f, Vector3.up, Side.None), new BoneMappingItem((int)HumanBodyBones.Spine, (int)HumanBodyBones.Chest, 0, 3, 1.4f, Vector3.up, Side.None, true, false), new BoneMappingItem((int)HumanBodyBones.Chest, (int)HumanBodyBones.UpperChest, 0, 3, 1.4f, Vector3.up, Side.None, true, false), new BoneMappingItem((int)HumanBodyBones.UpperChest, (int)HumanBodyBones.RightShoulder, 1, 3, 0.0f, Vector3.right, Side.Right, true, false, kShoulderKeywords), new BoneMappingItem((int)HumanBodyBones.RightShoulder, (int)HumanBodyBones.RightUpperArm, 0, 2, 0.5f, Vector3.right, Side.Right, kUpperArmKeywords), new BoneMappingItem((int)HumanBodyBones.RightUpperArm, (int)HumanBodyBones.RightLowerArm, 1, 2, 2.0f, Vector3.right, Side.Right, kLowerArmKeywords), new BoneMappingItem((int)HumanBodyBones.RightLowerArm, (int)HumanBodyBones.RightHand, 1, 2, 1.0f, Vector3.right, Side.Right, kHandKeywords), new BoneMappingItem((int)HumanBodyBones.UpperChest, (int)HumanBodyBones.Neck, 1, 3, 1.8f, Vector3.up, Side.None, true, false, kNeckKeywords), new BoneMappingItem((int)HumanBodyBones.Neck, (int)HumanBodyBones.Head, 0, 2, 0.3f, Vector3.up, Side.None, kHeadKeywords), new BoneMappingItem((int)HumanBodyBones.Head, (int)HumanBodyBones.Jaw, 1, 2, 0.0f, Vector3.forward, Side.None, true, false, kJawKeywords), new BoneMappingItem((int)HumanBodyBones.Head, (int)HumanBodyBones.RightEye, 1, 2, 0.0f, new Vector3(1, 1, 1), Side.Right, true, false, kEyeKeywords), new BoneMappingItem((int)HumanBodyBones.RightHand, -2, 1, 2, 0.0f, new Vector3(1, -1, 2), Side.Right, true, false, kThumbKeywords), new BoneMappingItem((int)HumanBodyBones.RightHand, -3, 1, 2, 0.0f, new Vector3(3, 0, 1), Side.Right, true, false, kIndexFingerKeywords), }; private static BoneMappingItem[] s_LeftMappingDataHand = new BoneMappingItem[] { new BoneMappingItem(-2, -1, 1, 2, 0.0f, Side.None), new BoneMappingItem(-1, (int)HumanBodyBones.LeftThumbProximal, 1, 3, 0.0f, new Vector3(2, 0, 1), Side.None, kThumbKeywords), new BoneMappingItem(-1, (int)HumanBodyBones.LeftIndexProximal, 1, 3, 0.0f, new Vector3(4, 0, 1), Side.None, kIndexFingerKeywords), new BoneMappingItem(-1, (int)HumanBodyBones.LeftMiddleProximal, 1, 3, 0.0f, new Vector3(4, 0, 0), Side.None, kMiddleFingerKeywords), new BoneMappingItem(-1, (int)HumanBodyBones.LeftRingProximal, 1, 3, 0.0f, new Vector3(4, 0, -1), Side.None, kRingFingerKeywords), new BoneMappingItem(-1, (int)HumanBodyBones.LeftLittleProximal, 1, 3, 0.0f, new Vector3(4, 0, -2), Side.None, kLittleFingerKeywords), new BoneMappingItem((int)HumanBodyBones.LeftThumbProximal, (int)HumanBodyBones.LeftThumbIntermediate, 1, 1, 0.0f, Side.None, false, true), new BoneMappingItem((int)HumanBodyBones.LeftIndexProximal, (int)HumanBodyBones.LeftIndexIntermediate, 1, 1, 0.0f, Side.None, false, true), new BoneMappingItem((int)HumanBodyBones.LeftMiddleProximal, (int)HumanBodyBones.LeftMiddleIntermediate, 1, 1, 0.0f, Side.None, false, true), new BoneMappingItem((int)HumanBodyBones.LeftRingProximal, (int)HumanBodyBones.LeftRingIntermediate, 1, 1, 0.0f, Side.None, false, true), new BoneMappingItem((int)HumanBodyBones.LeftLittleProximal, (int)HumanBodyBones.LeftLittleIntermediate, 1, 1, 0.0f, Side.None, false, true), new BoneMappingItem((int)HumanBodyBones.LeftThumbIntermediate, (int)HumanBodyBones.LeftThumbDistal, 1, 1, 0.0f, Side.None, false, true), new BoneMappingItem((int)HumanBodyBones.LeftIndexIntermediate, (int)HumanBodyBones.LeftIndexDistal, 1, 1, 0.0f, Side.None, false, true), new BoneMappingItem((int)HumanBodyBones.LeftMiddleIntermediate, (int)HumanBodyBones.LeftMiddleDistal, 1, 1, 0.0f, Side.None, false, true), new BoneMappingItem((int)HumanBodyBones.LeftRingIntermediate, (int)HumanBodyBones.LeftRingDistal, 1, 1, 0.0f, Side.None, false, true), new BoneMappingItem((int)HumanBodyBones.LeftLittleIntermediate, (int)HumanBodyBones.LeftLittleDistal, 1, 1, 0.0f, Side.None, false, true), }; private static BoneMappingItem[] s_RightMappingDataHand = new BoneMappingItem[] { new BoneMappingItem(-2, -1, 1, 2, 0.0f, Side.None), new BoneMappingItem(-1, (int)HumanBodyBones.RightThumbProximal, 1, 3, 0.0f, new Vector3(2, 0, 1), Side.None, kThumbKeywords), new BoneMappingItem(-1, (int)HumanBodyBones.RightIndexProximal, 1, 3, 0.0f, new Vector3(4, 0, 1), Side.None, kIndexFingerKeywords), new BoneMappingItem(-1, (int)HumanBodyBones.RightMiddleProximal, 1, 3, 0.0f, new Vector3(4, 0, 0), Side.None, kMiddleFingerKeywords), new BoneMappingItem(-1, (int)HumanBodyBones.RightRingProximal, 1, 3, 0.0f, new Vector3(4, 0, -1), Side.None, kRingFingerKeywords), new BoneMappingItem(-1, (int)HumanBodyBones.RightLittleProximal, 1, 3, 0.0f, new Vector3(4, 0, -2), Side.None, kLittleFingerKeywords), new BoneMappingItem((int)HumanBodyBones.RightThumbProximal, (int)HumanBodyBones.RightThumbIntermediate, 1, 1, 0.0f, Side.None, false, true), new BoneMappingItem((int)HumanBodyBones.RightIndexProximal, (int)HumanBodyBones.RightIndexIntermediate, 1, 1, 0.0f, Side.None, false, true), new BoneMappingItem((int)HumanBodyBones.RightMiddleProximal, (int)HumanBodyBones.RightMiddleIntermediate, 1, 1, 0.0f, Side.None, false, true), new BoneMappingItem((int)HumanBodyBones.RightRingProximal, (int)HumanBodyBones.RightRingIntermediate, 1, 1, 0.0f, Side.None, false, true), new BoneMappingItem((int)HumanBodyBones.RightLittleProximal, (int)HumanBodyBones.RightLittleIntermediate, 1, 1, 0.0f, Side.None, false, true), new BoneMappingItem((int)HumanBodyBones.RightThumbIntermediate, (int)HumanBodyBones.RightThumbDistal, 1, 1, 0.0f, Side.None, false, true), new BoneMappingItem((int)HumanBodyBones.RightIndexIntermediate, (int)HumanBodyBones.RightIndexDistal, 1, 1, 0.0f, Side.None, false, true), new BoneMappingItem((int)HumanBodyBones.RightMiddleIntermediate, (int)HumanBodyBones.RightMiddleDistal, 1, 1, 0.0f, Side.None, false, true), new BoneMappingItem((int)HumanBodyBones.RightRingIntermediate, (int)HumanBodyBones.RightRingDistal, 1, 1, 0.0f, Side.None, false, true), new BoneMappingItem((int)HumanBodyBones.RightLittleIntermediate, (int)HumanBodyBones.RightLittleDistal, 1, 1, 0.0f, Side.None, false, true), }; private static bool s_DidPerformInit = false; private Dictionary<Transform, bool> m_ValidBones; private bool m_TreatDummyBonesAsReal = false; private Quaternion m_Orientation; private int m_MappingIndexOffset = 0; private BoneMappingItem[] m_MappingData; private Dictionary<string, int> m_BoneHasKeywordDict; private Dictionary<string, int> m_BoneHasBadKeywordDict; private Dictionary<int, BoneMatch> m_BoneMatchDict; private static int GetLeftBoneIndexFromRight(int rightIndex) { if (rightIndex < 0) { return rightIndex; } else if (rightIndex < (int)HumanBodyBones.LastBone) { string name = Enum.GetName(typeof(HumanBodyBones), rightIndex); name = name.Replace("Right", "Left"); return (int)(HumanBodyBones)Enum.Parse(typeof(HumanBodyBones), name); } return -1; } public static void InitGlobalMappingData() { if (s_DidPerformInit) return; List<BoneMappingItem> mappingData = new List<BoneMappingItem>(s_MappingDataBody); // Add left side bones to match right side ones. int size = mappingData.Count; for (int i = 0; i < size; i++) { BoneMappingItem item = mappingData[i]; if (item.side == Side.Right) { // Get left HumanBodyBones that mirrors right one. int bone = GetLeftBoneIndexFromRight(item.bone); // Get left parent HumanBodyBones that mirrors parent of right one int parentBone = GetLeftBoneIndexFromRight(item.parent); // Add left BoneMappingItem that mirrors right one. mappingData.Add(new BoneMappingItem(parentBone, bone, item.minStep, item.maxStep, item.lengthRatio, new Vector3(-item.dir.x, item.dir.y, item.dir.z), Side.Left, item.optional, item.alwaysInclude, item.keywords)); } } s_MappingDataBody = mappingData.ToArray(); // Cache children for each BoneMappingItem for (int i = 0; i < s_MappingDataBody.Length; i++) s_MappingDataBody[i].GetChildren(s_MappingDataBody); for (int i = 0; i < s_LeftMappingDataHand.Length; i++) s_LeftMappingDataHand[i].GetChildren(s_LeftMappingDataHand); for (int i = 0; i < s_RightMappingDataHand.Length; i++) s_RightMappingDataHand[i].GetChildren(s_RightMappingDataHand); s_DidPerformInit = true; } public static Dictionary<int, Transform> MapBones(Transform root, Dictionary<Transform, bool> validBones) { AvatarAutoMapper mapper = new AvatarAutoMapper(validBones); return mapper.MapBones(root); } public AvatarAutoMapper(Dictionary<Transform, bool> validBones) { m_BoneHasKeywordDict = new Dictionary<string, int>(); m_BoneHasBadKeywordDict = new Dictionary<string, int>(); m_BoneMatchDict = new Dictionary<int, BoneMatch>(); m_ValidBones = validBones; } public Dictionary<int, Transform> MapBones(Transform root) { InitGlobalMappingData(); Dictionary<int, Transform> mapping = new Dictionary<int, Transform>(); // Perform body mapping { m_Orientation = Quaternion.identity; m_MappingData = s_MappingDataBody; m_MappingIndexOffset = 0; m_BoneMatchDict.Clear(); BoneMatch rootMatch = new BoneMatch(null, root, m_MappingData[0]); m_TreatDummyBonesAsReal = false; MapBonesFromRootDown(rootMatch, mapping); // There are 15 required bones. If we mapped less than that, check if we can do better. if (mapping.Count < 15) { m_TreatDummyBonesAsReal = true; MapBonesFromRootDown(rootMatch, mapping); } // Check if character has correct alignment if (mapping.ContainsKey((int)HumanBodyBones.LeftUpperLeg) && mapping.ContainsKey((int)HumanBodyBones.RightUpperLeg) && mapping.ContainsKey((int)HumanBodyBones.LeftUpperArm) && mapping.ContainsKey((int)HumanBodyBones.RightUpperArm)) { m_Orientation = AvatarSetupTool.AvatarComputeOrientation( mapping[(int)HumanBodyBones.LeftUpperLeg].position, mapping[(int)HumanBodyBones.RightUpperLeg].position, mapping[(int)HumanBodyBones.LeftUpperArm].position, mapping[(int)HumanBodyBones.RightUpperArm].position); // If not standard aligned, try to map again with correct alignment assumptions if (Vector3.Angle(m_Orientation * Vector3.up, Vector3.up) > 20 || Vector3.Angle(m_Orientation * Vector3.forward, Vector3.forward) > 20) { if (kDebug) Debug.Log("*** Mapping with new computed orientation"); mapping.Clear(); m_BoneMatchDict.Clear(); MapBonesFromRootDown(rootMatch, mapping); } } // For models that don't have meshes, all bones are marked valid; even the root. // So we use this to check if this model has meshes or not. bool modelHasMeshes = !(m_ValidBones.ContainsKey(root) && m_ValidBones[root] == true); // Fix up hips to be valid bone closest to the root // For models with meshes, valid bones further up are mapped to part of the mesh (otherwise they wouldn't be valid). // For models with no meshes we don't know which transforms are valid bones and which aren't // so we skip this step and use the found hips bone as-is. if (modelHasMeshes && mapping.Count > 0 && mapping.ContainsKey((int)HumanBodyBones.Hips)) { while (true) { Transform parent = mapping[(int)HumanBodyBones.Hips].parent; if (parent != null && parent != rootMatch.bone && m_ValidBones.ContainsKey(parent) && m_ValidBones[parent] == true) mapping[(int)HumanBodyBones.Hips] = parent; else break; } } // Move upper chest to chest if no chest was found if (!mapping.ContainsKey((int)HumanBodyBones.Chest) && mapping.ContainsKey((int)HumanBodyBones.UpperChest)) { mapping.Add((int)HumanBodyBones.Chest, mapping[(int)HumanBodyBones.UpperChest]); mapping.Remove((int)HumanBodyBones.UpperChest); } } int kMinFingerBones = 3; Quaternion bodyOrientation = m_Orientation; // Perform left hand mapping if (mapping.ContainsKey((int)HumanBodyBones.LeftHand)) { Transform lowerArm = mapping[(int)HumanBodyBones.LeftLowerArm]; Transform hand = mapping[(int)HumanBodyBones.LeftHand]; // Use reference orientation based on lower arm for mapping hand m_Orientation = Quaternion.FromToRotation(bodyOrientation * -Vector3.right, hand.position - lowerArm.position) * bodyOrientation; m_MappingData = s_LeftMappingDataHand; m_MappingIndexOffset = (int)HumanBodyBones.LeftThumbProximal; m_BoneMatchDict.Clear(); BoneMatch rootMatch = new BoneMatch(null, lowerArm, m_MappingData[0]); m_TreatDummyBonesAsReal = true; int mappingCountBefore = mapping.Count; MapBonesFromRootDown(rootMatch, mapping); // If we only mapped 2 finger bones or less, then cancel mapping of fingers if (mapping.Count < mappingCountBefore + kMinFingerBones) { for (int i = (int)HumanBodyBones.LeftThumbProximal; i <= (int)HumanBodyBones.LeftLittleDistal; i++) mapping.Remove(i); } } // Perform right hand mapping if (mapping.ContainsKey((int)HumanBodyBones.RightHand)) { Transform lowerArm = mapping[(int)HumanBodyBones.RightLowerArm]; Transform hand = mapping[(int)HumanBodyBones.RightHand]; // Use reference orientation based on lower arm for mapping hand m_Orientation = Quaternion.FromToRotation(bodyOrientation * Vector3.right, hand.position - lowerArm.position) * bodyOrientation; m_MappingData = s_RightMappingDataHand; m_MappingIndexOffset = (int)HumanBodyBones.RightThumbProximal; m_BoneMatchDict.Clear(); BoneMatch rootMatch = new BoneMatch(null, lowerArm, m_MappingData[0]); m_TreatDummyBonesAsReal = true; int mappingCountBefore = mapping.Count; MapBonesFromRootDown(rootMatch, mapping); // If we only mapped 2 finger bones or less, then cancel mapping of fingers if (mapping.Count < mappingCountBefore + kMinFingerBones) { for (int i = (int)HumanBodyBones.RightThumbProximal; i <= (int)HumanBodyBones.RightLittleDistal; i++) mapping.Remove(i); } } return mapping; } private void MapBonesFromRootDown(BoneMatch rootMatch, Dictionary<int, Transform> mapping) { // Perform mapping List<BoneMatch> childMatches = RecursiveFindPotentialBoneMatches(rootMatch, m_MappingData[0], true); if (childMatches != null && childMatches.Count > 0) { if (kDebug) { EvaluateBoneMatch(childMatches[0], true); } ApplyMapping(childMatches[0], mapping); } } private void ApplyMapping(BoneMatch match, Dictionary<int, Transform> mapping) { if (match.doMap) mapping[match.item.bone] = match.bone; foreach (BoneMatch child in match.children) ApplyMapping(child, mapping); } private string GetStrippedAndNiceBoneName(Transform bone) { string[] strings = bone.name.Split(':'); return ObjectNames.NicifyVariableName(strings[strings.Length - 1]); } private int BoneHasBadKeyword(Transform bone, params string[] keywords) { string key = bone.GetInstanceID() + ":" + String.Concat(keywords); if (m_BoneHasBadKeywordDict.ContainsKey(key)) return m_BoneHasBadKeywordDict[key]; int score = 0; string boneName; // If parent transform has any of keywords, don't accept. Transform parent = bone.parent; while (parent.parent != null && m_ValidBones.ContainsKey(parent) && !m_ValidBones[parent]) parent = parent.parent; boneName = GetStrippedAndNiceBoneName(parent).ToLower(); foreach (string word in keywords) if (word[0] != '!' && boneName.Contains(word)) { score = -20; m_BoneHasBadKeywordDict[key] = score; return score; } // If this transform has any of the illegal keywords, don't accept. boneName = GetStrippedAndNiceBoneName(bone).ToLower(); foreach (string word in keywords) if (word[0] == '!' && boneName.Contains(word.Substring(1))) { score = -1000; m_BoneHasBadKeywordDict[key] = score; return score; } m_BoneHasBadKeywordDict[key] = score; return score; } private int BoneHasKeyword(Transform bone, params string[] keywords) { string key = bone.GetInstanceID() + ":" + String.Concat(keywords); if (m_BoneHasKeywordDict.ContainsKey(key)) return m_BoneHasKeywordDict[key]; int score = 0; // If this transform has any of the keywords, accept. string boneName = GetStrippedAndNiceBoneName(bone).ToLower(); foreach (string word in keywords) if (word[0] != '!' && boneName.Contains(word)) { score = 20; m_BoneHasKeywordDict[key] = score; return score; } m_BoneHasKeywordDict[key] = score; return score; } private const string kLeftMatch = @"(^|.*[ \.:_-])[lL]($|[ \.:_-].*)"; private const string kRightMatch = @"(^|.*[ \.:_-])[rR]($|[ \.:_-].*)"; private bool MatchesSideKeywords(string boneName, bool left) { if (boneName.ToLower().Contains(left ? "left" : "right")) return true; if (System.Text.RegularExpressions.Regex.Match(boneName, left ? kLeftMatch : kRightMatch).Length > 0) return true; return false; } private int GetBoneSideMatchPoints(BoneMatch match) { string boneName = match.bone.name; if (match.item.side == Side.None) if (MatchesSideKeywords(boneName, false) || MatchesSideKeywords(boneName, true)) return -1000; bool left = (match.item.side == Side.Left); if (MatchesSideKeywords(boneName, left)) return 15; if (MatchesSideKeywords(boneName, !left)) return -1000; return 0; } private int GetMatchKey(BoneMatch parentMatch, Transform t, BoneMappingItem goalItem) { SimpleProfiler.Begin("GetMatchKey"); int key = goalItem.bone; key += t.GetInstanceID() * 1000; if (parentMatch != null) { key += parentMatch.bone.GetInstanceID() * 1000000; if (parentMatch.parent != null) key += parentMatch.parent.bone.GetInstanceID() * 1000000000; } SimpleProfiler.End(); return key; } // Returns possible matches sorted with best-scoring ones first in the list private List<BoneMatch> RecursiveFindPotentialBoneMatches(BoneMatch parentMatch, BoneMappingItem goalItem, bool confirmedChoice) { List<BoneMatch> matches = new List<BoneMatch>(); // We want to search with breadh first search so we have to use a queue Queue<QueuedBone> queue = new Queue<QueuedBone>(); // Find matches queue.Enqueue(new QueuedBone(parentMatch.bone, 0)); while (queue.Count > 0) { QueuedBone current = queue.Dequeue(); Transform t = current.bone; if (current.level >= goalItem.minStep && (m_TreatDummyBonesAsReal || m_ValidBones == null || (m_ValidBones.ContainsKey(t) && m_ValidBones[t]))) { BoneMatch match; var key = GetMatchKey(parentMatch, t, goalItem); if (m_BoneMatchDict.ContainsKey(key)) { match = m_BoneMatchDict[key]; } else { match = new BoneMatch(parentMatch, t, goalItem); // RECURSIVE CALL EvaluateBoneMatch(match, false); m_BoneMatchDict[key] = match; } if (match.score > 0 || kDebug) matches.Add(match); } SimpleProfiler.Begin("Queue"); if (current.level < goalItem.maxStep) { foreach (Transform child in t) if (m_ValidBones == null || m_ValidBones.ContainsKey(child)) if (!m_TreatDummyBonesAsReal && m_ValidBones != null && !m_ValidBones[child]) queue.Enqueue(new QueuedBone(child, current.level)); else queue.Enqueue(new QueuedBone(child, current.level + 1)); } SimpleProfiler.End(); } if (matches.Count == 0) return null; // Sort by match score with best matches first SimpleProfiler.Begin("SortAndTrim"); matches.Sort(); if (matches[0].score <= 0) return null; if (kDebug && confirmedChoice) DebugMatchChoice(matches); // Keep top 3 priorities only for optimization while (matches.Count > 3) matches.RemoveAt(matches.Count - 1); matches.TrimExcess(); SimpleProfiler.End(); return matches; } private string GetNameOfBone(int boneIndex) { if (boneIndex < 0) return "" + boneIndex; return "" + (HumanBodyBones)boneIndex; } private string GetMatchString(BoneMatch match) { return GetNameOfBone(match.item.bone) + ":" + (match.bone == null ? "null" : match.bone.name); } private void DebugMatchChoice(List<BoneMatch> matches) { string str = GetNameOfBone(matches[0].item.bone) + " preferred order: "; for (int i = 0; i < matches.Count; i++) str += matches[i].bone.name + " (" + matches[i].score.ToString("0.0", CultureInfo.InvariantCulture.NumberFormat) + " / " + matches[i].totalSiblingScore.ToString("0.0", CultureInfo.InvariantCulture.NumberFormat) + "), "; foreach (BoneMatch m in matches) { str += "\n Match " + m.bone.name + " (" + m.score.ToString("0.0", CultureInfo.InvariantCulture.NumberFormat) + " / " + m.totalSiblingScore.ToString("0.0", CultureInfo.InvariantCulture.NumberFormat) + "):"; foreach (string s in m.debugTracker) str += "\n - " + s; } Debug.Log(str); } private bool IsParentOfOther(Transform knownCommonParent, Transform potentialParent, Transform potentialChild) { Transform t = potentialChild; while (t != knownCommonParent) { if (t == potentialParent) return true; if (t == knownCommonParent) return false; t = t.parent; } return false; } private bool ShareTransformPath(Transform commonParent, Transform childA, Transform childB) { return IsParentOfOther(commonParent, childA, childB) || IsParentOfOther(commonParent, childB, childA); } private List<BoneMatch> GetBestChildMatches(BoneMatch parentMatch, List<List<BoneMatch>> childMatchesLists) { List<BoneMatch> bestMatches = new List<BoneMatch>(); if (childMatchesLists.Count == 1) { bestMatches.Add(childMatchesLists[0][0]); return bestMatches; } int[] choices = new int[childMatchesLists.Count]; float dummyScore; choices = GetBestChildMatchChoices(parentMatch, childMatchesLists, choices, out dummyScore); for (int i = 0; i < choices.Length; i++) { if (choices[i] >= 0) bestMatches.Add(childMatchesLists[i][choices[i]]); } return bestMatches; } private int[] GetBestChildMatchChoices(BoneMatch parentMatch, List<List<BoneMatch>> childMatchesLists, int[] choices, out float score) { // See if any choices share the same transform path. List<int> sharedIndices = new List<int>(); for (int i = 0; i < choices.Length; i++) { if (choices[i] < 0) continue; sharedIndices.Clear(); sharedIndices.Add(i); for (int j = i + 1; j < choices.Length; j++) { if (choices[j] < 0) continue; if (ShareTransformPath(parentMatch.bone, childMatchesLists[i][choices[i]].bone, childMatchesLists[j][choices[j]].bone)) sharedIndices.Add(j); } if (sharedIndices.Count > 1) break; } if (sharedIndices.Count <= 1) { // If no shared transform paths, calculate score and return choices. score = 0; for (int i = 0; i < choices.Length; i++) if (choices[i] >= 0) score += childMatchesLists[i][choices[i]].totalSiblingScore; return choices; } else { // If transform paths are shared by multiple choices, call function recursively. float bestScore = 0; int[] bestChoices = choices; for (int i = 0; i < sharedIndices.Count; i++) { int[] altChoices = new int[choices.Length]; Array.Copy(choices, altChoices, choices.Length); // In each call, one of the choices retains their priority while the remaining are bumped one priority down. for (int j = 0; j < sharedIndices.Count; j++) { if (i != j) { if (sharedIndices[j] >= altChoices.Length) Debug.LogError("sharedIndices[j] (" + sharedIndices[j] + ") >= altChoices.Length (" + altChoices.Length + ")"); if (sharedIndices[j] >= childMatchesLists.Count) Debug.LogError("sharedIndices[j] (" + sharedIndices[j] + ") >= childMatchesLists.Count (" + childMatchesLists.Count + ")"); if (altChoices[sharedIndices[j]] < childMatchesLists[sharedIndices[j]].Count - 1) altChoices[sharedIndices[j]]++; else altChoices[sharedIndices[j]] = -1; } } float altScore; altChoices = GetBestChildMatchChoices(parentMatch, childMatchesLists, altChoices, out altScore); if (altScore > bestScore) { bestScore = altScore; bestChoices = altChoices; } } // Return the choices with the best score score = bestScore; return bestChoices; } } private void EvaluateBoneMatch(BoneMatch match, bool confirmedChoice) { match.score = 0; match.siblingScore = 0; // Things to copy from identical match: score, siblingScore, children, doMap // Iterate child BoneMappingitems List<List<BoneMatch>> childMatchesLists = new List<List<BoneMatch>>(); int intendedChildCount = 0; foreach (int c in match.item.GetChildren(m_MappingData)) { BoneMappingItem i = m_MappingData[c]; if (i.parent == match.item.bone) { intendedChildCount++; // RECURSIVE CALL List<BoneMatch> childMatches = RecursiveFindPotentialBoneMatches(match, i, confirmedChoice); if (childMatches == null || childMatches.Count == 0) continue; childMatchesLists.Add(childMatches); } } // Best best child matches bool sameAsParentOrChild = (match.bone == match.humanBoneParent.bone); if (childMatchesLists.Count > 0) { SimpleProfiler.Begin("GetBestChildMatches"); match.children = GetBestChildMatches(match, childMatchesLists); SimpleProfiler.End(); // Handle child matches foreach (BoneMatch childMatch in match.children) { // RECURSIVE CALL for debugging purposes if (kDebug && confirmedChoice) EvaluateBoneMatch(childMatch, confirmedChoice); // Transfer info from best child match to parent match.score += childMatch.score; if (kDebug) match.debugTracker.AddRange(childMatch.debugTracker); if (childMatch.bone == match.bone && childMatch.item.bone >= 0) sameAsParentOrChild = true; } } SimpleProfiler.Begin("ScoreBoneMatch"); // Keyword score the bone if it's not optional or if it's different from both parent bone and all child bones if (!match.item.optional || !sameAsParentOrChild) ScoreBoneMatch(match); SimpleProfiler.End(); // Rate bone according to how well it matches goal direction SimpleProfiler.Begin("MatchesDir"); if (match.item.dir != Vector3.zero) { Vector3 goalDir = match.item.dir; if (m_MappingIndexOffset >= (int)HumanBodyBones.LeftThumbProximal && m_MappingIndexOffset < (int)HumanBodyBones.RightThumbProximal) goalDir.x *= -1; Vector3 dir = (match.bone.position - match.humanBoneParent.bone.position).normalized; dir = Quaternion.Inverse(m_Orientation) * dir; float dirMatchingScore = Vector3.Dot(dir, goalDir) * (match.item.optional ? 5 : 10); match.siblingScore += dirMatchingScore; if (kDebug) match.debugTracker.Add("* " + dirMatchingScore + ": " + GetMatchString(match) + " matched dir (" + (match.bone.position - match.humanBoneParent.bone.position).normalized + " , " + goalDir + ")"); if (dirMatchingScore > 0) { match.score += 10; if (kDebug) match.debugTracker.Add(10 + ": " + GetMatchString(match) + " matched dir (" + (match.bone.position - match.humanBoneParent.bone.position).normalized + " , " + goalDir + ")"); } } SimpleProfiler.End(); // Give small score if bone matches side it belongs to. SimpleProfiler.Begin("MatchesSide"); if (m_MappingIndexOffset == 0) { int sideMatchingScore = GetBoneSideMatchPoints(match); if (match.parent.item.side == Side.None || sideMatchingScore < 0) { match.siblingScore += sideMatchingScore; if (kDebug) match.debugTracker.Add("* " + sideMatchingScore + ": " + GetMatchString(match) + " matched side"); } } SimpleProfiler.End(); // These criteria can not push a bone above the threshold, but they can help to break ties. if (match.score > 0) { // Reward optional bones being included if (match.item.optional && !sameAsParentOrChild) { match.score += 5; if (kDebug) match.debugTracker.Add(5 + ": " + GetMatchString(match) + " optional bone is included"); } // Handle end bones if (intendedChildCount == 0 && match.bone.childCount > 0) { // Reward end bones having a dummy child transform match.score += 1; if (kDebug) match.debugTracker.Add(1 + ": " + GetMatchString(match) + " has dummy child bone"); } // Give score to bones length ratio according to match with goal ratio. SimpleProfiler.Begin("LengthRatio"); if (match.item.lengthRatio != 0) { float parentLength = Vector3.Distance(match.bone.position, match.humanBoneParent.bone.position); if (parentLength == 0 && match.bone != match.humanBoneParent.bone) { match.score -= 1000; if (kDebug) match.debugTracker.Add((-1000) + ": " + GetMatchString(match.humanBoneParent) + " has zero length"); } float grandParentLength = Vector3.Distance(match.humanBoneParent.bone.position, match.humanBoneParent.humanBoneParent.bone.position); if (grandParentLength > 0) { float logRatio = Mathf.Log(parentLength / grandParentLength, 2); float logGoalRatio = Mathf.Log(match.item.lengthRatio, 2); float ratioScore = 10 * Mathf.Clamp(1 - 0.6f * Mathf.Abs(logRatio - logGoalRatio), 0, 1); match.score += ratioScore; if (kDebug) match.debugTracker.Add(ratioScore + ": parent " + GetMatchString(match.humanBoneParent) + " matched lengthRatio - " + parentLength + " / " + grandParentLength + " = " + (parentLength / grandParentLength) + " (" + logRatio + ") goal: " + match.item.lengthRatio + " (" + logGoalRatio + ")"); } } SimpleProfiler.End(); } // Only map optional bones if they're not the same as the parent or child. if (match.item.bone >= 0 && (!match.item.optional || !sameAsParentOrChild)) match.doMap = true; } private void ScoreBoneMatch(BoneMatch match) { int badKeywordScore = BoneHasBadKeyword(match.bone, match.item.keywords); match.score += badKeywordScore; if (kDebug && badKeywordScore != 0) match.debugTracker.Add(badKeywordScore + ": " + GetMatchString(match) + " matched bad keywords"); if (badKeywordScore < 0) return; int keywordScore = BoneHasKeyword(match.bone, match.item.keywords); match.score += keywordScore; if (kDebug && keywordScore != 0) match.debugTracker.Add(keywordScore + ": " + GetMatchString(match) + " matched keywords"); // If child bone with no required keywords, give a minimal score so it can still be included in mapping if (match.item.keywords.Length == 0 && match.item.alwaysInclude) { match.score += 1; if (kDebug) match.debugTracker.Add(1 + ": " + GetMatchString(match) + " always-include point"); } } } }
UnityCsReference/Editor/Mono/Inspector/Avatar/AvatarAutoMapper.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/Avatar/AvatarAutoMapper.cs", "repo_id": "UnityCsReference", "token_count": 22972 }
312
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEngine.Experimental.Rendering; using UnityEngine.SceneManagement; using UnityEngine.Rendering; using System; namespace UnityEditor { public static class CameraEditorUtils { static readonly Color k_ColorThemeCameraGizmo = new Color(233f / 255f, 233f / 255f, 233f / 255f, 128f / 255f); static readonly Color k_ColorThemeCameraSensorGizmo = new Color(180f / 255f, 180f / 255f, 180f / 255f, 128f / 255f); public static float GameViewAspectRatio => CameraEditor.GetGameViewAspectRatio(); static int s_MovingHandleId = 0; static Vector3 s_InitialFarMid; static readonly int[] s_FrustumHandleIds = { "CameraEditor_FrustumHandleTop".GetHashCode(), "CameraEditor_FrustumHandleBottom".GetHashCode(), "CameraEditor_FrustumHandleLeft".GetHashCode(), "CameraEditor_FrustumHandleRight".GetHashCode() }; public static Func<Camera> virtualCameraPreviewInstantiator { get => CameraPreviewUtils.s_VirtualCameraPreviewInstantiator; set => CameraPreviewUtils.s_VirtualCameraPreviewInstantiator = value; } public static void HandleFrustum(Camera c, int cameraEditorTargetIndex) { bool ContainsHandleId(int targetId) { foreach (int id in s_FrustumHandleIds) if (id == targetId) return true; return false; } if (c.projectionMatrixMode == Camera.ProjectionMatrixMode.Explicit) return; Color orgHandlesColor = Handles.color; Color slidersColor = k_ColorThemeCameraGizmo; slidersColor.a *= 2f; Handles.color = slidersColor; // get the corners of the far clip plane in world space var far = new Vector3[4]; float frustumAspect; if (c.usePhysicalProperties) { if (!TryGetSensorGateFrustum(c, null, far, out frustumAspect)) return; } else { if (!TryGetFrustum(c, null, far, out frustumAspect)) return; } var leftBottomFar = far[0]; var leftTopFar = far[1]; var rightTopFar = far[2]; var rightBottomFar = far[3]; // manage our own gui changed state, so we can use it for individual slider changes bool guiChanged = GUI.changed; Vector3 farMid = Vector3.Lerp(leftBottomFar, rightTopFar, 0.5f); if (s_MovingHandleId != 0) { if (!ContainsHandleId(GUIUtility.hotControl - cameraEditorTargetIndex)) s_MovingHandleId = GUIUtility.hotControl; else farMid = s_InitialFarMid; } else if (ContainsHandleId(GUIUtility.hotControl - cameraEditorTargetIndex)) { s_MovingHandleId = GUIUtility.hotControl; s_InitialFarMid = farMid; } // FOV handles // Top and bottom handles float halfHeight = -1.0f; Vector3 changedPosition = MidPointPositionSlider(s_FrustumHandleIds[0] + cameraEditorTargetIndex, leftTopFar, rightTopFar, c.transform.up); if (!GUI.changed) changedPosition = MidPointPositionSlider(s_FrustumHandleIds[1] + cameraEditorTargetIndex, leftBottomFar, rightBottomFar, -c.transform.up); if (GUI.changed) halfHeight = (changedPosition - farMid).magnitude; // Left and right handles GUI.changed = false; changedPosition = MidPointPositionSlider(s_FrustumHandleIds[2] + cameraEditorTargetIndex, rightBottomFar, rightTopFar, c.transform.right); if (!GUI.changed) changedPosition = MidPointPositionSlider(s_FrustumHandleIds[3] + cameraEditorTargetIndex, leftBottomFar, leftTopFar, -c.transform.right); if (GUI.changed) halfHeight = (changedPosition - farMid).magnitude / frustumAspect; // Update camera settings if changed if (halfHeight >= 0.0f) { Undo.RecordObject(c, "Adjust Camera"); if (c.orthographic) { c.orthographicSize = halfHeight; } else { Vector3 posUp = farMid + c.transform.up * halfHeight; Vector3 posDown = farMid - c.transform.up * halfHeight; Vector3 nearMid = farMid - c.transform.forward * c.farClipPlane; c.fieldOfView = Vector3.Angle((posDown - nearMid), (posUp - nearMid)); } guiChanged = true; } GUI.changed = guiChanged; Handles.color = orgHandlesColor; } public static void DrawFrustumGizmo(Camera camera) { var near = new Vector3[4]; var far = new Vector3[4]; float frustumAspect; if (camera.usePhysicalProperties) { if (TryGetSensorGateFrustum(camera, null, far, out frustumAspect)) { Color orgColor = Handles.color; Handles.color = k_ColorThemeCameraSensorGizmo; for (int i = 0; i < 4; ++i) { Handles.DrawLine(far[i], far[(i + 1) % 4]); } Handles.color = orgColor; } if (TryGetFrustum(camera, near, far, out frustumAspect)) { Color orgColor = Handles.color; Handles.color = k_ColorThemeCameraGizmo; for (int i = 0; i < 4; ++i) { Handles.DrawLine(far[i], far[(i + 1) % 4]); Handles.DrawLine(near[i], far[i]); Handles.DrawLine(near[i], near[(i + 1) % 4]); } Handles.color = orgColor; } } else if (TryGetFrustum(camera, near, far, out frustumAspect)) { Color orgColor = Handles.color; Handles.color = k_ColorThemeCameraGizmo; for (int i = 0; i < 4; ++i) { Handles.DrawLine(near[i], near[(i + 1) % 4]); Handles.DrawLine(far[i], far[(i + 1) % 4]); Handles.DrawLine(near[i], far[i]); } Handles.color = orgColor; } } // Returns near- and far-corners in this order: leftBottom, leftTop, rightTop, rightBottom // Assumes input arrays are of length 4 (if allocated) public static bool TryGetSensorGateFrustum(Camera camera, Vector3[] near, Vector3[] far, out float frustumAspect) { frustumAspect = GetFrustumAspectRatio(camera); if (frustumAspect < 0) return false; if (far != null) { Vector2 planeSize; planeSize.y = camera.farClipPlane * Mathf.Tan(Mathf.Deg2Rad * camera.fieldOfView * 0.5f); planeSize.x = planeSize.y * camera.sensorSize.x / camera.sensorSize.y; Vector3 rightOffset = camera.gameObject.transform.right * planeSize.x; Vector3 upOffset = camera.gameObject.transform.up * planeSize.y; Vector3 localAim = camera.GetLocalSpaceAim() * camera.farClipPlane; localAim.z = -localAim.z; Vector3 planePosition = camera.cameraToWorldMatrix.MultiplyPoint(localAim); far[0] = planePosition - rightOffset - upOffset; // leftBottom far[1] = planePosition - rightOffset + upOffset; // leftTop far[2] = planePosition + rightOffset + upOffset; // rightTop far[3] = planePosition + rightOffset - upOffset; // rightBottom } if (near != null) { Vector2 planeSize; planeSize.y = camera.nearClipPlane * Mathf.Tan(Mathf.Deg2Rad * camera.fieldOfView * 0.5f); planeSize.x = planeSize.y * camera.sensorSize.x / camera.sensorSize.y; Vector3 rightOffset = camera.gameObject.transform.right * planeSize.x; Vector3 upOffset = camera.gameObject.transform.up * planeSize.y; Vector3 localAim = camera.GetLocalSpaceAim() * camera.nearClipPlane; localAim.z = -localAim.z; Vector3 planePosition = camera.cameraToWorldMatrix.MultiplyPoint(localAim); near[0] = planePosition - rightOffset - upOffset; // leftBottom near[1] = planePosition - rightOffset + upOffset; // leftTop near[2] = planePosition + rightOffset + upOffset; // rightTop near[3] = planePosition + rightOffset - upOffset; // rightBottom } return true; } // Returns near- and far-corners in this order: leftBottom, leftTop, rightTop, rightBottom // Assumes input arrays are of length 4 (if allocated) public static bool TryGetFrustum(Camera camera, Vector3[] near, Vector3[] far, out float frustumAspect) { frustumAspect = GetFrustumAspectRatio(camera); if (frustumAspect < 0) return false; if (far != null) { if (camera.projectionMatrixMode == (int)Camera.ProjectionMatrixMode.Explicit) { far[0] = new Vector3(0, 0, camera.farClipPlane); // leftBottomFar far[1] = new Vector3(0, 1, camera.farClipPlane); // leftTopFar far[2] = new Vector3(1, 1, camera.farClipPlane); // rightTopFar far[3] = new Vector3(1, 0, camera.farClipPlane); // rightBottomFar for (int i = 0; i < 4; ++i) far[i] = camera.ViewportToWorldPoint(far[i]); } else { CalculateFrustumPlaneAt(camera, camera.farClipPlane, far); } } if (near != null) { if (camera.projectionMatrixMode == (int)Camera.ProjectionMatrixMode.Explicit) { near[0] = new Vector3(0, 0, camera.nearClipPlane); // leftBottomNear near[1] = new Vector3(0, 1, camera.nearClipPlane); // leftTopNear near[2] = new Vector3(1, 1, camera.nearClipPlane); // rightTopNear near[3] = new Vector3(1, 0, camera.nearClipPlane); // rightBottomNear for (int i = 0; i < 4; ++i) near[i] = camera.ViewportToWorldPoint(near[i]); } else { CalculateFrustumPlaneAt(camera, camera.nearClipPlane, near); } } return true; } private static void CalculateFrustumPlaneAt(Camera camera, float distance, Vector3[] plane) { Vector2 planeSize = camera.GetFrustumPlaneSizeAt(distance) * .5f; Vector3 rightOffset = camera.gameObject.transform.right * planeSize.x; Vector3 upOffset = camera.gameObject.transform.up * planeSize.y; Vector3 localAim = camera.GetLocalSpaceAim() * distance; localAim.z = -localAim.z; Vector3 planePosition = camera.cameraToWorldMatrix.MultiplyPoint(localAim); plane[0] = planePosition - rightOffset - upOffset; // leftBottom plane[1] = planePosition - rightOffset + upOffset; // leftTop plane[2] = planePosition + rightOffset + upOffset; // rightTop plane[3] = planePosition + rightOffset - upOffset; // rightBottom } public static bool IsViewportRectValidToRender(Rect normalizedViewPortRect) { if (normalizedViewPortRect.width <= 0f || normalizedViewPortRect.height <= 0f) return false; if (normalizedViewPortRect.x >= 1f || normalizedViewPortRect.xMax <= 0f) return false; if (normalizedViewPortRect.y >= 1f || normalizedViewPortRect.yMax <= 0f) return false; return true; } public static float GetFrustumAspectRatio(Camera camera) { var normalizedViewPortRect = camera.rect; if (normalizedViewPortRect.width <= 0f || normalizedViewPortRect.height <= 0f) return -1f; return camera.usePhysicalProperties ? camera.sensorSize.x / camera.sensorSize.y : GameViewAspectRatio * normalizedViewPortRect.width / normalizedViewPortRect.height; } public static Vector3 PerspectiveClipToWorld(Matrix4x4 clipToWorld, Vector3 viewPositionWS, Vector3 positionCS) { var tempCS = new Vector3(positionCS.x, positionCS.y, 0.95f); var result = clipToWorld.MultiplyPoint(tempCS); var r = result - viewPositionWS; return r.normalized * positionCS.z + viewPositionWS; } public static void GetFrustumPlaneAt(Matrix4x4 clipToWorld, Vector3 viewPosition, float distance, Vector3[] points) { points[0] = new Vector3(-1, -1, distance); // leftBottomFar points[1] = new Vector3(-1, 1, distance); // leftTopFar points[2] = new Vector3(1, 1, distance); // rightTopFar points[3] = new Vector3(1, -1, distance); // rightBottomFar for (var i = 0; i < 4; ++i) points[i] = PerspectiveClipToWorld(clipToWorld, viewPosition, points[i]); } static Vector3 MidPointPositionSlider(int controlID, Vector3 position1, Vector3 position2, Vector3 direction) { Vector3 midPoint = Vector3.Lerp(position1, position2, 0.5f); return Handles.Slider(controlID, midPoint, direction, HandleUtility.GetHandleSize(midPoint) * 0.03f, Handles.DotHandleCap, 0f); } } internal static class CameraPreviewUtils { static Camera s_PreviewCamera; static RenderTexture s_PreviewTexture; internal static Func<Camera> s_VirtualCameraPreviewInstantiator; internal struct PreviewSettings { public Vector2 size; public ulong overrideSceneCullingMask; public Scene scene; public bool useHDR; public float aspect => size.x / size.y; internal PreviewSettings(Vector2 previewSize) { size = previewSize; overrideSceneCullingMask = 0; scene = default; useHDR = false; } } class SavedStateForCameraPreview : IDisposable { Camera m_Target; public CameraType cameraType; public ulong overrideSceneCullingMask; public RenderTexture renderTarget; public Scene scene; public SavedStateForCameraPreview() { m_Target = null; renderTarget = null; overrideSceneCullingMask = 0; cameraType = CameraType.Game; scene = default; } public SavedStateForCameraPreview(Camera source) { m_Target = source; renderTarget = source.targetTexture; overrideSceneCullingMask = source.overrideSceneCullingMask; cameraType = source.cameraType; scene = source.scene; } public void Dispose() { m_Target.targetTexture = renderTarget; m_Target.overrideSceneCullingMask = overrideSceneCullingMask; m_Target.cameraType = cameraType; m_Target.scene = scene; } } static RenderTexture GetPreviewTexture(int width, int height, bool hdr) { if (s_PreviewTexture != null && (s_PreviewTexture.width != width || s_PreviewTexture.height != height || (GraphicsSettings.currentRenderPipeline == null && s_PreviewTexture.antiAliasing != QualitySettings.antiAliasing))) { s_PreviewTexture.Release(); } if (s_PreviewTexture == null) { GraphicsFormat format = (hdr) ? SystemInfo.GetGraphicsFormat(DefaultFormat.HDR) : SystemInfo.GetGraphicsFormat(DefaultFormat.LDR); s_PreviewTexture = new RenderTexture(width, height, 24, format); } if (GraphicsSettings.currentRenderPipeline == null) { // Built-in Render Pipeline, insure that antiAliasing is set to 1 or more s_PreviewTexture.antiAliasing = Math.Max(1, QualitySettings.antiAliasing); } else { // SRPs s_PreviewTexture.enableRandomWrite = true; } return s_PreviewTexture; } static Camera previewCamera { get { if (s_PreviewCamera == null && CameraEditorUtils.virtualCameraPreviewInstantiator != null) s_PreviewCamera = CameraEditorUtils.virtualCameraPreviewInstantiator(); if (s_PreviewCamera == null) { s_PreviewCamera = EditorUtility.CreateGameObjectWithHideFlags("Preview Camera", HideFlags.HideAndDontSave, typeof(Camera)).GetComponent<Camera>(); s_PreviewCamera.enabled = false; s_PreviewCamera.cameraType = CameraType.Preview; } return s_PreviewCamera; } } internal static RenderTexture GetPreview(Camera camera, PreviewSettings settings) { if (RenderPipeline.SupportsRenderRequest(camera, new RenderPipeline.StandardRequest())) return RenderInternal(camera, settings); return RenderPreviewWithCameraCopy(camera, settings); } internal static RenderTexture GetPreview(IViewpoint virtualCameraSource, PreviewSettings settings) { var sourceCamera = virtualCameraSource.TargetObject as Camera; if (sourceCamera) return GetPreview(sourceCamera, settings); // Viewpoint represents a virtual camera. ViewpointUtility.ApplyTransformData(virtualCameraSource, previewCamera.gameObject.transform); ViewpointUtility.ApplyCameraLensData(virtualCameraSource as ICameraLensData, previewCamera); return RenderInternal(previewCamera, settings); } static RenderTexture RenderPreviewWithCameraCopy(Camera sourceCamera, PreviewSettings settings) { previewCamera.CopyFrom(sourceCamera); // Only for Legacy/Built-in Render Pipeline. if (GraphicsSettings.currentRenderPipeline == null) { // Make sure to sync any Skybox component on the preview camera var dstSkybox = previewCamera.GetComponent<Skybox>(); if (dstSkybox == null) dstSkybox = previewCamera.gameObject.AddComponent<Skybox>(); var srcSkybox = sourceCamera.GetComponent<Skybox>(); if (srcSkybox && srcSkybox.enabled) { dstSkybox.enabled = true; dstSkybox.material = srcSkybox.material; } else { dstSkybox.enabled = false; } } Handles.EmitGUIGeometryForCamera(sourceCamera, previewCamera); return RenderInternal(previewCamera, settings); } static RenderTexture RenderInternal(Camera cameraToRender, PreviewSettings settings) { var rt = GetPreviewTexture((int)settings.size.x, (int)settings.size.y, settings.useHDR); // When sensor size is reduced, the previous frame is still visible behind so we need to clear the texture before rendering. if (cameraToRender.usePhysicalProperties) { RenderTexture oldRt = RenderTexture.active; RenderTexture.active = rt; GL.Clear(false, true, Color.clear); RenderTexture.active = oldRt; } using (new SavedStateForCameraPreview(cameraToRender)) { // make sure the preview camera is rendering the same stage as the SceneView is if (settings.overrideSceneCullingMask != 0) cameraToRender.overrideSceneCullingMask = settings.overrideSceneCullingMask; else cameraToRender.scene = settings.scene; RenderPipeline.StandardRequest request = new RenderPipeline.StandardRequest() { destination = rt, }; // Use RenderRequest API when the active SRP supports it for implementation-agnostic rendering. if (RenderPipeline.SupportsRenderRequest(cameraToRender, request)) cameraToRender.SubmitRenderRequest<RenderPipeline.StandardRequest>(request); else { // Built-in RP and SRPs that don't support the RenderRequest API will // render the old way. previewCamera.targetTexture = rt; previewCamera.Render(); } } return rt; } } }
UnityCsReference/Editor/Mono/Inspector/CameraEditorUtils.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/CameraEditorUtils.cs", "repo_id": "UnityCsReference", "token_count": 10773 }
313
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Collections.Generic; using System.Linq; namespace UnityEditor.IMGUI.Controls { internal abstract class AdvancedDropdownDataSource { private static readonly string kSearchHeader = L10n.Tr("Search"); private AdvancedDropdownItem m_MainTree; private AdvancedDropdownItem m_SearchTree; private AdvancedDropdownItem m_CurrentContextTree; private List<int> m_SelectedIDs = new List<int>(); public AdvancedDropdownItem mainTree { get { return m_MainTree; }} public AdvancedDropdownItem searchTree { get { return m_SearchTree; }} public List<int> selectedIDs { get { return m_SelectedIDs; }} public bool CurrentFolderContextualSearch { get; set; } protected AdvancedDropdownItem root { get { return m_MainTree; }} protected List<AdvancedDropdownItem> m_SearchableElements; internal delegate bool SearchMatchItemHandler(in AdvancedDropdownItem item, in string[] words, out bool didMatchStart); internal SearchMatchItemHandler searchMatchItem; internal IComparer<AdvancedDropdownItem> searchMatchItemComparer; public void ReloadData() { m_MainTree = FetchData(); } protected abstract AdvancedDropdownItem FetchData(); public void RebuildSearch(string search, AdvancedDropdownItem currentTree) { if (CurrentFolderContextualSearch && m_CurrentContextTree != currentTree && currentTree != searchTree) { m_SearchableElements = null; } m_CurrentContextTree = currentTree; m_SearchTree = Search(search); } protected bool AddMatchItem(AdvancedDropdownItem e, string name, string[] searchWords, List<AdvancedDropdownItem> matchesStart, List<AdvancedDropdownItem> matchesWithin) { var didMatchAll = true; var didMatchStart = false; if (searchMatchItem != null) { didMatchAll = searchMatchItem(e, searchWords, out didMatchStart); } else { // See if we match ALL the search words. for (var w = 0; w < searchWords.Length; w++) { var search = searchWords[w]; if (name.Contains(search)) { // If the start of the item matches the first search word, make a note of that. if (w == 0 && name.StartsWith(search)) didMatchStart = true; } else { // As soon as any word is not matched, we disregard this item. didMatchAll = false; break; } } } // We always need to match all search words. // If we ALSO matched the start, this item gets priority. if (didMatchAll) { if (didMatchStart) matchesStart.Add(e); else matchesWithin.Add(e); } return didMatchAll; } protected virtual AdvancedDropdownItem Search(string searchString) { if (m_SearchableElements == null) { BuildSearchableElements(); } if (string.IsNullOrEmpty(searchString)) return null; // Support multiple search words separated by spaces. var searchWords = searchString.ToLower().Split(' '); // We keep two lists. Matches that matches the start of an item always get first priority. var matchesStart = new List<AdvancedDropdownItem>(); var matchesWithin = new List<AdvancedDropdownItem>(); foreach (var e in m_SearchableElements) { var name = e.name.ToLower().Replace(" ", ""); AddMatchItem(e, name, searchWords, matchesStart, matchesWithin); } var searchTree = new AdvancedDropdownItem(kSearchHeader); if (searchMatchItemComparer == null) matchesStart.Sort(); else matchesStart.Sort(searchMatchItemComparer); foreach (var element in matchesStart) { searchTree.AddChild(element); } if (searchMatchItemComparer == null) matchesWithin.Sort(); else matchesWithin.Sort(searchMatchItemComparer); foreach (var element in matchesWithin) { searchTree.AddChild(element); } return searchTree; } void BuildSearchableElements() { m_SearchableElements = new List<AdvancedDropdownItem>(); BuildSearchableElements(CurrentFolderContextualSearch && m_CurrentContextTree != null ? m_CurrentContextTree : root); } void BuildSearchableElements(AdvancedDropdownItem item) { if (!item.children.Any()) { m_SearchableElements.Add(item); return; } foreach (var child in item.children) { BuildSearchableElements(child); } } } }
UnityCsReference/Editor/Mono/Inspector/Core/AdvancedDropdown/AdvancedDropdownDataSource.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/Core/AdvancedDropdown/AdvancedDropdownDataSource.cs", "repo_id": "UnityCsReference", "token_count": 2601 }
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.Collections.Generic; using System.Linq; using UnityEditor.Profiling; using UnityEngine; using UnityEngine.Scripting; using UnityEngine.UIElements; using Object = UnityEngine.Object; using AssetImporterEditor = UnityEditor.AssetImporters.AssetImporterEditor; namespace UnityEditor { [EditorWindowTitle(title = "Inspector", useTypeNameAsIconName = true)] internal class InspectorWindow : PropertyEditor, IPropertyView, IHasCustomMenu { static readonly List<InspectorWindow> m_AllInspectors = new List<InspectorWindow>(); static bool s_AllOptimizedGUIBlocksNeedsRebuild; [SerializeField] EditorGUIUtility.EditorLockTracker m_LockTracker = new EditorGUIUtility.EditorLockTracker(); [SerializeField] PreviewWindow m_PreviewWindow; readonly HashSet<DataMode> m_UserSupportedDataModes = new(4); IMGUIContainer m_TrackerResetter; public bool isLocked { get { return m_LockTracker.isLocked; } set { m_LockTracker.isLocked = value; } } public bool isVisible => m_Parent.actualView == this; internal void Awake() { AddInspectorWindow(this); } protected override void OnDestroy() { if (m_PreviewWindow is { IsFloatingWindow: true }) m_PreviewWindow.Close(); if (m_Tracker != null && !m_Tracker.Equals(ActiveEditorTracker.sharedTracker)) { // Ensure that m_Tracker is null before calling Destroy(), as a callback could be made to redraw the // InspectorWindow, and the native representation of the tracker will already be gone var trackerToDestroy = m_Tracker; m_Tracker = null; trackerToDestroy.Destroy(); } if (m_TrackerResetter != null) { m_TrackerResetter.Dispose(); m_TrackerResetter = null; } } protected override void OnEnable() { // Enable MSAA for UIElements inspectors, which is the only supported // antialiasing solution for UIElements. antiAliasing = 4; RefreshTitle(); AddInspectorWindow(this); base.OnEnable(); RestoreLockStateFromSerializedData(); if (m_LockTracker == null) m_LockTracker = new EditorGUIUtility.EditorLockTracker(); m_LockTracker.lockStateChanged.AddListener(LockStateChanged); m_Tracker.dataMode = GetDataModeController_Internal().dataMode; EditorApplication.projectWasLoaded += OnProjectWasLoaded; Selection.selectionChanged += OnSelectionChanged; AssemblyReloadEvents.afterAssemblyReload += OnAfterAssemblyReload; } private void OnAfterAssemblyReload() { // Case 1348788: After reloading the assemblies after a script compilation, // active editors are not rebuilt automatically. If a custom editor changed // the way it handles multi object editing you won't see the effect in the inspector unless // you change the selection. It is a minor issue. But this call makes sure to rebuild the active // editors if necessary. // Note: This is only a problem when adding the attribute CanEditMultipleObjects. When the attribute is not // there, the editor used for multi editing is the generic inspector. If you add the CanEditMultipleObjects attribute, // a refresh is triggered and we check if the editor instance is still valid, which is the case for the generic inspector // so we don't rebuild it. When removing the CanEditMultipleObjects, the refresh sees that the editor was the custom inspector // but its instance is no longer valid, so it rebuilds the inspector. if (EditorsForMultiEditingChanged()) tracker.ForceRebuild(); } void OnBecameVisible() { SceneView.SetActiveEditorsDirty(true); } void OnBecameInvisible() { SceneView.SetActiveEditorsDirty(); } private void OnProjectWasLoaded() { // EditorApplication.projectWasLoaded, which calls this, fires after OnEnabled // therefore the logic in OnEnabled already tried to de-serialize the locked objects, including those it only had InstanceIDs of // This needs to get fixed here as the InstanceIDs have been reshuffled with the new session and could resolving to random Objects if (m_InstanceIDsLockedBeforeSerialization.Count > 0) { // Game objects will have new instanceIDs in a new Unity session, so take out all objects that where reconstructed from InstanceIDs for (int i = m_InstanceIDsLockedBeforeSerialization.Count - 1; i >= 0; i--) { for (int j = m_ObjectsLockedBeforeSerialization.Count - 1; j >= 0; j--) { if (m_ObjectsLockedBeforeSerialization[j] == null || m_ObjectsLockedBeforeSerialization[j].GetInstanceID() == m_InstanceIDsLockedBeforeSerialization[i]) { m_ObjectsLockedBeforeSerialization.RemoveAt(j); break; } } } m_InstanceIDsLockedBeforeSerialization.Clear(); RestoreLockStateFromSerializedData(); } } private void OnSelectionChanged() { RebuildContentsContainers(); if (Selection.objects.Length == 0 && m_MultiEditLabel != null) { m_MultiEditLabel.RemoveFromHierarchy(); } if (isLocked) return; UpdateSupportedDataModesList(); } // Note: supportedModes is cleared before and sorted after this method is called protected override void OnUpdateSupportedDataModes(List<DataMode> supportedModes) { // Not showing data modes in debug if (m_InspectorMode != InspectorMode.Normal) return; m_UserSupportedDataModes.Clear(); DataModeSupportUtils.GetDataModeSupport(Selection.activeObject, Selection.activeContext, m_UserSupportedDataModes); supportedModes.AddRange(m_UserSupportedDataModes); } protected override void OnDisable() { base.OnDisable(); RemoveInspectorWindow(this); m_LockTracker?.lockStateChanged.RemoveListener(LockStateChanged); EditorApplication.projectWasLoaded -= OnProjectWasLoaded; Selection.selectionChanged -= OnSelectionChanged; AssemblyReloadEvents.afterAssemblyReload -= OnAfterAssemblyReload; } static internal void RepaintAllInspectors() { foreach (var win in m_AllInspectors) win.Repaint(); } internal static List<InspectorWindow> GetInspectors() { return m_AllInspectors; } [UsedByNativeCode] internal static void RedrawFromNative() { var propertyEditors = Resources.FindObjectsOfTypeAll<PropertyEditor>(); foreach (var propertyEditor in propertyEditors) propertyEditor.RebuildContentsContainers(); } internal static InspectorWindow[] GetAllInspectorWindows() { return m_AllInspectors.ToArray(); } public override void AddItemsToMenu(GenericMenu menu) { m_LockTracker.AddItemsToMenu(menu); menu.AddItem(EditorGUIUtility.TrTextContent("Properties..."), false, () => OpenPropertyEditor(GetInspectedObjects())); menu.AddSeparator(String.Empty); base.AddItemsToMenu(menu); } protected override void RefreshTitle() { string iconName = "UnityEditor.InspectorWindow"; if (m_InspectorMode == InspectorMode.Normal) titleContent = EditorGUIUtility.TrTextContentWithIcon("Inspector", iconName); else titleContent = EditorGUIUtility.TrTextContentWithIcon("Debug", iconName); } protected override void UpdateWindowObjectNameTitle() { // The inspector window doesn't not track the object name. } protected override void EnsureAppropriateTrackerIsInUse() { if (m_InspectorMode == InspectorMode.Normal && !isLocked) m_Tracker = ActiveEditorTracker.sharedTracker; else if (m_Tracker is null || m_Tracker.Equals(ActiveEditorTracker.sharedTracker)) m_Tracker = new ActiveEditorTracker(); } protected override void CreateTracker() { if (m_Tracker != null && m_Tracker.inspectorMode == m_InspectorMode) return; EnsureAppropriateTrackerIsInUse(); m_Tracker.inspectorMode = m_InspectorMode; m_Tracker.RebuildIfNecessary(); } protected virtual void ShowButton(Rect r) { m_LockTracker.ShowButton(r, Styles.lockButton); } private void LockStateChanged(bool lockState) { EnsureAppropriateTrackerIsInUse(); m_Tracker.isLocked = lockState; // Update the lock state of the ActiveEditorTracker in use if (m_Tracker.isLocked != lockState) { // Sync LockTracker lock state if m_Tracker failed to lock e.g. if user tried to lock Packages folder https://fogbugz.unity3d.com/f/cases/1173185/ m_LockTracker.isLocked = m_Tracker.isLocked; return; } if (lockState) PrepareLockedObjectsForSerialization(); else ClearSerializedLockedObjects(); if (lockState) tracker.RebuildIfNecessary(); else tracker.ForceRebuild(); } protected override bool CloseIfEmpty() { return false; } protected override void BeginRebuildContentContainers() { FlushAllOptimizedGUIBlocksIfNeeded(); if (m_TrackerResetter == null) { m_TrackerResetInserted = false; m_TrackerResetter = CreateIMGUIContainer(() => {}, "activeEditorTrackerResetter"); rootVisualElement.Insert(0, m_TrackerResetter); } } protected override bool BeginDrawPreviewAndLabels() { if (m_PreviewWindow && Event.current?.type == EventType.Repaint) m_PreviewWindow.Repaint(); return m_PreviewWindow == null; } protected override void EndDrawPreviewAndLabels(Event evt, Rect rect, Rect dragRect) { if (m_HasPreview || m_PreviewWindow != null) { if (EditorGUILayout.DropdownButton(Styles.menuIcon, FocusType.Passive, Styles.preOptionsButton)) { GenericMenu menu = new GenericMenu(); menu.AddItem( EditorGUIUtility.TrTextContent(m_PreviewWindow == null ? "Convert to Floating Window" : "Dock Preview to Inspector"), false, () => { if (m_PreviewWindow == null) { hasFloatingPreviewWindow = true; DetachPreview(false); } else { m_PreviewWindow.Close(); hasFloatingPreviewWindow = false; } }); menu.AddItem( EditorGUIUtility.TrTextContent(m_PreviewResizer.GetExpanded() ? "Minimize in Inspector" : "Restore in Inspector"), false, () => { m_PreviewResizer.SetExpanded(position, k_InspectorPreviewMinTotalHeight, k_MinAreaAbovePreview, kBottomToolbarHeight, dragRect, !m_PreviewResizer.GetExpanded()); }); menu.ShowAsContext(); } } // Detach preview on right click in preview title bar if (evt.type == EventType.MouseUp && evt.button == 1 && rect.Contains(evt.mousePosition) && m_PreviewWindow == null) DetachPreview(); } protected override void CreatePreviewEllipsisMenu(InspectorPreviewWindow window, PropertyEditor editor) { if (editor.previewWindow != null) { window.ClearEllipsisMenu(); window.AppendActionToEllipsisMenu( "Convert to Floating Window", (e) => { if (m_PreviewWindow == null) { DetachPreview(false); hasFloatingPreviewWindow = true; window.parent.Remove(window); } else { hasFloatingPreviewWindow = false; m_PreviewWindow.Close(); } }, a => hasFloatingPreviewWindow ? DropdownMenuAction.Status.Checked : DropdownMenuAction.Status.Normal); window.AppendActionToEllipsisMenu( "Minimize in Inspector", (e) => { editor.ExpandCollapsePreview(); }, a => !editor.showingPreview ? DropdownMenuAction.Status.Checked : DropdownMenuAction.Status.Normal ); } } private void DetachPreview(bool exitGUI = true) { if (Event.current != null) Event.current.Use(); m_PreviewWindow = CreateInstance(typeof(PreviewWindow)) as PreviewWindow; m_PreviewWindow.SetParentInspector(this); m_PreviewWindow.RebuildContentsContainers(); m_PreviewWindow.Show(); Repaint(); UIEventRegistration.MakeCurrentIMGUIContainerDirty(); if (exitGUI) GUIUtility.ExitGUI(); } [UsedByNativeCode] internal static void ShowWindow() { GetWindow(typeof(InspectorWindow)); } private static void FlushAllOptimizedGUIBlocksIfNeeded() { if (!s_AllOptimizedGUIBlocksNeedsRebuild) return; s_AllOptimizedGUIBlocksNeedsRebuild = false; } private void PrepareLockedObjectsForSerialization() { ClearSerializedLockedObjects(); if (m_Tracker != null && m_Tracker.isLocked) { m_Tracker.GetObjectsLockedByThisTracker(m_ObjectsLockedBeforeSerialization); // take out non persistent and track them in a list of instance IDs, because they wouldn't survive serialization as Objects for (int i = m_ObjectsLockedBeforeSerialization.Count - 1; i >= 0; i--) { if (!EditorUtility.IsPersistent(m_ObjectsLockedBeforeSerialization[i])) { if (m_ObjectsLockedBeforeSerialization[i] != null) m_InstanceIDsLockedBeforeSerialization.Add(m_ObjectsLockedBeforeSerialization[i].GetInstanceID()); m_ObjectsLockedBeforeSerialization.RemoveAt(i); } } } } private void ClearSerializedLockedObjects() { m_ObjectsLockedBeforeSerialization.Clear(); m_InstanceIDsLockedBeforeSerialization.Clear(); } internal void GetObjectsLocked(List<Object> objs) { m_Tracker.GetObjectsLockedByThisTracker(objs); } internal void SetObjectsLocked(List<Object> objs) { m_LockTracker.isLocked = true; m_Tracker.SetObjectsLockedByThisTracker(objs); } private void RestoreLockStateFromSerializedData() { if (m_Tracker == null) return; // try to retrieve all Objects from their stored instance ids in the list. // this is only used for non persistent objects (scene objects) if (m_InstanceIDsLockedBeforeSerialization.Count > 0) { for (int i = 0; i < m_InstanceIDsLockedBeforeSerialization.Count; i++) { Object instance = EditorUtility.InstanceIDToObject(m_InstanceIDsLockedBeforeSerialization[i]); //don't add null objects (i.e. if (instance) { m_ObjectsLockedBeforeSerialization.Add(instance); } } } for (int i = m_ObjectsLockedBeforeSerialization.Count - 1; i >= 0; i--) { if (m_ObjectsLockedBeforeSerialization[i] == null) { m_ObjectsLockedBeforeSerialization.RemoveAt(i); } } // set the tracker to the serialized list. if it contains nulls or is empty, the tracker will be set to unlocked // this fixes case 775007 m_Tracker.SetObjectsLockedByThisTracker(m_ObjectsLockedBeforeSerialization); // Sync LockTracker lock state with m_Tracker lock state in case m_ObjectsLockedBeforeSerialization is empty m_LockTracker.isLocked = m_Tracker.isLocked; // since this method likely got called during OnEnable, and rebuilding the tracker could call OnDisable on all Editors, // some of which might not have gotten their enable yet, the rebuilding needs to happen delayed in EditorApplication.update EditorApplication.CallDelayed(tracker.RebuildIfNecessary, 0f); } internal static bool AddInspectorWindow(InspectorWindow window) { if (m_AllInspectors.Contains(window)) { return false; } m_AllInspectors.Add(window); return true; } internal static void RemoveInspectorWindow(InspectorWindow window) { m_AllInspectors.Remove(window); } internal static void ApplyChanges() { foreach (var inspector in m_AllInspectors) { foreach (var editor in inspector.tracker.activeEditors) { if(editor.hasUnsavedChanges) editor.SaveChanges(); } } } internal static void RefreshInspectors() { foreach (var inspector in m_AllInspectors) { inspector.tracker.ForceRebuild(); } } internal override Object GetInspectedObject() { if (tracker.hasComponentsWhichCannotBeMultiEdited && !tracker.isLocked) return Selection.activeObject; Editor editor = InspectorWindowUtils.GetFirstNonImportInspectorEditor(tracker.activeEditors); if (editor == null) return null; return editor.target; } internal Object[] GetInspectedObjects() { if (tracker.hasComponentsWhichCannotBeMultiEdited && !tracker.isLocked) return Selection.objects; Editor editor = InspectorWindowUtils.GetFirstNonImportInspectorEditor(tracker.activeEditors); if (editor == null) return null; return editor.targets; } private bool EditorsForMultiEditingChanged() { foreach (var editor in tracker.activeEditors) { if (EditorForMultiEditingChanged(editor, editor.target)) return true; } return false; } private static bool EditorForMultiEditingChanged(Editor editor, Object target) { if (editor.targets.Length <= 1) return false; var currentEditorType = editor.GetType(); var expectedEditorType = CustomEditorAttributes.FindCustomEditorType(target, true); // Going from generic to generic inspector for multi editing is correctly handled. if (editor is GenericInspector && expectedEditorType == null) return false; return currentEditorType != expectedEditorType; } } }
UnityCsReference/Editor/Mono/Inspector/Core/InspectorWindow.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/Core/InspectorWindow.cs", "repo_id": "UnityCsReference", "token_count": 10303 }
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.Linq; using UnityEngine; using Object = UnityEngine.Object; namespace UnityEditor { internal static class InspectorWindowUtils { public struct LayoutGroupChecker : IDisposable { // cache the layout group we expect to have at the end of drawing this editor GUILayoutGroup m_ExpectedGroup; GUILayoutGroup expectedGroup => m_ExpectedGroup ?? (m_ExpectedGroup = GUILayoutUtility.current.topLevel); public void Dispose() { if (GUIUtility.guiIsExiting) { return; //Something has already requested an ExitGUI } // Check and try to cleanup layout groups. if (GUILayoutUtility.current.topLevel != expectedGroup) { if (!GUILayoutUtility.current.layoutGroups.Contains(expectedGroup)) { // We can't recover from this, so we error. Debug.LogError("Expected top level layout group missing! Too many GUILayout.EndScrollView/EndVertical/EndHorizontal?"); GUIUtility.ExitGUI(); } else { // We can recover from this, so we warning. Debug.LogWarning("Unexpected top level layout group! Missing GUILayout.EndScrollView/EndVertical/EndHorizontal?"); while (GUILayoutUtility.current.topLevel != expectedGroup) GUILayoutUtility.EndLayoutGroup(); } } } } public static void GetPreviewableTypes(out Dictionary<Type, List<Type>> previewableTypes) { // We initialize this list once per InspectorWindow, instead of globally. // This means that if the user is debugging an IPreviewable structure, // the InspectorWindow can be closed and reopened to refresh this list. previewableTypes = new Dictionary<Type, List<Type>>(); foreach (var type in TypeCache.GetTypesDerivedFrom<IPreviewable>()) { // we don't want Editor classes with preview here. if (type.IsSubclassOf(typeof(Editor))) { continue; } if (type.GetConstructor(Type.EmptyTypes) == null) { Debug.LogError($"{type} does not contain a default constructor, it will not be registered as a " + $"preview handler. Use the Initialize function to set up your object instead."); continue; } // Record only the types with a CustomPreviewAttribute. var attrs = type.GetCustomAttributes(typeof(CustomPreviewAttribute), false) as CustomPreviewAttribute[]; foreach (CustomPreviewAttribute previewAttr in attrs) { if (previewAttr.m_Type == null) { continue; } foreach (var customPreviewType in new[] { previewAttr.m_Type }.Concat(TypeCache.GetTypesDerivedFrom(previewAttr.m_Type))) { if (!previewableTypes.TryGetValue(customPreviewType, out var types)) { types = new List<Type>(); previewableTypes.Add(customPreviewType, types); } types.Add(type); } } } } public static Editor GetFirstNonImportInspectorEditor(Editor[] editors) { foreach (Editor e in editors) { // Check for target rather than the editor type itself, // because some importers use default inspector if (e.target is AssetImporter) { continue; } return e; } return null; } internal static bool IsExcludedClass(Object target) { return ModuleMetadata.GetModuleIncludeSettingForObject(target) == ModuleIncludeSetting.ForceExclude; } private static Dictionary<Type, ObsoleteAttribute> s_ObsoleteTypes; public static void DisplayDeprecationMessageIfNecessary(Editor editor) { if (!editor || !editor.target) { return; } if (s_ObsoleteTypes == null) { var obsoleteTypes = TypeCache.GetTypesWithAttribute<ObsoleteAttribute>(); s_ObsoleteTypes = new Dictionary<Type, ObsoleteAttribute>(obsoleteTypes.Count); foreach (var type in obsoleteTypes) { var attr = (ObsoleteAttribute)Attribute.GetCustomAttribute(type, typeof(ObsoleteAttribute)); s_ObsoleteTypes[type] = attr; } } if (!s_ObsoleteTypes.TryGetValue(editor.target.GetType(), out var obsoleteAttribute)) { return; } var message = string.IsNullOrEmpty(obsoleteAttribute.Message) ? "This component has been marked as obsolete." : obsoleteAttribute.Message; EditorGUILayout.HelpBox(message, obsoleteAttribute.IsError ? MessageType.Error : MessageType.Warning); } public static void DrawAddedComponentBackground(Rect position, Object[] targets, float adjust = 0) { if (Event.current.type == EventType.Repaint && targets.Length == 1) { Component comp = targets[0] as Component; if (comp != null && EditorGUIUtility.comparisonViewMode == EditorGUIUtility.ComparisonViewMode.None && PrefabUtility.GetCorrespondingConnectedObjectFromSource(comp.gameObject) != null && PrefabUtility.GetCorrespondingObjectFromSource(comp) == null) { // Ensure colored margin here for component body doesn't overlap colored margin from InspectorTitlebar, // and extends down to exactly touch the separator line between/after components. EditorGUI.DrawOverrideBackgroundApplicable(new Rect(position.x, position.y + 3 + adjust, position.width, position.height - 2)); } } } } }
UnityCsReference/Editor/Mono/Inspector/Core/Utils/InspectorWindowUtils.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/Core/Utils/InspectorWindowUtils.cs", "repo_id": "UnityCsReference", "token_count": 3281 }
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 UnityEditor; namespace UnityEditor { [CustomEditor(typeof(Font))] [CanEditMultipleObjects] internal class FontInspector : Editor { public override void OnInspectorGUI() { foreach (Object o in targets) { // Dont draw the default inspector for imported font assets. // It can be very slow when there is a lot of embedded font data, // and the presented information is not useful to the user anyways. // We still need it for editable, "Custom Font" assets, though. if (o.hideFlags == HideFlags.NotEditable) return; } DrawDefaultInspector(); } } }
UnityCsReference/Editor/Mono/Inspector/FontInspector.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/FontInspector.cs", "repo_id": "UnityCsReference", "token_count": 385 }
317
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; namespace UnityEditor { internal class LegacyIlluminShaderGUI : ShaderGUI { public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props) { base.OnGUI(materialEditor, props); materialEditor.LightmapEmissionProperty(0); // We assume that illumin shader always has emission foreach (Material material in materialEditor.targets) material.globalIlluminationFlags &= ~MaterialGlobalIlluminationFlags.EmissiveIsBlack; } } } // namespace UnityEditor
UnityCsReference/Editor/Mono/Inspector/LegacyIlluminShaderGUI.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/LegacyIlluminShaderGUI.cs", "repo_id": "UnityCsReference", "token_count": 266 }
318
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEditor; using UnityEditor.Build; using UnityEditorInternal; using UnityEngine.Rendering; using UnityEngine.UIElements; using UnityEditor.Callbacks; namespace UnityEditor { [CustomEditor(typeof(MemorySettings))] internal class MemorySettingsEditor : Editor { class Content { public static readonly GUIContent kGeneralSettingsWarning = EditorGUIUtility.TrTextContent("Changing Memory setup values can cause severe performance degradation."); public static readonly GUIContent kEditorSettingsWarning = EditorGUIUtility.TrTextContent("Changing the memory setup for editor will update the ProjectSettings/boot.config file. This file is loaded at Editor startup, so will take effect at next startup."); public static readonly GUIContent kMainAllocatorsTitle = EditorGUIUtility.TrTextContent("Main Allocators"); public static readonly GUIContent kMainAllocatorTitle = EditorGUIUtility.TrTextContent("Main Allocator"); public static readonly GUIContent kMainAllocatorBlockSize = EditorGUIUtility.TrTextContent("Main Thread Block Size", "Block size used by main thread allocator"); public static readonly GUIContent kThreadAllocatorBlockSize = EditorGUIUtility.TrTextContent("Shared Thread Block Size", "Block size used by shared thread allocator"); public static readonly GUIContent kGfxAllocatorTitle = EditorGUIUtility.TrTextContent("Gfx Allocator"); public static readonly GUIContent kMainGfxBlockSize = EditorGUIUtility.TrTextContent("Main Thread Block Size", "Block size used by main thread for gfx allocations"); public static readonly GUIContent kThreadGfxBlockSize = EditorGUIUtility.TrTextContent("Shared Thread Block Size", "Block size used by shared threads for gfx allocations"); public static readonly GUIContent kExtraAllocatorTitle = EditorGUIUtility.TrTextContent("Other Allocators"); public static readonly GUIContent kCacheBlockSize = EditorGUIUtility.TrTextContent("File Cache Block Size", "Block size used by file cache allocator. Setting this value to 0 will cause the file cache allocations to be passed to the main allocator"); public static readonly GUIContent kTypetreeBlockSize = EditorGUIUtility.TrTextContent("Type Tree Block Size", "Block size used by the tree allocator. Setting this value to 0 will cause the type tree allocations to be passed to the main allocator"); public static readonly GUIContent kTempAllocatorTitle_Player = EditorGUIUtility.TrTextContent("Fast Per Thread Temporary Allocators", "Block size can grow to twice the initial size"); public static readonly GUIContent kTempAllocatorTitle_Editor = EditorGUIUtility.TrTextContent("Fast Per Thread Temporary Allocators", "Block size can grow to 8 times the initial size"); public static readonly GUIContent kTempAllocatorSizeMain = EditorGUIUtility.TrTextContent("Main Thread Block Size", "Initial size for main thread temp allocator"); public static readonly GUIContent kTempAllocatorSizeJobWorker = EditorGUIUtility.TrTextContent("Job Worker Block Size", "Block size for worker job temp allocators"); public static readonly GUIContent kTempAllocatorSizeBackgroundWorker = EditorGUIUtility.TrTextContent("Background Job Worker Block Size", "Block size for worker job temp allocators"); public static readonly GUIContent kTempAllocatorSizePreloadManager = EditorGUIUtility.TrTextContent("Preload Block Size", "Block size for worker job temp allocators"); public static readonly GUIContent kTempAllocatorSizeAudioWorker = EditorGUIUtility.TrTextContent("Audio Worker Block Size", "Block size for worker job temp allocators"); public static readonly GUIContent kTempAllocatorSizeCloudWorker = EditorGUIUtility.TrTextContent("Cloud Worker Block Size", "Block size for worker job temp allocators"); public static readonly GUIContent kTempAllocatorSizeGfx = EditorGUIUtility.TrTextContent("Gfx Thread Block Size", "Block size for worker job temp allocators"); public static readonly GUIContent kTempAllocatorSizeGIBakingWorker = EditorGUIUtility.TrTextContent("GI Baking Block Size", "Block size for GI baking workers temp allocators"); public static readonly GUIContent kTempAllocatorSizeNavMeshWorker = EditorGUIUtility.TrTextContent("NavMesh Worker Block Size", "Block size for worker job temp allocators"); // TODO: guard input parameters public static readonly GUIContent kJobTempAllocatorTitle = EditorGUIUtility.TrTextContent("Fast Thread Shared Temporary Allocators"); public static readonly GUIContent kJobTempAllocatorBlockSize = EditorGUIUtility.TrTextContent("Job Allocator Block Size", "Block size for worker job temp allocators. Can grow to 64 blocks"); public static readonly GUIContent kBackgroundJobTempAllocatorBlockSize = EditorGUIUtility.TrTextContent("Background Job Allocator Block Size", "Block size for background worker job temp allocators. Can grow to 64 blocks"); public static readonly GUIContent kJobTempAllocatorReducedBlockSize = EditorGUIUtility.TrTextContent("Job Allocator Block Sizes on low memory platform", "Block sizes for job and background if platform has less than 2GB memory"); public static readonly GUIContent kBucketAllocatorTitle = EditorGUIUtility.TrTextContent("Shared Bucket Allocator"); public static readonly GUIContent kBucketAllocatorGranularity = EditorGUIUtility.TrTextContent("Bucket Allocator Granularity", "Bucket allocator bucket granularity"); public static readonly GUIContent kBucketAllocatorBucketsCount = EditorGUIUtility.TrTextContent("Bucket Allocator BucketCount", "Number of bucket size increments of bucket granularity"); public static readonly GUIContent kBucketAllocatorBlockSize = EditorGUIUtility.TrTextContent("Bucket Allocator Block Size", "Bucket allocator block size"); public static readonly GUIContent kBucketAllocatorBlockCount = EditorGUIUtility.TrTextContent("Bucket Allocator Block Count", "Bucket allocator block count"); public static readonly GUIContent kProfilerAllocatorTitle = EditorGUIUtility.TrTextContent("Profiler Allocators"); public static readonly GUIContent kProfilerBlockSize = EditorGUIUtility.TrTextContent("Profiler Block Size", "Block size used by main profiler allocations"); public static readonly GUIContent kProfilerEditorBlockSize = EditorGUIUtility.TrTextContent("Editor Profiler Block Size", "Editor only: Block size used by editor specific profiler allocations"); public static readonly GUIContent kProfilerBucketAllocatorTitle = EditorGUIUtility.TrTextContent("Shared Profiler Bucket Allocator"); public static readonly GUIContent kProfilerBucketAllocatorGranularity = EditorGUIUtility.TrTextContent("Bucket Allocator Granularity", "Bucket allocator bucket granularity"); public static readonly GUIContent kProfilerBucketAllocatorBucketsCount = EditorGUIUtility.TrTextContent("Bucket Allocator BucketCount", "Number of bucket size increments of bucket granularity"); public static readonly GUIContent kProfilerBucketAllocatorBlockSize = EditorGUIUtility.TrTextContent("Bucket Allocator Block Size", "Bucket allocator block size"); public static readonly GUIContent kProfilerBucketAllocatorBlockCount = EditorGUIUtility.TrTextContent("Bucket Allocator Block Count", "Bucket allocator block count"); public static readonly GUIContent kEditorLabel = EditorGUIUtility.TrTextContent("Editor", "Editor settings"); public static readonly GUIContent kPlayerLabel = EditorGUIUtility.TrTextContent("Players", "player settings"); } class Styles { public static readonly GUIStyle lockButton = "IN LockButton"; public static readonly GUIStyle titleGroupHeader = new GUIStyle(EditorStyles.toolbar) { margin = new RectOffset() }; public static readonly GUIStyle settingsFramebox = new GUIStyle(EditorStyles.frameBox) { padding = new RectOffset(1, 1, 1, 0) }; public static readonly string warningDialogTitle = L10n.Tr("Edit memory settings"); public static readonly string warningDialogText = L10n.Tr("Changing default memory setting can have severe negative impact on performance. Are you sure you want to continue?"); public static readonly string okDialogButton = L10n.Tr("Ok"); public static readonly string cancelDialogButton = L10n.Tr("Cancel"); } const string kWarningDialogSessionKey = "MemorySettingsWarning"; SerializedProperty m_PlatformMemorySettingsProperty; SerializedProperty m_EditorMemorySettingsProperty; SerializedProperty m_DefaultMemorySettingsProperty; static Styles s_Styles; static SettingsProvider s_SettingsProvider; int m_SelectedPlatform = 0; BuildPlatform[] m_ValidPlatforms; const int kMaxGroupCount = 10; bool[] m_ShowSettingsUI = new bool[kMaxGroupCount]; AnimatedValues.AnimBool[] m_SettingsAnimator = new AnimatedValues.AnimBool[kMaxGroupCount]; Dictionary<BuildTarget, SerializedProperty> m_MemorySettingsDictionary; public void OnEnable() { m_ValidPlatforms = BuildPlatforms.instance.GetValidPlatforms(true).ToArray(); m_EditorMemorySettingsProperty = serializedObject.FindProperty("m_EditorMemorySettings"); m_PlatformMemorySettingsProperty = serializedObject.FindProperty("m_PlatformMemorySettings"); m_DefaultMemorySettingsProperty = serializedObject.FindProperty("m_DefaultMemorySettings"); m_MemorySettingsDictionary = new Dictionary<BuildTarget, SerializedProperty>(); foreach (SerializedProperty prop in m_PlatformMemorySettingsProperty) { m_MemorySettingsDictionary.Add((BuildTarget)prop.FindPropertyRelative("first").intValue, prop.FindPropertyRelative("second")); } for (var i = 0; i < m_SettingsAnimator.Length; i++) m_SettingsAnimator[i] = new AnimatedValues.AnimBool(m_ShowSettingsUI[i], RepaintSettingsEditorWindow); } bool m_EditorSelected = true; static GUIStyle s_TabOnlyOne; static GUIStyle s_TabFirst; static GUIStyle s_TabMiddle; static GUIStyle s_TabLast; static Rect GetTabRect(Rect rect, int tabIndex, int tabCount, out GUIStyle tabStyle) { if (s_TabOnlyOne == null) { s_TabOnlyOne = "Tab onlyOne"; s_TabFirst = "Tab first"; s_TabMiddle = "Tab middle"; s_TabLast = "Tab last"; } tabStyle = s_TabMiddle; if (tabCount == 1) { tabStyle = s_TabOnlyOne; } else if (tabIndex == 0) { tabStyle = s_TabFirst; } else if (tabIndex == (tabCount - 1)) { tabStyle = s_TabLast; } float tabWidth = rect.width / tabCount; int left = Mathf.RoundToInt(tabIndex * tabWidth); int right = Mathf.RoundToInt((tabIndex + 1) * tabWidth); return new Rect(rect.x + left, rect.y, right - left, EditorGUI.kTabButtonHeight); } void RepaintSettingsEditorWindow() { // Invoking a Repaint on an Editor instantiated via AssetSettingsProvider does not currently work due to a bug. So instead we store a reference to the settings provider and repaint it directly. s_SettingsProvider?.Repaint(); } private bool BeginGroup(int index, GUIContent title) { Debug.Assert(kMaxGroupCount > index, "Max group count in MemorySettings is too low"); var indentLevel = EditorGUI.indentLevel; EditorGUILayout.BeginVertical(GUILayout.Height(20)); EditorGUILayout.BeginHorizontal((indentLevel == 0) ? Styles.titleGroupHeader : GUIStyle.none); Rect r = GUILayoutUtility.GetRect(title, EditorStyles.inspectorTitlebarText); r = EditorGUI.IndentedRect(r); EditorGUI.indentLevel = 0; m_ShowSettingsUI[index] = EditorGUI.FoldoutTitlebar(r, title, m_ShowSettingsUI[index], true, EditorStyles.inspectorTitlebarFlat, EditorStyles.inspectorTitlebarText); EditorGUI.indentLevel = indentLevel; EditorGUILayout.EndHorizontal(); m_SettingsAnimator[index].target = m_ShowSettingsUI[index]; var visible = EditorGUILayout.BeginFadeGroup(m_SettingsAnimator[index].faded); EditorGUI.indentLevel++; EditorGUILayout.Space(); return visible; } private void EndGroup() { EditorGUI.indentLevel--; EditorGUILayout.Space(); EditorGUILayout.EndFadeGroup(); EditorGUILayout.EndVertical(); } enum SizeEnum { B, KB, MB, } private void OptionalVariableField(SerializedProperty settings, string variablename, GUIContent label, bool useBytes = true) { const int k_FieldSpacing = 2; if (s_Styles == null) s_Styles = new Styles(); var prop = settings.FindPropertyRelative(variablename); var defaultValueProp = m_DefaultMemorySettingsProperty.FindPropertyRelative(variablename); var overrideText = new GUIContent(string.Empty, "Override Default"); var toggleSize = EditorStyles.toggle.CalcSize(overrideText); var enumValue = SizeEnum.MB; var sizeEnumWidth = EditorStyles.popup.CalcSize(GUIContent.Temp(enumValue.ToString())).x; var minWidth = EditorGUI.indent + EditorGUIUtility.labelWidth + EditorGUI.kSpacing + toggleSize.x + EditorGUI.kSpacing + EditorGUIUtility.fieldWidth + EditorGUI.kSpacing + sizeEnumWidth; var rect = GUILayoutUtility.GetRect(minWidth, EditorGUIUtility.singleLineHeight + k_FieldSpacing); rect.height -= k_FieldSpacing; rect = EditorGUI.IndentedRect(rect); var indent = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; var labelRect = rect; labelRect.width = EditorGUIUtility.labelWidth; GUI.Label(labelRect, label); var toggleRect = rect; toggleRect.xMin = labelRect.xMax + EditorGUI.kSpacing; toggleRect.size = toggleSize; var useDefault = prop.intValue < 0; var newuseDefault = GUI.Toggle(toggleRect, useDefault, overrideText, Styles.lockButton); var fieldRect = rect; fieldRect.xMin = toggleRect.xMax + EditorGUI.kSpacing; fieldRect.xMax = Mathf.Max(fieldRect.xMax - sizeEnumWidth - EditorGUI.kSpacing, fieldRect.xMin + EditorGUIUtility.fieldWidth); var defaultValue = defaultValueProp.intValue; var sizeEnumRect = rect; sizeEnumRect.xMin = fieldRect.xMax + EditorGUI.kSpacing; sizeEnumRect.width = sizeEnumWidth; if (newuseDefault != useDefault) { if (!newuseDefault) { var result = EditorUtility.DisplayDialog(Styles.warningDialogTitle, Styles.warningDialogText, Styles.okDialogButton, Styles.cancelDialogButton, DialogOptOutDecisionType.ForThisSession, kWarningDialogSessionKey); if (!result) newuseDefault = true; } prop.intValue = newuseDefault ? -1 : defaultValue; } if (newuseDefault) { using (new EditorGUI.DisabledScope(true)) { int displayValue = defaultValue; if (useBytes) { enumValue = SizeEnum.B; if ((defaultValue % (1024 * 1024)) == 0) { enumValue = SizeEnum.MB; displayValue /= 1024 * 1024; } else if ((defaultValue % 1024) == 0) { enumValue = SizeEnum.KB; displayValue /= 1024; } } EditorGUI.IntField(fieldRect, displayValue); if (useBytes) EditorGUI.EnumPopup(sizeEnumRect, enumValue); } } else { int factor = 1; enumValue = SizeEnum.B; int oldIntValue = prop.intValue; if (useBytes) { if ((oldIntValue % (1024 * 1024)) == 0) { factor = 1024 * 1024; enumValue = SizeEnum.MB; } else if ((oldIntValue % 1024) == 0) { factor = 1024; enumValue = SizeEnum.KB; } } var newIntValue = factor * EditorGUI.DelayedIntField(fieldRect, oldIntValue / factor); if (useBytes) { SizeEnum newEnumValue = (SizeEnum)EditorGUI.EnumPopup(sizeEnumRect, enumValue); if (newEnumValue != enumValue) { if (newEnumValue == SizeEnum.MB) { if (enumValue == SizeEnum.KB) newIntValue *= 1024; else newIntValue *= 1024 * 1024; } if (newEnumValue == SizeEnum.KB) { if (enumValue == SizeEnum.MB) newIntValue /= 1024; else newIntValue *= 1024; } if (newEnumValue == SizeEnum.B) { if (enumValue == SizeEnum.MB) newIntValue /= 1024 * 1024; else newIntValue /= 1024; } } } prop.intValue = newIntValue; } EditorGUI.indentLevel = indent; } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUI.BeginChangeCheck(); EditorGUILayout.HelpBox(Content.kGeneralSettingsWarning.text, MessageType.Warning, true); Rect r = EditorGUILayout.BeginVertical(Styles.settingsFramebox); GUIStyle buttonStyle = null; Rect buttonRect = GetTabRect(r, 0, 2, out buttonStyle); if (GUI.Toggle(buttonRect, m_EditorSelected, Content.kEditorLabel, buttonStyle)) m_EditorSelected = true; buttonRect = GetTabRect(r, 1, 2, out buttonStyle); if (GUI.Toggle(buttonRect, !m_EditorSelected, Content.kPlayerLabel, buttonStyle)) m_EditorSelected = false; GUILayoutUtility.GetRect(10, EditorGUI.kTabButtonHeight); EditorGUI.EndChangeCheck(); SerializedProperty currentSettings; if (m_EditorSelected) { EditorGUI.BeginChangeCheck(); GUILayout.Label("Settings for Editor"); EditorGUILayout.HelpBox(Content.kEditorSettingsWarning.text, MessageType.Warning, true); EditorGUILayout.Space(); currentSettings = m_EditorMemorySettingsProperty; MemorySettingsUtils.InitializeDefaultsForPlatform(-1); } else { GUILayout.Label("Settings for Players"); m_SelectedPlatform = EditorGUILayout.BeginPlatformGrouping(m_ValidPlatforms, null, Styles.settingsFramebox); GUILayout.Label(string.Format(L10n.Tr("Settings for {0}"), m_ValidPlatforms[m_SelectedPlatform].title.text)); if (!m_MemorySettingsDictionary.TryGetValue(m_ValidPlatforms[m_SelectedPlatform].defaultTarget, out currentSettings)) { MemorySettingsUtils.SetPlatformDefaultValues((int)m_ValidPlatforms[m_SelectedPlatform].defaultTarget); serializedObject.Update(); OnEnable(); m_MemorySettingsDictionary.TryGetValue(m_ValidPlatforms[m_SelectedPlatform].defaultTarget, out currentSettings); } MemorySettingsUtils.InitializeDefaultsForPlatform((int)m_ValidPlatforms[m_SelectedPlatform].defaultTarget); } if (BeginGroup(0, Content.kMainAllocatorsTitle)) { if (BeginGroup(1, Content.kMainAllocatorTitle)) { OptionalVariableField(currentSettings, "m_MainAllocatorBlockSize", Content.kMainAllocatorBlockSize); OptionalVariableField(currentSettings, "m_ThreadAllocatorBlockSize", Content.kThreadAllocatorBlockSize); } EndGroup(); if (BeginGroup(2, Content.kGfxAllocatorTitle)) { OptionalVariableField(currentSettings, "m_MainGfxBlockSize", Content.kMainGfxBlockSize); OptionalVariableField(currentSettings, "m_ThreadGfxBlockSize", Content.kThreadGfxBlockSize); } EndGroup(); if (BeginGroup(3, Content.kExtraAllocatorTitle)) { OptionalVariableField(currentSettings, "m_CacheBlockSize", Content.kCacheBlockSize); OptionalVariableField(currentSettings, "m_TypetreeBlockSize", Content.kTypetreeBlockSize); } EndGroup(); if (BeginGroup(4, Content.kBucketAllocatorTitle)) { OptionalVariableField(currentSettings, "m_BucketAllocatorGranularity", Content.kBucketAllocatorGranularity); OptionalVariableField(currentSettings, "m_BucketAllocatorBucketsCount", Content.kBucketAllocatorBucketsCount, false); OptionalVariableField(currentSettings, "m_BucketAllocatorBlockSize", Content.kBucketAllocatorBlockSize); OptionalVariableField(currentSettings, "m_BucketAllocatorBlockCount", Content.kBucketAllocatorBlockCount, false); } EndGroup(); } EndGroup(); if (BeginGroup(5, m_EditorSelected ? Content.kTempAllocatorTitle_Editor : Content.kTempAllocatorTitle_Player)) { OptionalVariableField(currentSettings, "m_TempAllocatorSizeMain", Content.kTempAllocatorSizeMain); OptionalVariableField(currentSettings, "m_TempAllocatorSizeJobWorker", Content.kTempAllocatorSizeJobWorker); OptionalVariableField(currentSettings, "m_TempAllocatorSizeBackgroundWorker", Content.kTempAllocatorSizeBackgroundWorker); OptionalVariableField(currentSettings, "m_TempAllocatorSizePreloadManager", Content.kTempAllocatorSizePreloadManager); OptionalVariableField(currentSettings, "m_TempAllocatorSizeAudioWorker", Content.kTempAllocatorSizeAudioWorker); OptionalVariableField(currentSettings, "m_TempAllocatorSizeCloudWorker", Content.kTempAllocatorSizeCloudWorker); OptionalVariableField(currentSettings, "m_TempAllocatorSizeGfx", Content.kTempAllocatorSizeGfx); OptionalVariableField(currentSettings, "m_TempAllocatorSizeGIBakingWorker", Content.kTempAllocatorSizeGIBakingWorker); OptionalVariableField(currentSettings, "m_TempAllocatorSizeNavMeshWorker", Content.kTempAllocatorSizeNavMeshWorker); } EndGroup(); if (BeginGroup(6, Content.kJobTempAllocatorTitle)) { OptionalVariableField(currentSettings, "m_JobTempAllocatorBlockSize", Content.kJobTempAllocatorBlockSize); OptionalVariableField(currentSettings, "m_BackgroundJobTempAllocatorBlockSize", Content.kBackgroundJobTempAllocatorBlockSize); OptionalVariableField(currentSettings, "m_JobTempAllocatorReducedBlockSize", Content.kJobTempAllocatorReducedBlockSize); } EndGroup(); if (BeginGroup(7, Content.kProfilerAllocatorTitle)) { OptionalVariableField(currentSettings, "m_ProfilerBlockSize", Content.kProfilerBlockSize); if (m_EditorSelected) OptionalVariableField(currentSettings, "m_ProfilerEditorBlockSize", Content.kProfilerEditorBlockSize); if (BeginGroup(8, Content.kProfilerBucketAllocatorTitle)) { OptionalVariableField(currentSettings, "m_ProfilerBucketAllocatorGranularity", Content.kProfilerBucketAllocatorGranularity); OptionalVariableField(currentSettings, "m_ProfilerBucketAllocatorBucketsCount", Content.kProfilerBucketAllocatorBucketsCount, false); OptionalVariableField(currentSettings, "m_ProfilerBucketAllocatorBlockSize", Content.kProfilerBucketAllocatorBlockSize); OptionalVariableField(currentSettings, "m_ProfilerBucketAllocatorBlockCount", Content.kProfilerBucketAllocatorBlockCount, false); } EndGroup(); } EndGroup(); if (m_EditorSelected) { if (EditorGUI.EndChangeCheck()) { serializedObject.ApplyModifiedProperties(); MemorySettingsUtils.WriteEditorMemorySettings(); } } else { EditorGUILayout.EndPlatformGrouping(); serializedObject.ApplyModifiedProperties(); } EditorGUILayout.EndVertical(); } [SettingsProvider] internal static SettingsProvider CreateProjectSettingsProvider() { var provider = AssetSettingsProvider.CreateProviderFromAssetPath( "Project/Memory Settings", "ProjectSettings/MemorySettings.asset", SettingsProvider.GetSearchKeywordsFromGUIContentProperties<Content>()); s_SettingsProvider = provider; return provider; } } }
UnityCsReference/Editor/Mono/Inspector/MemorySettingsEditor.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/MemorySettingsEditor.cs", "repo_id": "UnityCsReference", "token_count": 11563 }
319
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; using UnityEditor.Build; using UnityEditor.Modules; using UnityEditor.PlatformSupport; using UnityEngine; namespace UnityEditor { internal class PlayerSettingsIconsEditor { class SettingsContent { public static readonly GUIContent iconTitle = EditorGUIUtility.TrTextContent("Icon"); public static readonly GUIContent defaultIcon = EditorGUIUtility.TrTextContent("Default Icon"); public static readonly GUIContent UIPrerenderedIcon = EditorGUIUtility.TrTextContent("Prerendered Icon"); public static string undoChangedIconString { get { return LocalizationDatabase.GetLocalizedString("Changed Icon"); } } } // Icon layout constants const int kSlotSize = 64; const int kMaxPreviewSize = 96; const int kIconSpacing = 6; PlayerSettingsEditor m_Owner; int m_SelectedPlatform = 0; BuildPlatform[] m_ValidPlatforms; // Serialized icons SerializedProperty m_PlatformIcons; SerializedProperty m_LegacyPlatformIcons; SerializedProperty m_UIPrerenderedIcon; // Deserialized icons (all platforms) BuildTargetIcons[] m_AllIcons; // Deserialized legacy icons (all platforms) LegacyBuildTargetIcons[] m_AllLegacyIcons; // Required icons for platform. Provided by platform extension Dictionary<PlatformIconKind, PlatformIcon[]> m_RequiredIcons; public PlayerSettingsIconsEditor(PlayerSettingsEditor owner) { m_Owner = owner; } public void OnEnable() { m_ValidPlatforms = BuildPlatforms.instance.GetValidPlatforms(true).ToArray(); m_PlatformIcons = m_Owner.FindPropertyAssert("m_BuildTargetPlatformIcons"); m_LegacyPlatformIcons = m_Owner.FindPropertyAssert("m_BuildTargetIcons"); m_UIPrerenderedIcon = m_Owner.FindPropertyAssert("uIPrerenderedIcon"); DeserializeIcons(); DeserializeLegacyIcons(); } private void DeserializeIcons() { var allIconsList = new List<BuildTargetIcons>(); for (int i = 0; i < m_PlatformIcons.arraySize; i++) { var platform = m_PlatformIcons.GetArrayElementAtIndex(i); var icons = platform.FindPropertyRelative("m_Icons"); var platformName = platform.FindPropertyRelative("m_BuildTarget").stringValue; if (platformName == null || icons.arraySize <= 0) continue; var platformIcons = new BuildTargetIcons { BuildTarget = platformName, Icons = new PlatformIconStruct[icons.arraySize] }; for (int j = 0; j < icons.arraySize; j++) { var platformIconsEntry = icons.GetArrayElementAtIndex(j); var icon = new PlatformIconStruct() { Width = platformIconsEntry.FindPropertyRelative("m_Width").intValue, Height = platformIconsEntry.FindPropertyRelative("m_Height").intValue, Kind = platformIconsEntry.FindPropertyRelative("m_Kind").intValue, SubKind = platformIconsEntry.FindPropertyRelative("m_SubKind").stringValue, }; var texturesEntry = platformIconsEntry.FindPropertyRelative("m_Textures"); icon.Textures = new Texture2D[texturesEntry.arraySize]; for (int k = 0; k < texturesEntry.arraySize; k++) { icon.Textures[k] = (Texture2D)texturesEntry.GetArrayElementAtIndex(k).objectReferenceValue; } platformIcons.Icons[j] = icon; } allIconsList.Add(platformIcons); } m_AllIcons = allIconsList.ToArray(); } private void DeserializeLegacyIcons() { var allIconsList = new List<LegacyBuildTargetIcons>(); for (int i = 0; i < m_LegacyPlatformIcons.arraySize; i++) { var platform = m_LegacyPlatformIcons.GetArrayElementAtIndex(i); var icons = platform.FindPropertyRelative("m_Icons"); var platformName = platform.FindPropertyRelative("m_BuildTarget").stringValue; if (platformName == null || icons.arraySize <= 0) continue; var platformIcons = new LegacyBuildTargetIcons { BuildTarget = platformName, Icons = new LegacyPlatformIcon[icons.arraySize] }; for (int j = 0; j < icons.arraySize; j++) { var platformIconsEntry = icons.GetArrayElementAtIndex(j); var icon = new LegacyPlatformIcon() { Width = platformIconsEntry.FindPropertyRelative("m_Width").intValue, Height = platformIconsEntry.FindPropertyRelative("m_Height").intValue, Kind = (IconKind)platformIconsEntry.FindPropertyRelative("m_Kind").intValue, }; var texture = platformIconsEntry.FindPropertyRelative("m_Icon"); icon.Icon = (Texture2D)texture.objectReferenceValue; platformIcons.Icons[j] = icon; } allIconsList.Add(platformIcons); } m_AllLegacyIcons = allIconsList.ToArray(); } private void SerializeIcons() { m_PlatformIcons.ClearArray(); for (int i = 0; i < m_AllIcons.Length; i++) { var platformIcons = m_AllIcons[i]; var platformName = platformIcons.BuildTarget; m_PlatformIcons.InsertArrayElementAtIndex(i); var serializedPlatform = m_PlatformIcons.GetArrayElementAtIndex(i); if (platformName == null || platformIcons.Icons == null) return; serializedPlatform.FindPropertyRelative("m_BuildTarget").stringValue = platformName; var iconsMember = serializedPlatform.FindPropertyRelative("m_Icons"); iconsMember.ClearArray(); // Even after clearing parent array, this is not cleared for (int k = 0; k < platformIcons.Icons.Length; k++) { var icon = platformIcons.Icons[k]; iconsMember.InsertArrayElementAtIndex(k); var platformIconsEntry = iconsMember.GetArrayElementAtIndex(k); platformIconsEntry.FindPropertyRelative("m_Width").intValue = icon.Width; platformIconsEntry.FindPropertyRelative("m_Height").intValue = icon.Height; platformIconsEntry.FindPropertyRelative("m_Kind").intValue = icon.Kind; platformIconsEntry.FindPropertyRelative("m_SubKind").stringValue = icon.SubKind; var texturesMember = platformIconsEntry.FindPropertyRelative("m_Textures"); texturesMember.ClearArray(); // Even after clearing parent array, this is not cleared for (int l = 0; l < icon.Textures.Length; l++) { texturesMember.InsertArrayElementAtIndex(l); texturesMember.GetArrayElementAtIndex(l).objectReferenceValue = icon.Textures[l]; } } } } private void SerializeLegacyIcons() { m_LegacyPlatformIcons.ClearArray(); for (int i = 0; i < m_AllLegacyIcons.Length; i++) { var platformIcons = m_AllLegacyIcons[i]; var platformName = platformIcons.BuildTarget; m_LegacyPlatformIcons.InsertArrayElementAtIndex(i); var serializedPlatform = m_LegacyPlatformIcons.GetArrayElementAtIndex(i); if (platformName == null || platformIcons.Icons == null) return; serializedPlatform.FindPropertyRelative("m_BuildTarget").stringValue = platformName; var iconsMember = serializedPlatform.FindPropertyRelative("m_Icons"); iconsMember.ClearArray(); // Even after clearing parent array, this is not cleared for (int k = 0; k < platformIcons.Icons.Length; k++) { var icon = platformIcons.Icons[k]; iconsMember.InsertArrayElementAtIndex(k); var platformIconsEntry = iconsMember.GetArrayElementAtIndex(k); platformIconsEntry.FindPropertyRelative("m_Width").intValue = icon.Width; platformIconsEntry.FindPropertyRelative("m_Height").intValue = icon.Height; platformIconsEntry.FindPropertyRelative("m_Kind").intValue = (int)icon.Kind; var iconTexture = platformIconsEntry.FindPropertyRelative("m_Icon"); iconTexture.objectReferenceValue = icon.Icon; } } } private void SetLegacyPlatformIcons(string platform, Texture2D[] icons, IconKind kind, ref LegacyBuildTargetIcons[] allIcons) { allIcons = PlayerSettings.SetPlatformIconsForTargetIcons(platform, icons, kind, allIcons); SerializeLegacyIcons(); } static void ImportLegacyIcons(string platform, PlatformIconKind kind, PlatformIcon[] platformIcons, LegacyBuildTargetIcons[] allLegacyIcons) { if (!Enum.IsDefined(typeof(IconKind), kind.kind)) return; var iconKind = (IconKind)kind.kind; var legacyIcons = PlayerSettings.GetPlatformIconsForTargetIcons(platform, iconKind, allLegacyIcons); var legacyIconWidths = PlayerSettings.GetIconWidthsForPlatform(platform, iconKind); var legacyIconHeights = PlayerSettings.GetIconHeightsForPlatform(platform, iconKind); for (var i = 0; i < legacyIcons.Length; i++) { var selectedIcons = new List<PlatformIcon>(); foreach (var icon in platformIcons) { if (icon.width == legacyIconWidths[i] && icon.height == legacyIconHeights[i]) { selectedIcons.Add(icon); } } foreach (var selectedIcon in selectedIcons) selectedIcon.SetTextures(legacyIcons[i]); } } private void SetPreviewTextures(PlatformIcon platformIcon) { Texture2D[] previewTextures = new Texture2D[platformIcon.maxLayerCount]; for (int i = 0; i < platformIcon.maxLayerCount; i++) { previewTextures[i] = PlayerSettings.GetPlatformIconAtSizeForTargetIcons(platformIcon.kind.platform, platformIcon.width, platformIcon.height, m_AllIcons, platformIcon.kind.kind, platformIcon.iconSubKind, i); } platformIcon.SetPreviewTextures(previewTextures); } internal PlatformIcon[] GetPlatformIcons(BuildTargetGroup platform, PlatformIconKind kind, ref BuildTargetIcons[] allIcons) { var namedBuildTarget = NamedBuildTarget.FromBuildTargetGroup(platform); if (!BuildTargetDiscovery.TryGetBuildTarget(BuildPipeline.GetBuildTargetByName(namedBuildTarget.TargetName), out var iBuildTarget)) return Array.Empty<PlatformIcon>(); var requiredIcons = iBuildTarget.IconPlatformProperties?.GetRequiredPlatformIcons(); if (requiredIcons == null) return Array.Empty<PlatformIcon>(); var serializedIcons = PlayerSettings.GetPlatformIconsFromTargetIcons(namedBuildTarget.TargetName, kind.kind, allIcons); if (m_RequiredIcons == null) m_RequiredIcons = new Dictionary<PlatformIconKind, PlatformIcon[]>(); if (!m_RequiredIcons.ContainsKey(kind)) { foreach (var requiredIcon in requiredIcons) { if (!m_RequiredIcons.ContainsKey(requiredIcon.Key)) m_RequiredIcons.Add(requiredIcon.Key, requiredIcon.Value); } } var icons = PlatformIcon.GetRequiredPlatformIconsByType(kind, m_RequiredIcons); if (serializedIcons.Length <= 0) { // Map legacy icons to required icons ImportLegacyIcons(namedBuildTarget.TargetName, kind, icons, m_AllLegacyIcons); // Serialize required icons SetPlatformIcons(platform, kind, icons, ref allIcons); foreach (var icon in icons) if (icon.IsEmpty()) icon.SetTextures(null); } else { // Map serialized icons to required icons icons = PlayerSettings.GetPlatformIconsFromStruct(icons, kind, serializedIcons.ToArray()); } return icons; } void SetIconsForPlatform(BuildTargetGroup targetGroup, PlatformIcon[] icons, PlatformIconKind kind, ref BuildTargetIcons[] allIcons) { var namedBuildTarget = NamedBuildTarget.FromBuildTargetGroup(targetGroup); if (!BuildTargetDiscovery.TryGetBuildTarget(BuildPipeline.GetBuildTargetByName(namedBuildTarget.TargetName), out var iBuildTarget)) return; var requiredIcons = iBuildTarget.IconPlatformProperties?.GetRequiredPlatformIcons(); if (requiredIcons == null) return; if (m_RequiredIcons == null) m_RequiredIcons = new Dictionary<PlatformIconKind, PlatformIcon[]>(); if (!m_RequiredIcons.ContainsKey(kind)) { foreach (var requiredIcon in requiredIcons) { if (!m_RequiredIcons.ContainsKey(requiredIcon.Key)) m_RequiredIcons.Add(requiredIcon.Key, requiredIcon.Value); } } var requiredIconCount = PlatformIcon.GetRequiredPlatformIconsByType(kind, m_RequiredIcons).Length; PlatformIconStruct[] iconStructs; if (icons == null) iconStructs = new PlatformIconStruct[0]; else if (requiredIconCount != icons.Length) { throw new InvalidOperationException($"Attempting to set an incorrect number of icons for {namedBuildTarget} {kind} kind, it requires {requiredIconCount} icons but trying to assign {icons.Length}."); } else { iconStructs = icons.Select( i => i.GetPlatformIconStruct() ).ToArray<PlatformIconStruct>(); } allIcons = PlayerSettings.SetIconsForPlatformForTargetIcons(namedBuildTarget.TargetName, iconStructs, kind.kind, allIcons); } void SetPlatformIcons(BuildTargetGroup targetGroup, PlatformIconKind kind, PlatformIcon[] icons, ref BuildTargetIcons[] allIcons) { SetIconsForPlatform(targetGroup, icons, kind, ref allIcons); SerializeIcons(); } public void LegacyIconSectionGUI() { // Both default icon and Legacy icons are serialized to the same map // That's why m_LegacyPlatformIcons can be excluded in two places (other place in IconSectionGUI()) using (var vertical = new EditorGUILayout.VerticalScope()) using (new EditorGUI.PropertyScope(vertical.rect, GUIContent.none, m_LegacyPlatformIcons)) { // Get icons and icon sizes for selected platform (or default) EditorGUI.BeginChangeCheck(); string platformName = ""; Texture2D[] icons = PlayerSettings.GetPlatformIconsForTargetIcons(platformName, IconKind.Any, m_AllLegacyIcons); int[] widths = PlayerSettings.GetIconWidthsForPlatform(platformName, IconKind.Any); // Ensure the default icon list is always populated correctly if (icons.Length != widths.Length) { icons = new Texture2D[widths.Length]; } icons[0] = (Texture2D)EditorGUILayout.ObjectField(SettingsContent.defaultIcon, icons[0], typeof(Texture2D), false); // Save changes if (EditorGUI.EndChangeCheck()) { Undo.RecordObjects(m_Owner.targets, SettingsContent.undoChangedIconString); SetLegacyPlatformIcons(platformName, icons, IconKind.Any, ref m_AllLegacyIcons); } } } public void SerializedObjectUpdated() { DeserializeIcons(); DeserializeLegacyIcons(); } public void IconSectionGUI(NamedBuildTarget namedBuildTarget, ISettingEditorExtension settingsExtension, int platformID, int sectionIndex) { m_SelectedPlatform = platformID; if (!m_Owner.BeginSettingsBox(sectionIndex, SettingsContent.iconTitle)) { m_Owner.EndSettingsBox(); return; } var platformUsesStandardIcons = true; if (settingsExtension != null) platformUsesStandardIcons = settingsExtension.UsesStandardIcons(); if (platformUsesStandardIcons) { var selectedDefault = (m_SelectedPlatform < 0); // Set default platform variables BuildPlatform platform = null; var platformName = ""; // Override if a platform is selected if (!selectedDefault) { platform = m_ValidPlatforms[m_SelectedPlatform]; platformName = platform.name; } var iconUISettings = IconSettings.StandardIcons; if (BuildTargetDiscovery.TryGetBuildTarget(platform.defaultTarget, out IBuildTarget iBuildTarget)) iconUISettings = iBuildTarget.IconPlatformProperties?.IconUISettings ?? IconSettings.StandardIcons; if (iconUISettings == IconSettings.None) { PlayerSettingsEditor.ShowNoSettings(); EditorGUILayout.Space(); } else if (iconUISettings == IconSettings.StandardIcons) { // Both default icon and Legacy icons are serialized to the same map // That's why m_LegacyPlatformIcons can be excluded in two places (other place in CommonSettings()) using (var vertical = new EditorGUILayout.VerticalScope()) using (new EditorGUI.PropertyScope(vertical.rect, GUIContent.none, m_LegacyPlatformIcons)) { // Get icons and icon sizes for selected platform (or default) var icons = PlayerSettings.GetPlatformIconsForTargetIcons(platformName, IconKind.Any, m_AllLegacyIcons); var widths = PlayerSettings.GetIconWidthsForPlatform(platformName, IconKind.Any); var heights = PlayerSettings.GetIconHeightsForPlatform(platformName, IconKind.Any); var kinds = PlayerSettings.GetIconKindsForPlatform(platformName); var overrideIcons = true; if (!selectedDefault) { // If the list of icons for this platform is not empty (and has the correct size), // consider the icon overridden for this platform EditorGUI.BeginChangeCheck(); overrideIcons = (icons.Length == widths.Length); overrideIcons = GUILayout.Toggle(overrideIcons, string.Format(L10n.Tr("Override for {0}"), platform.title.text)); EditorGUI.BeginDisabled(!overrideIcons); var changed = EditorGUI.EndChangeCheck(); if (changed || (!overrideIcons && icons.Length > 0)) { // Set the list of icons to correct length if overridden, otherwise to an empty list if (overrideIcons) icons = new Texture2D[widths.Length]; else icons = new Texture2D[0]; if (changed) SetLegacyPlatformIcons(platformName, icons, IconKind.Any, ref m_AllLegacyIcons); } } // Show the icons for this platform (or default) EditorGUI.BeginChangeCheck(); for (int i = 0; i < widths.Length; i++) { var previewWidth = Mathf.Min(kMaxPreviewSize, widths[i]); var previewHeight = (int)((float)heights[i] * previewWidth / widths[i]); // take into account the aspect ratio var rect = GUILayoutUtility.GetRect(kSlotSize, Mathf.Max(kSlotSize, previewHeight) + kIconSpacing); var width = Mathf.Min(rect.width, EditorGUIUtility.labelWidth + 4 + kSlotSize + kIconSpacing + kMaxPreviewSize); // Label var label = widths[i] + "x" + heights[i]; GUI.Label(new Rect(rect.x, rect.y, width - kMaxPreviewSize - kSlotSize - 2 * kIconSpacing, 20), label); // Texture slot if (overrideIcons) { var slotWidth = kSlotSize; var slotHeight = (int)((float)heights[i] / widths[i] * kSlotSize); // take into account the aspect ratio icons[i] = (Texture2D)EditorGUI.ObjectField( new Rect(rect.x + width - kMaxPreviewSize - kSlotSize - kIconSpacing, rect.y, slotWidth, slotHeight), icons[i], typeof(Texture2D), false); } // Preview var previewRect = new Rect(rect.x + width - kMaxPreviewSize, rect.y, previewWidth, previewHeight); var closestIcon = PlayerSettings.GetPlatformIconForSizeForTargetIcons(platformName, widths[i], heights[i], kinds[i], m_AllLegacyIcons); if (closestIcon != null) GUI.DrawTexture(previewRect, closestIcon); else GUI.Box(previewRect, ""); } // Save changes if (EditorGUI.EndChangeCheck()) { Undo.RecordObjects(m_Owner.targets, SettingsContent.undoChangedIconString); SetLegacyPlatformIcons(platformName, icons, IconKind.Any, ref m_AllLegacyIcons); } EditorGUI.EndDisabled(); } } } if (settingsExtension != null) settingsExtension.IconSectionGUI(); m_Owner.EndSettingsBox(); } internal void ShowPlatformIconsByKind(PlatformIconFieldGroup iconFieldGroup, bool foldByKind, bool foldBySubkind) { // All icons that are displayed here are serialized into a single map // So in the preset we can only exclude/include all icons using (var vertical = new EditorGUILayout.VerticalScope()) using (new EditorGUI.PropertyScope(vertical.rect, GUIContent.none, m_PlatformIcons)) { int labelHeight = 20; foreach (var kind in PlayerSettings.GetSupportedIconKinds(NamedBuildTarget.FromBuildTargetGroup(iconFieldGroup.targetGroup))) { iconFieldGroup.SetPlatformIcons(GetPlatformIcons(iconFieldGroup.targetGroup, kind, ref m_AllIcons), kind); } foreach (var kindGroup in iconFieldGroup.m_IconsFields) { EditorGUI.BeginChangeCheck(); var key = kindGroup.Key; if (foldByKind) { GUIContent kindName = new GUIContent( string.Format("{0} icons ({1}/{2})", key.m_Label, kindGroup.Key.m_SetIconSlots, kindGroup.Key.m_IconSlotCount), key.m_KindDescription ); Rect rectKindLabel = GUILayoutUtility.GetRect(kSlotSize, labelHeight); rectKindLabel.x += 2; key.m_State = EditorGUI.Foldout(rectKindLabel, key.m_State, kindName, true, EditorStyles.foldout); } else key.m_State = true; if (key.m_State) { kindGroup.Key.m_SetIconSlots = 0; foreach (var subKindGroup in kindGroup.Value) { subKindGroup.Key.m_SetIconSlots = PlayerSettings.GetNonEmptyPlatformIconCount(subKindGroup.Value.Select(x => x.platformIcon) .ToArray()); kindGroup.Key.m_SetIconSlots += subKindGroup.Key.m_SetIconSlots; if (foldBySubkind) { string subKindName = string.Format("{0} icons ({1}/{2})", subKindGroup.Key.m_Label, subKindGroup.Key.m_SetIconSlots, subKindGroup.Value.Length); Rect rectSubKindLabel = GUILayoutUtility.GetRect(kSlotSize, labelHeight); rectSubKindLabel.x += 8; subKindGroup.Key.m_State = EditorGUI.Foldout(rectSubKindLabel, subKindGroup.Key.m_State, subKindName, true, EditorStyles.foldout); } else subKindGroup.Key.m_State = true; if (subKindGroup.Key.m_State || !foldBySubkind) { foreach (var iconField in subKindGroup.Value) { SetPreviewTextures(iconField.platformIcon); iconField.DrawAt(); } } } } if (EditorGUI.EndChangeCheck()) SetPlatformIcons(iconFieldGroup.targetGroup, key.m_Kind, iconFieldGroup.m_PlatformIconsByKind[key.m_Kind], ref m_AllIcons); } } } } }
UnityCsReference/Editor/Mono/Inspector/PlayerSettingsEditor/PlayerSettingsIconsEditor.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/PlayerSettingsEditor/PlayerSettingsIconsEditor.cs", "repo_id": "UnityCsReference", "token_count": 13847 }
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; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEngine; using UnityEngine.Rendering; using Object = UnityEngine.Object; namespace UnityEditor.Rendering { public static class RenderPipelineEditorUtility { public static Type[] GetDerivedTypesSupportedOnCurrentPipeline<T>() { return TypeCache.GetTypesDerivedFrom<T>() .Where(t => t.GetCustomAttribute<SupportedOnRenderPipelineAttribute>() is { isSupportedOnCurrentPipeline: true }) .ToArray(); } [Obsolete($"{nameof(FetchFirstCompatibleTypeUsingScriptableRenderPipelineExtension)} is deprecated. Use {nameof(GetDerivedTypesSupportedOnCurrentPipeline)} instead. #from(2023.1)", false)] public static Type FetchFirstCompatibleTypeUsingScriptableRenderPipelineExtension<TBaseClass>() { var extensionTypes = TypeCache.GetTypesDerivedFrom<TBaseClass>(); foreach (Type extensionType in extensionTypes) { #pragma warning disable CS0618 if (Attribute.GetCustomAttribute(extensionType, typeof(ScriptableRenderPipelineExtensionAttribute)) is ScriptableRenderPipelineExtensionAttribute { inUse: true }) return extensionType; #pragma warning restore CS0618 } return null; } private static Dictionary<Type, Type> s_RenderPipelineAssetToRenderPipelineType = new(); public static Type GetPipelineTypeFromPipelineAssetType(Type pipelineAssetType) { if (!typeof(RenderPipelineAsset).IsAssignableFrom(pipelineAssetType)) return null; if (s_RenderPipelineAssetToRenderPipelineType.TryGetValue(pipelineAssetType, out var pipelineType)) return pipelineType; Type baseGenericType = pipelineAssetType; while (baseGenericType != null) { if (!baseGenericType.IsGenericType || baseGenericType.GetGenericTypeDefinition() != typeof(RenderPipelineAsset<>)) { baseGenericType = baseGenericType.BaseType; continue; } pipelineType = baseGenericType.GetGenericArguments()[0]; s_RenderPipelineAssetToRenderPipelineType[pipelineAssetType] = pipelineType; return pipelineType; } var pipelineAsset = ScriptableObject.CreateInstance(pipelineAssetType) as RenderPipelineAsset; pipelineType = pipelineAsset.pipelineType; Object.DestroyImmediate(pipelineAsset); s_RenderPipelineAssetToRenderPipelineType[pipelineAssetType] = pipelineType; return pipelineType; } public static bool TrySetRenderingLayerName(int index, string name) => TagManager.Internal_TrySetRenderingLayerName(index, name); public static bool TryAddRenderingLayerName(string name) => TagManager.Internal_TryAddRenderingLayerName(name); internal static int GetActiveMaxRenderingLayers() { if (EditorGraphicsSettings.TryGetRenderPipelineSettingsFromInterface<RenderingLayersLimitSettings>(out var settings) && settings.Length != 0) return settings[0].maxSupportedRenderingLayers; return 32; } internal static List<(int, string)> GetMaxRenderingLayersFromSettings() { var result = new List<(int, string)>(); var renderPipelineAssets = GraphicsSettings.allConfiguredRenderPipelines; foreach (var renderPipelineAsset in renderPipelineAssets) { var pipelineType = GetPipelineTypeFromPipelineAssetType(renderPipelineAsset.GetType()); if (pipelineType == null) continue; if (!EditorGraphicsSettings.TryGetRenderPipelineSettingsFromInterfaceForPipeline<RenderingLayersLimitSettings>(pipelineType, out var settings)) continue; if (settings.Length == 0) continue; result.Add((settings[0].maxSupportedRenderingLayers, renderPipelineAsset.pipelineType.Name)); } return result; } internal static (string[], int[]) GetRenderingLayerNamesAndValuesForMask(uint currentMask) { var names = RenderingLayerMask.GetDefinedRenderingLayerNames(); var values = RenderingLayerMask.GetDefinedRenderingLayerValues(); if (currentMask != uint.MaxValue) { //calculate remaining mask value uint remainingMask = currentMask; for (int i = 0; i < values.Length; i++) { uint valueUint = unchecked((uint)values[i]); if ((currentMask & valueUint) != 0) remainingMask &= ~valueUint; } //add remaining mask value to the end of the list if (remainingMask != 0) { var listOfUnnamedBits = new List<(int, uint)>(); for (int i = 0; i < 32; i++) { if ((remainingMask & (1u << i)) != 0) listOfUnnamedBits.Add((i, 1u << i)); } var allNames = new List<string>(names.Length + listOfUnnamedBits.Count); var allValues = new List<int>(names.Length + listOfUnnamedBits.Count); allNames.AddRange(names); allValues.AddRange(values); for (int i = 0; i < listOfUnnamedBits.Count; i++) { var bit = listOfUnnamedBits[i]; var indexOfTheNextValue = allValues.FindIndex((currentValue) => unchecked((uint)currentValue) > bit.Item2); if (indexOfTheNextValue == -1) indexOfTheNextValue = allValues.Count; //find an index of specific bit value allNames.Insert(indexOfTheNextValue, $"Undefined Layer {bit.Item1}"); allValues.Insert(indexOfTheNextValue, unchecked((int)bit.Item2)); } names = allNames.ToArray(); values = allValues.ToArray(); } } return (names, values); } } }
UnityCsReference/Editor/Mono/Inspector/RenderPipelineEditorUtility.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/RenderPipelineEditorUtility.cs", "repo_id": "UnityCsReference", "token_count": 3104 }
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 System.Linq; namespace UnityEditor { /** * Internal class for handling the drawing of ShadowCascade splits GUI and user interaction. */ internal static class ShadowCascadeSplitGUI { private const int kSliderbarTopMargin = 2; private const int kSliderbarHeight = 28; private const int kSliderbarBottomMargin = 2; private const int kPartitionHandleWidth = 2; private const int kPartitionHandleExtraHitAreaWidth = 2; private static readonly Color[] kCascadeColors = { new Color(0.5f, 0.5f, 0.6f, 1.0f), new Color(0.5f, 0.6f, 0.5f, 1.0f), new Color(0.6f, 0.6f, 0.5f, 1.0f), new Color(0.6f, 0.5f, 0.5f, 1.0f), }; // using a LODGroup skin private static readonly GUIStyle s_CascadeSliderBG = "LODSliderRange"; private static readonly GUIStyle s_TextCenteredStyle = new GUIStyle(EditorStyles.whiteMiniLabel) { alignment = TextAnchor.MiddleCenter }; // Internal struct to bundle drag information private class DragCache { public int m_ActivePartition; // the cascade partition that we are currently dragging/resizing public float m_NormalizedPartitionSize; // the normalized size of the partition (0.0f < size < 1.0f) public Vector2 m_LastCachedMousePosition; // mouse position the last time we registered a drag or mouse down. public DragCache(int activePartition, float normalizedPartitionSize, Vector2 currentMousePos) { m_ActivePartition = activePartition; m_NormalizedPartitionSize = normalizedPartitionSize; m_LastCachedMousePosition = currentMousePos; } } private static DragCache s_DragCache; private static readonly int s_CascadeSliderId = "s_CascadeSliderId".GetHashCode(); private static SceneView s_RestoreSceneView; private static SceneView.CameraMode s_OldSceneDrawMode; private static bool s_OldSceneLightingMode; /** * Static function to handle the GUI and User input related to the cascade slider. * * @param normalizedCascadePartition The array of partition sizes in the range 0.0f - 1.0f; expects ONE entry if cascades = 2, and THREE if cascades=4 * The last entry will be automatically determined by summing up the array, and doing 1.0f - sum */ public static void HandleCascadeSliderGUI(ref float[] normalizedCascadePartitions) { GUILayout.Label("Cascade splits"); // get the inspector width since we need it while drawing the partition rects. // Only way currently is to reserve the block in the layout using GetRect(), and then immediately drawing the empty box // to match the call to GetRect. // From this point on, we move to non-layout based code. var sliderRect = GUILayoutUtility.GetRect(GUIContent.none , s_CascadeSliderBG , GUILayout.Height(kSliderbarTopMargin + kSliderbarHeight + kSliderbarBottomMargin) , GUILayout.ExpandWidth(true)); GUI.Box(sliderRect, GUIContent.none); float currentX = sliderRect.x; float cascadeBoxStartY = sliderRect.y + kSliderbarTopMargin; float cascadeSliderWidth = sliderRect.width - (normalizedCascadePartitions.Length * kPartitionHandleWidth); Color origTextColor = GUI.color; Color origBackgroundColor = GUI.backgroundColor; int colorIndex = -1; // setup the array locally with the last partition float[] adjustedCascadePartitions = new float[normalizedCascadePartitions.Length + 1]; Array.Copy(normalizedCascadePartitions, adjustedCascadePartitions, normalizedCascadePartitions.Length); adjustedCascadePartitions[adjustedCascadePartitions.Length - 1] = 1.0f - normalizedCascadePartitions.Sum(); // check for user input on any of the partition handles // this mechanism gets the current event in the queue... make sure that the mouse is over our control before consuming the event int sliderControlId = GUIUtility.GetControlID(s_CascadeSliderId, FocusType.Passive); Event currentEvent = Event.current; int hotPartitionHandleIndex = -1; // the index of any partition handle that we are hovering over or dragging // draw each cascade partition for (int i = 0; i < adjustedCascadePartitions.Length; ++i) { float currentPartition = adjustedCascadePartitions[i]; colorIndex = (colorIndex + 1) % kCascadeColors.Length; GUI.backgroundColor = kCascadeColors[colorIndex]; float boxLength = (cascadeSliderWidth * currentPartition); // main cascade box Rect partitionRect = new Rect(currentX, cascadeBoxStartY, boxLength, kSliderbarHeight); GUI.Box(partitionRect, GUIContent.none, s_CascadeSliderBG); currentX += boxLength; // cascade box percentage text GUI.color = Color.white; Rect textRect = partitionRect; var cascadeText = UnityString.Format("{0}\n{1:F1}%", i, currentPartition * 100.0f); GUI.Label(textRect, GUIContent.Temp(cascadeText, cascadeText), s_TextCenteredStyle); // no need to draw the partition handle for last box if (i == adjustedCascadePartitions.Length - 1) break; // partition handle GUI.backgroundColor = Color.black; Rect handleRect = partitionRect; handleRect.x = currentX; handleRect.width = kPartitionHandleWidth; GUI.Box(handleRect, GUIContent.none, s_CascadeSliderBG); // we want a thin handle visually (since wide black bar looks bad), but a slightly larger // hit area for easier manipulation Rect handleHitRect = handleRect; handleHitRect.xMin -= kPartitionHandleExtraHitAreaWidth; handleHitRect.xMax += kPartitionHandleExtraHitAreaWidth; if (handleHitRect.Contains(currentEvent.mousePosition)) hotPartitionHandleIndex = i; // add regions to slider where the cursor changes to Resize-Horizontal if (s_DragCache == null) { EditorGUIUtility.AddCursorRect(handleHitRect, MouseCursor.ResizeHorizontal, sliderControlId); } currentX += kPartitionHandleWidth; } GUI.color = origTextColor; GUI.backgroundColor = origBackgroundColor; EventType eventType = currentEvent.GetTypeForControl(sliderControlId); switch (eventType) { case EventType.MouseDown: if (hotPartitionHandleIndex >= 0) { s_DragCache = new DragCache(hotPartitionHandleIndex, normalizedCascadePartitions[hotPartitionHandleIndex], currentEvent.mousePosition); if (GUIUtility.hotControl == 0) GUIUtility.hotControl = sliderControlId; currentEvent.Use(); // Switch active scene view into shadow cascades visualization mode, once we start // tweaking cascade splits. if (s_RestoreSceneView == null) { s_RestoreSceneView = SceneView.lastActiveSceneView; if (s_RestoreSceneView != null) { s_OldSceneDrawMode = s_RestoreSceneView.cameraMode; s_OldSceneLightingMode = s_RestoreSceneView.sceneLighting; s_RestoreSceneView.cameraMode = SceneView.GetBuiltinCameraMode(DrawCameraMode.ShadowCascades); } } } break; case EventType.MouseUp: // mouseUp event anywhere should release the hotcontrol (if it belongs to us), drags (if any) if (GUIUtility.hotControl == sliderControlId) { GUIUtility.hotControl = 0; currentEvent.Use(); } s_DragCache = null; // Restore previous scene view drawing mode once we stop tweaking cascade splits. if (s_RestoreSceneView != null) { s_RestoreSceneView.cameraMode = s_OldSceneDrawMode; s_RestoreSceneView.sceneLighting = s_OldSceneLightingMode; s_RestoreSceneView = null; } break; case EventType.MouseDrag: if (GUIUtility.hotControl != sliderControlId) break; // convert the mouse movement to normalized cascade width. Make sure that we are safe to apply the delta before using it. float delta = (currentEvent.mousePosition - s_DragCache.m_LastCachedMousePosition).x / cascadeSliderWidth; bool isLeftPartitionHappy = ((adjustedCascadePartitions[s_DragCache.m_ActivePartition] + delta) > 0.0f); bool isRightPartitionHappy = ((adjustedCascadePartitions[s_DragCache.m_ActivePartition + 1] - delta) > 0.0f); if (isLeftPartitionHappy && isRightPartitionHappy) { s_DragCache.m_NormalizedPartitionSize += delta; normalizedCascadePartitions[s_DragCache.m_ActivePartition] = s_DragCache.m_NormalizedPartitionSize; if (s_DragCache.m_ActivePartition < normalizedCascadePartitions.Length - 1) normalizedCascadePartitions[s_DragCache.m_ActivePartition + 1] -= delta; GUI.changed = true; } s_DragCache.m_LastCachedMousePosition = currentEvent.mousePosition; currentEvent.Use(); break; } } } }
UnityCsReference/Editor/Mono/Inspector/ShadowCascadeSplitGUI.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/ShadowCascadeSplitGUI.cs", "repo_id": "UnityCsReference", "token_count": 4986 }
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 UnityEditor; namespace UnityEditor { [CustomEditor(typeof(TextMesh))] [CanEditMultipleObjects] internal class TextMeshInspector : Editor { SerializedProperty m_Font; void OnEnable() { m_Font = serializedObject.FindProperty("m_Font"); } public override void OnInspectorGUI() { Font oldFont = m_Font.hasMultipleDifferentValues ? null : (m_Font.objectReferenceValue as Font); DrawDefaultInspector(); Font newFont = m_Font.hasMultipleDifferentValues ? null : (m_Font.objectReferenceValue as Font); if (newFont != null && newFont != oldFont) { foreach (TextMesh textMesh in targets) { var renderer = textMesh.GetComponent<MeshRenderer>(); if (renderer) renderer.sharedMaterial = newFont.material; } } } } }
UnityCsReference/Editor/Mono/Inspector/TextMeshInspector.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/TextMeshInspector.cs", "repo_id": "UnityCsReference", "token_count": 522 }
323
// 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.UIElements; using UnityEngine.UIElements; using System; namespace UnityEditor.Inspector { internal class ClippingPlanes : BaseCompositeField<Vector2, FloatField, float> { [Serializable] public new class UxmlSerializedData : BaseCompositeField<Vector2, FloatField, float>.UxmlSerializedData { public override object CreateInstance() => new ClippingPlanes(); } const string k_CompositeInputStyle = "unity-composite-field__input"; const string k_CompositeFieldStyle = "unity-composite-field__field"; const string k_NearClipStyle = "unity-near-clip-input"; const string k_FarClipStyle = "unity-far-clip-input"; const float k_NearFarLabelsWidth = EditorGUI.kNearFarLabelsWidth; bool m_DirtyX; bool m_DirtyY; readonly SerializedProperty[] m_Properties = new SerializedProperty[2]; public SerializedProperty nearClip { get => m_Properties[0]; set { m_Properties[0] = value; MockPropertyField(fields[0], EditorGUI.s_NearAndFarLabels[0], m_Properties[0]); Update(); } } public SerializedProperty farClip { get => m_Properties[1]; set { m_Properties[1] = value; MockPropertyField(fields[1], EditorGUI.s_NearAndFarLabels[1], m_Properties[1]); Update(); } } internal override FieldDescription[] DescribeFields() => new[] { new FieldDescription("Near", k_NearClipStyle, r => r.x, (ref Vector2 r, float v) => { r.x = v; m_DirtyX = true; }), new FieldDescription("Far", k_FarClipStyle, r => r.y, (ref Vector2 r, float v) => { r.y = v; m_DirtyY = true; }), }; public ClippingPlanes() : base(labelProperty, 2) { AddToClassList(BaseField<bool>.alignedFieldUssClassName); RegisterCallback<AttachToPanelEvent>(e => { e.elementTarget.Q(className: k_CompositeInputStyle)?.RemoveFromClassList(k_CompositeInputStyle); foreach (var field in fields) { field.RemoveFromClassList(k_CompositeFieldStyle); field.RemoveFromClassList(BaseField<bool>.alignedFieldUssClassName); field.style.marginLeft = field.style.marginRight = 0; var label = field.Q<Label>(); label.style.flexBasis = label.style.minWidth = new StyleLength(k_NearFarLabelsWidth); label.style.marginLeft = label.style.marginRight = 0; } }); RegisterCallback<ChangeEvent<Vector2>>(e => { if (m_DirtyX) { m_Properties[0].floatValue = e.newValue.x; m_Properties[0].serializedObject.ApplyModifiedProperties(); } if (m_DirtyY) { m_Properties[1].floatValue = e.newValue.y; m_Properties[1].serializedObject.ApplyModifiedProperties(); } m_DirtyX = m_DirtyY = false; }); } public void Update() { value = new Vector2(m_Properties[0]?.floatValue ?? default, m_Properties[1]?.floatValue ?? default); if (m_Properties[0] != null) fields[0]?.schedule.Execute(() => BindingsStyleHelpers.UpdateElementStyle(fields[0], m_Properties[0])); if (m_Properties[1] != null) fields[1]?.schedule.Execute(() => BindingsStyleHelpers.UpdateElementStyle(fields[1], m_Properties[1])); } static BaseField<TValue> MockPropertyField<TValue>(BaseField<TValue> field, GUIContent content, SerializedProperty property) { field.label = content.text; field.tooltip = content.tooltip; field.AddToClassList(BaseField<bool>.alignedFieldUssClassName); BindingsStyleHelpers.RegisterRightClickMenu(field, property); return field; } } }
UnityCsReference/Editor/Mono/Inspector/VisualElements/ClippingPlanes.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/VisualElements/ClippingPlanes.cs", "repo_id": "UnityCsReference", "token_count": 2273 }
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 UnityEngine; using Object = UnityEngine.Object; using UnityEditor; using System.Reflection; using UnityEngine.Bindings; using UnityEditor.Scripting.ScriptCompilation; using System.Globalization; using Unity.CodeEditor; using TargetAttributes = UnityEditor.BuildTargetDiscovery.TargetAttributes; using UnityEngine.Scripting; using System.Runtime.InteropServices; using UnityEngine.SceneManagement; namespace UnityEditorInternal { [System.Obsolete("CanAppendBuild has been deprecated. Use UnityEditor.CanAppendBuild instead (UnityUpgradable) -> [UnityEditor] UnityEditor.CanAppendBuild", true)] public enum CanAppendBuild { Unsupported = 0, Yes = 1, No = 2, } // Keep in sync with DllType in MonoEditorUtility.h public enum DllType { Unknown = 0, Native = 1, UnknownManaged = 2, ManagedNET35 = 3, ManagedNET40 = 4, WinMDNative = 5, WinMDNET40 = 6 } [RequiredByNativeCode] internal class LoadFileAndForgetOperationHelper { // When the load operation completes this is invoked to hold the result so that it doesn't // get garbage collected [RequiredByNativeCode] public static void SetObjectResult(LoadFileAndForgetOperation op, UnityEngine.Object result) { op.m_ObjectReference = result; } } [StructLayout(LayoutKind.Sequential)] [RequiredByNativeCode] public class LoadFileAndForgetOperation : AsyncOperation { internal UnityEngine.Object m_ObjectReference; public extern UnityEngine.Object Result { [NativeMethod("GetRequestedObject")] get; } public LoadFileAndForgetOperation() { } private LoadFileAndForgetOperation(IntPtr ptr) : base(ptr) { } new internal static class BindingsMarshaller { public static LoadFileAndForgetOperation ConvertToManaged(IntPtr ptr) => new LoadFileAndForgetOperation(ptr); public static IntPtr ConvertToNative(LoadFileAndForgetOperation asyncOperation) => asyncOperation.m_Ptr; } } [NativeHeader("Editor/Src/InternalEditorUtility.bindings.h")] [NativeHeader("Editor/Mono/MonoEditorUtility.h")] [NativeHeader("Editor/Platform/Interface/ColorPicker.h")] [NativeHeader("Editor/Platform/Interface/EditorUtility.h")] [NativeHeader("Editor/Src/Application/Application.h")] [NativeHeader("Modules/AssetDatabase/Editor/Public/AssetDatabase.h")] [NativeHeader("Modules/AssetDatabase/Editor/Public/AssetDatabaseDeprecated.h")] [NativeHeader("Editor/Src/AssetPipeline/TextureImporting/BumpMapSettings.h")] [NativeHeader("Editor/Src/ScriptCompilation/PrecompiledAssemblies.h")] [NativeHeader("Editor/Src/AssetPipeline/ObjectHashGenerator.h")] [NativeHeader("Editor/Src/AssetPipeline/UnityExtensions.h")] [NativeHeader("Editor/Src/Windowing/AuxWindowManager.h")] [NativeHeader("Editor/Src/DisplayDialog.h")] [NativeHeader("Editor/Src/DragAndDropForwarding.h")] [NativeHeader("Editor/Src/EditorHelper.h")] [NativeHeader("Editor/Src/EditorUserBuildSettings.h")] [NativeHeader("Editor/Src/EditorWindowController.h")] [NativeHeader("Editor/Src/EditorModules.h")] [NativeHeader("Editor/Src/Gizmos/GizmoUtil.h")] [NativeHeader("Editor/Src/HierarchyState.h")] [NativeHeader("Editor/Src/InspectorExpandedState.h")] [NativeHeader("Editor/Src/LoadFileAndForgetOperation.h")] [NativeHeader("Runtime/Interfaces/ILicensing.h")] [NativeHeader("Editor/Src/RemoteInput/RemoteInput.h")] [NativeHeader("Editor/Src/ShaderMenu.h")] [NativeHeader("Editor/Src/Undo/ObjectUndo.h")] [NativeHeader("Modules/AssetDatabase/Editor/Public/AssetDatabaseProperty.h")] [NativeHeader("Editor/Src/Utility/CustomLighting.h")] [NativeHeader("Editor/Src/Utility/DiffTool.h")] [NativeHeader("Editor/Src/Utility/GameObjectHierarchyProperty.h")] [NativeHeader("Runtime/BaseClasses/TagManager.h")] [NativeHeader("Runtime/Camera/Camera.h")] [NativeHeader("Runtime/Camera/RenderManager.h")] [NativeHeader("Runtime/Camera/RenderSettings.h")] [NativeHeader("Runtime/Camera/Skybox.h")] [NativeHeader("Runtime/Transform/RectTransform.h")] [NativeHeader("Runtime/Graphics/Renderer.h")] [NativeHeader("Runtime/Graphics/ScreenManager.h")] [NativeHeader("Runtime/Graphics/SpriteFrame.h")] [NativeHeader("Runtime/2D/Common/SpriteTypes.h")] [NativeHeader("Runtime/Graphics/GraphicsHelper.h")] [NativeHeader("Runtime/Graphics/GpuDeviceManager.h")] [NativeHeader("Runtime/Input/Cursor.h")] [NativeHeader("Runtime/Misc/GameObjectUtility.h")] [NativeHeader("Runtime/Misc/Player.h")] [NativeHeader("Runtime/Misc/PlayerSettings.h")] [NativeHeader("Runtime/Serialize/PersistentManager.h")] [NativeHeader("Runtime/Shaders/ShaderImpl/FastPropertyName.h")] [NativeHeader("Runtime/Serialize/PersistentManager.h")] [NativeHeader("Runtime/Threads/ThreadChecks.h")] [NativeHeader("Runtime/Utilities/Word.h")] [NativeHeader("Editor/Src/BuildPipeline/BuildPlayer.h")] [NativeHeader("Editor/Src/BuildPipeline/BuildTargetPlatformSpecific.h")] [NativeHeader("Runtime/Utilities/Argv.h")] [NativeHeader("Runtime/Utilities/FileUtilities.h")] [NativeHeader("Runtime/Utilities/LaunchUtilities.h")] [NativeHeader("Runtime/Utilities/UnityConfiguration.h")] [NativeHeader("Runtime/Utilities/UnityGitConfiguration.h")] public partial class InternalEditorUtility { public extern static bool isHumanControllingUs { [FreeFunction("IsHumanControllingUs")] get; } public extern static bool isApplicationActive { [FreeFunction("IsApplicationActive")] get; } public extern static bool inBatchMode { [FreeFunction("IsBatchmode")] get; } [StaticAccessor("BumpMapSettings::Get()", StaticAccessorType.Dot)] [NativeMethod("PerformUnmarkedBumpMapTexturesFixingAfterDialog")] public extern static void BumpMapSettingsFixingWindowReportResult(int result); [StaticAccessor("BumpMapSettings::Get()", StaticAccessorType.Dot)] [NativeMethod("PerformUnmarkedBumpMapTexturesFixing")] public extern static bool PerformUnmarkedBumpMapTexturesFixing(); [FreeFunction("InternalEditorUtilityBindings::BumpMapTextureNeedsFixingInternal")] public extern static bool BumpMapTextureNeedsFixingInternal([NotNull] Material material, string propName, bool flaggedAsNormal); internal static bool BumpMapTextureNeedsFixing(MaterialProperty prop) { if (prop.type != MaterialProperty.PropType.Texture) return false; bool hintIfNormal = ((prop.flags & MaterialProperty.PropFlags.Normal) != 0); foreach (Material material in prop.targets) if (BumpMapTextureNeedsFixingInternal(material, prop.name, hintIfNormal)) return true; return false; } [FreeFunction("InternalEditorUtilityBindings::FixNormalmapTextureInternal")] public extern static void FixNormalmapTextureInternal([NotNull] Material material, string propName); internal static void FixNormalmapTexture(MaterialProperty prop) { foreach (Material material in prop.targets) FixNormalmapTextureInternal(material, prop.name); } [FreeFunction("InternalEditorUtilityBindings::GetEditorAssemblyPath")] public extern static string GetEditorAssemblyPath(); [FreeFunction("InternalEditorUtilityBindings::GetEngineAssemblyPath")] public extern static string GetEngineAssemblyPath(); [FreeFunction("InternalEditorUtilityBindings::GetEngineCoreModuleAssemblyPath")] public extern static string GetEngineCoreModuleAssemblyPath(); [FreeFunction("InternalEditorUtilityBindings::GetBuildSystemVariationArgs")] internal extern static string GetBuildSystemVariationArgs(); [FreeFunction("InternalEditorUtilityBindings::CalculateHashForObjectsAndDependencies")] public extern static string CalculateHashForObjectsAndDependencies(Object[] objects); [FreeFunction] public extern static void ExecuteCommandOnKeyWindow(string commandName); [FreeFunction("InternalEditorUtilityBindings::InstantiateMaterialsInEditMode")] public extern static Material[] InstantiateMaterialsInEditMode([NotNull] Renderer renderer); [System.Obsolete("BuildCanBeAppended has been deprecated. Use UnityEditor.BuildPipeline.BuildCanBeAppended instead (UnityUpgradable) -> [UnityEditor] UnityEditor.BuildPipeline.BuildCanBeAppended(*)", true)] public static CanAppendBuild BuildCanBeAppended(BuildTarget target, string location) { return (CanAppendBuild)BuildPipeline.BuildCanBeAppended(target, location); } [FreeFunction] extern internal static void RegisterPlatformModuleAssembly(string dllName, string dllLocation); [FreeFunction] extern internal static void RegisterPrecompiledAssembly(string dllName, string dllLocation); // This lets you add a MonoScript to a game object directly without any type checks or requiring the .NET representation to be loaded already. [FreeFunction("InternalEditorUtilityBindings::AddScriptComponentUncheckedUndoable")] extern internal static int AddScriptComponentUncheckedUndoable([NotNull] GameObject gameObject, [NotNull] MonoScript script); [FreeFunction("InternalEditorUtilityBindings::CreateScriptableObjectUnchecked")] extern internal static int CreateScriptableObjectUnchecked(MonoScript script); [Obsolete("RequestScriptReload has been deprecated. Use UnityEditor.EditorUtility.RequestScriptReload instead (UnityUpgradable) -> [UnityEditor] UnityEditor.EditorUtility.RequestScriptReload(*)")] public static void RequestScriptReload() { EditorUtility.RequestScriptReload(); } // Repaint all views on next tick. Used when the user changes skins in the prefs. [StaticAccessor("GetApplication()", StaticAccessorType.Dot)] [NativeMethod("SwitchSkinAndRepaintAllViews")] extern public static void SwitchSkinAndRepaintAllViews(); [StaticAccessor("GetApplication()", StaticAccessorType.Dot)] extern internal static bool IsSwitchSkinRequested(); [StaticAccessor("GetApplication()", StaticAccessorType.Dot)] [NativeMethod("RequestRepaintAllViews")] extern public static void RepaintAllViews(); [StaticAccessor("GetInspectorExpandedState()", StaticAccessorType.Dot)] [NativeMethod("IsInspectorExpanded")] extern public static bool GetIsInspectorExpanded(Object obj); [StaticAccessor("GetInspectorExpandedState()", StaticAccessorType.Dot)] [NativeMethod("SetInspectorExpanded")] extern public static void SetIsInspectorExpanded(Object obj, bool isExpanded); extern public static int[] expandedProjectWindowItems { [StaticAccessor("AssetDatabase::GetProjectWindowHierarchyState()", StaticAccessorType.Dot)] [NativeMethod("GetExpandedArray")] get; [FreeFunction("InternalEditorUtilityBindings::SetExpandedProjectWindowItems")] set; } public static Assembly LoadAssemblyWrapper(string dllName, string dllLocation) { return (Assembly)LoadAssemblyWrapperInternal(dllName, dllLocation); } [StaticAccessor("GetMonoManager()", StaticAccessorType.Dot)] [NativeMethod("LoadAssembly")] extern internal static object LoadAssemblyWrapperInternal(string dllName, string dllLocation); public static void SaveToSerializedFileAndForget(Object[] obj, string path, bool allowTextSerialization) { SaveToSerializedFileAndForgetInternal(path, obj, allowTextSerialization); } [FreeFunction("SaveToSerializedFileAndForget")] extern private static void SaveToSerializedFileAndForgetInternal(string path, Object[] obj, bool allowTextSerialization); [FreeFunction("InternalEditorUtilityBindings::LoadSerializedFileAndForget")] extern public static Object[] LoadSerializedFileAndForget(string path); [FreeFunction("LoadFileAndForgetOperation::LoadSerializedFileAndForgetAsync")] extern public static LoadFileAndForgetOperation LoadSerializedFileAndForgetAsync(string path, long localIdentifierInFile, ulong offsetInFile=0, long fileSize=-1, Scene destScene = default); [FreeFunction("InternalEditorUtilityBindings::ProjectWindowDrag")] extern public static DragAndDropVisualMode ProjectWindowDrag([Unmarshalled] HierarchyProperty property, bool perform); [FreeFunction("InternalEditorUtilityBindings::HierarchyWindowDrag")] extern public static DragAndDropVisualMode HierarchyWindowDrag([Unmarshalled] HierarchyProperty property, HierarchyDropFlags dropMode, Transform parentForDraggedObjects, bool perform); [FreeFunction("InternalEditorUtilityBindings::HierarchyWindowDragByID")] extern public static DragAndDropVisualMode HierarchyWindowDragByID(int dropTargetInstanceID, HierarchyDropFlags dropMode, Transform parentForDraggedObjects, bool perform); [FreeFunction("InternalEditorUtilityBindings::InspectorWindowDrag")] extern internal static DragAndDropVisualMode InspectorWindowDrag(Object[] targets, bool perform); [FreeFunction("InternalEditorUtilityBindings::SceneViewDrag")] extern public static DragAndDropVisualMode SceneViewDrag(Object dropUpon, Vector3 worldPosition, Vector2 viewportPosition, Transform parentForDraggedObjects, bool perform); [FreeFunction("InternalEditorUtilityBindings::SetRectTransformTemporaryRect")] extern public static void SetRectTransformTemporaryRect([NotNull] RectTransform rectTransform, Rect rect); [Obsolete("HasTeamLicense always returns true, no need to call it")] public static bool HasTeamLicense() { return true; } [FreeFunction("InternalEditorUtilityBindings::HasPro", IsThreadSafe = true)] extern public static bool HasPro(); [FreeFunction("InternalEditorUtilityBindings::HasFreeLicense", IsThreadSafe = true)] extern public static bool HasFreeLicense(); [FreeFunction("InternalEditorUtilityBindings::HasEduLicense", IsThreadSafe = true)] extern public static bool HasEduLicense(); [FreeFunction("InternalEditorUtilityBindings::HasUFSTLicense", IsThreadSafe = true)] extern internal static bool HasUFSTLicense(); [FreeFunction] extern public static bool HasAdvancedLicenseOnBuildTarget(BuildTarget target); public static bool IsMobilePlatform(BuildTarget target) { return BuildTargetDiscovery.PlatformHasFlag(target, TargetAttributes.HasIntegratedGPU); } [NativeThrows] [FreeFunction("InternalEditorUtilityBindings::GetBoundsOfDesktopAtPoint")] extern public static Rect GetBoundsOfDesktopAtPoint(Vector2 pos); [StaticAccessor("GetTagManager()", StaticAccessorType.Dot)] [NativeMethod("RemoveTag")] extern public static void RemoveTag(string tag); [FreeFunction("InternalEditorUtilityBindings::AddTag")] extern public static void AddTag(string tag); extern public static string[] tags { [FreeFunction("InternalEditorUtilityBindings::GetTags")] get; } extern public static string[] layers { [FreeFunction("InternalEditorUtilityBindings::GetLayers")] get; } [FreeFunction("InternalEditorUtilityBindings::GetLayersWithId")] extern static internal string[] GetLayersWithId(); [FreeFunction("InternalEditorUtilityBindings::CanRenameAssetInternal")] extern internal static bool CanRenameAsset(int instanceID); public static LayerMask ConcatenatedLayersMaskToLayerMask(int concatenatedLayersMask) { return ConcatenatedLayersMaskToLayerMaskInternal(concatenatedLayersMask); } [FreeFunction("InternalEditorUtilityBindings::ConcatenatedLayersMaskToLayerMaskInternal")] extern private static int ConcatenatedLayersMaskToLayerMaskInternal(int concatenatedLayersMask); [FreeFunction("TryOpenErrorFileFromConsole")] public extern static bool TryOpenErrorFileFromConsole(string path, int line, int column); [FreeFunction("TryOpenErrorFileFromConsoleInternal")] internal extern static bool TryOpenErrorFileFromConsoleInternal(string path, int line, int column, bool isDryRun); public static bool TryOpenErrorFileFromConsole(string path, int line) { return TryOpenErrorFileFromConsole(path, line, 0); } public static int LayerMaskToConcatenatedLayersMask(LayerMask mask) { return LayerMaskToConcatenatedLayersMaskInternal(mask); } [StaticAccessor("GetTagManager()", StaticAccessorType.Dot)] extern internal static string GetSortingLayerName(int index); [StaticAccessor("GetTagManager()", StaticAccessorType.Dot)] extern internal static int GetSortingLayerUniqueID(int index); [StaticAccessor("GetTagManager()", StaticAccessorType.Dot)] extern internal static string GetSortingLayerNameFromUniqueID(int id); [StaticAccessor("GetTagManager()", StaticAccessorType.Dot)] extern internal static int GetSortingLayerCount(); [StaticAccessor("GetTagManager()", StaticAccessorType.Dot)] extern internal static void SetSortingLayerName(int index, string name); [StaticAccessor("GetTagManager()", StaticAccessorType.Dot)] extern internal static void SetSortingLayerLocked(int index, bool locked); [StaticAccessor("GetTagManager()", StaticAccessorType.Dot)] extern internal static bool GetSortingLayerLocked(int index); [StaticAccessor("GetTagManager()", StaticAccessorType.Dot)] extern internal static bool IsSortingLayerDefault(int index); [StaticAccessor("GetTagManager()", StaticAccessorType.Dot)] extern internal static void AddSortingLayer(); [StaticAccessor("GetTagManager()", StaticAccessorType.Dot)] extern internal static void UpdateSortingLayersOrder(); extern internal static string[] sortingLayerNames { [FreeFunction("InternalEditorUtilityBindings::GetSortingLayerNames")] get; } extern internal static int[] sortingLayerUniqueIDs { [FreeFunction("InternalEditorUtilityBindings::GetSortingLayerUniqueIDs")] get; } // UV coordinates for the outer part of a sliced Sprite (the whole Sprite) [FreeFunction("InternalEditorUtilityBindings::GetSpriteOuterUV")] extern public static Vector4 GetSpriteOuterUV([NotNull] Sprite sprite, bool getAtlasData); [FreeFunction("PPtr<Object>::FromInstanceID")] extern public static Object GetObjectFromInstanceID(int instanceID); [FreeFunction("GetTypeWithoutLoadingObject")] extern public static Type GetTypeWithoutLoadingObject(int instanceID); [FreeFunction("Object::IDToPointer")] extern public static Object GetLoadedObjectFromInstanceID(int instanceID); [StaticAccessor("GetTagManager()", StaticAccessorType.Dot)] [NativeMethod("LayerToString")] extern public static string GetLayerName(int layer); extern public static string unityPreferencesFolder { [FreeFunction] get; } internal static extern string userAppDataFolder { [FreeFunction("GetUserAppDataFolder")] get; } [FreeFunction] extern public static string GetAssetsFolder(); [FreeFunction] extern public static string GetEditorFolder(); [FreeFunction] extern public static bool IsInEditorFolder(string path); public static void ReloadWindowLayoutMenu() { WindowLayout.UpdateWindowLayoutMenu(); } public static void RevertFactoryLayoutSettings(bool quitOnCancel) { WindowLayout.ResetAllLayouts(quitOnCancel); } public static void LoadDefaultLayout() { WindowLayout.LoadDefaultLayout(); } [StaticAccessor("GetRenderSettings()", StaticAccessorType.Dot)] extern internal static void CalculateAmbientProbeFromSkybox(); [Obsolete("SetupShaderMenu is obsolete. You can get list of available shaders with ShaderUtil.GetAllShaderInfos", false)] [FreeFunction("SetupShaderPopupMenu")] extern public static void SetupShaderMenu([NotNull] Material material); [FreeFunction("UnityConfig::GetUnityBuildFullVersion")] extern public static string GetFullUnityVersion(); public static Version GetUnityVersion() { Version version = new Version(GetUnityVersionDigits()); return new Version(version.Major, version.Minor, version.Build, GetUnityRevision()); } [FreeFunction("InternalEditorUtilityBindings::GetUnityVersionDigits")] extern public static string GetUnityVersionDigits(); [FreeFunction("UnityConfig::GetUnityBuildBranchName")] extern public static string GetUnityBuildBranch(); [FreeFunction("UnityConfig::GetUnityBuildHash")] extern public static string GetUnityBuildHash(); [FreeFunction("UnityConfig::GetUnityDisplayVersion")] extern public static string GetUnityDisplayVersion(); [FreeFunction("UnityConfig::GetUnityDisplayVersionVerbose")] extern public static string GetUnityDisplayVersionVerbose(); [FreeFunction("UnityConfig::GetUnityBuildTimeSinceEpoch")] extern public static int GetUnityVersionDate(); [FreeFunction("UnityConfig::GetUnityBuildNumericRevision")] extern public static int GetUnityRevision(); [FreeFunction("UnityConfig::GetUnityProductName")] extern public static string GetUnityProductName(); [FreeFunction("InternalEditorUtilityBindings::IsUnityBeta")] extern public static bool IsUnityBeta(); [FreeFunction("InternalEditorUtilityBindings::GetUnityCopyright")] extern public static string GetUnityCopyright(); [FreeFunction("InternalEditorUtilityBindings::GetLicenseInfoText")] extern public static string GetLicenseInfo(); [Obsolete("GetLicenseFlags is no longer supported", error: true)] [FreeFunction("InternalEditorUtilityBindings::GetLicenseFlags")] extern public static int[] GetLicenseFlags(); [FreeFunction("InternalEditorUtilityBindings::GetAuthToken")] extern public static string GetAuthToken(); [FreeFunction("InternalEditorUtilityBindings::OpenEditorConsole")] extern public static void OpenEditorConsole(); [FreeFunction("InternalEditorUtilityBindings::GetGameObjectInstanceIDFromComponent")] extern public static int GetGameObjectInstanceIDFromComponent(int instanceID); [FreeFunction("InternalEditorUtilityBindings::ReadScreenPixel")] extern public static Color[] ReadScreenPixel(Vector2 pixelPos, int sizex, int sizey); [FreeFunction("InternalEditorUtilityBindings::ReadScreenPixelUnderCursor")] extern public static Color[] ReadScreenPixelUnderCursor(Vector2 cursorPosHint, int sizex, int sizey); [FreeFunction("InternalEditorUtilityBindings::IsAllowedToReadPixelOutsideUnity")] extern internal static bool IsAllowedToReadPixelOutsideUnity(out string errorMessage); [StaticAccessor("GetGpuDeviceManager()", StaticAccessorType.Dot)] [NativeMethod("SetDevice")] extern public static void SetGpuDeviceAndRecreateGraphics(int index, string name); [StaticAccessor("GetGpuDeviceManager()", StaticAccessorType.Dot)] [NativeMethod("IsSupported")] extern public static bool IsGpuDeviceSelectionSupported(); [FreeFunction("InternalEditorUtilityBindings::GetGpuDevices")] extern public static string[] GetGpuDevices(); [FreeFunction("InternalEditorUtilityBindings::OpenPlayerConsole")] extern public static void OpenPlayerConsole(); public static string TextifyEvent(Event evt) { if (evt == null) return "none"; string text = null; switch (evt.keyCode) { case KeyCode.Keypad0: text = "[0]"; break; case KeyCode.Keypad1: text = "[1]"; break; case KeyCode.Keypad2: text = "[2]"; break; case KeyCode.Keypad3: text = "[3]"; break; case KeyCode.Keypad4: text = "[4]"; break; case KeyCode.Keypad5: text = "[5]"; break; case KeyCode.Keypad6: text = "[6]"; break; case KeyCode.Keypad7: text = "[7]"; break; case KeyCode.Keypad8: text = "[8]"; break; case KeyCode.Keypad9: text = "[9]"; break; case KeyCode.KeypadPeriod: text = "[.]"; break; case KeyCode.KeypadDivide: text = "[/]"; break; case KeyCode.KeypadMinus: text = "[-]"; break; case KeyCode.KeypadPlus: text = "[+]"; break; case KeyCode.KeypadEquals: text = "[=]"; break; case KeyCode.KeypadEnter: text = "enter"; break; case KeyCode.UpArrow: text = "up"; break; case KeyCode.DownArrow: text = "down"; break; case KeyCode.LeftArrow: text = "left"; break; case KeyCode.RightArrow: text = "right"; break; case KeyCode.Insert: text = "insert"; break; case KeyCode.Home: text = "home"; break; case KeyCode.End: text = "end"; break; case KeyCode.PageUp: text = "page up"; break; case KeyCode.PageDown: text = "page down"; break; case KeyCode.Backspace: text = "backspace"; break; case KeyCode.Delete: text = "delete"; break; case KeyCode.F1: text = "F1"; break; case KeyCode.F2: text = "F2"; break; case KeyCode.F3: text = "F3"; break; case KeyCode.F4: text = "F4"; break; case KeyCode.F5: text = "F5"; break; case KeyCode.F6: text = "F6"; break; case KeyCode.F7: text = "F7"; break; case KeyCode.F8: text = "F8"; break; case KeyCode.F9: text = "F9"; break; case KeyCode.F10: text = "F10"; break; case KeyCode.F11: text = "F11"; break; case KeyCode.F12: text = "F12"; break; case KeyCode.F13: text = "F13"; break; case KeyCode.F14: text = "F14"; break; case KeyCode.F15: text = "F15"; break; case KeyCode.Escape: text = "[esc]"; break; case KeyCode.Return: text = "return"; break; default: text = "" + evt.keyCode; break; } string modifiers = string.Empty; if (evt.alt) modifiers += "Alt+"; if (evt.command) modifiers += Application.platform == RuntimePlatform.OSXEditor ? "Cmd+" : "Ctrl+"; if (evt.control) modifiers += "Ctrl+"; if (evt.shift) modifiers += "Shift+"; return modifiers + text; } [StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)] [NativeProperty("defaultScreenWidth", TargetType.Field)] extern public static float defaultScreenWidth { get; } [StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)] [NativeProperty("defaultScreenHeight", TargetType.Field)] extern public static float defaultScreenHeight { get; } [StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)] [NativeProperty("defaultWebScreenWidth", TargetType.Field)] extern public static float defaultWebScreenWidth { get; } [StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)] [NativeProperty("defaultWebScreenHeight", TargetType.Field)] extern public static float defaultWebScreenHeight { get; } extern public static float remoteScreenWidth { [FreeFunction("RemoteScreenWidth")] get; } extern public static float remoteScreenHeight { [FreeFunction("RemoteScreenHeight")] get; } [FreeFunction] extern public static string[] GetAvailableDiffTools(); [FreeFunction] extern public static string GetNoDiffToolsDetectedMessage(); [FreeFunction("SetCustomDiffToolData")] extern internal static void SetCustomDiffToolData(string path, string diff2Command, string diff3Command, string mergeCommand); [FreeFunction("SetCustomDiffToolPrefs")] extern internal static void SetCustomDiffToolPrefs(string path, string diff2Command, string diff3Command, string mergeCommand); [FreeFunction("InternalEditorUtilityBindings::TransformBounds")] extern public static Bounds TransformBounds(Bounds b, Transform t); [StaticAccessor("CustomLighting::Get()", StaticAccessorType.Dot)] [NativeMethod("SetCustomLighting")] extern public static void SetCustomLightingInternal([Unmarshalled] Light[] lights, Color ambient); public static void SetCustomLighting(Light[] lights, Color ambient) { if (lights == null) throw new System.ArgumentNullException("lights"); SetCustomLightingInternal(lights, ambient); } [StaticAccessor("CustomLighting::Get()", StaticAccessorType.Dot)] [NativeMethod("RestoreSceneLighting")] extern public static void RemoveCustomLighting(); [StaticAccessor("GetRenderManager()", StaticAccessorType.Dot)] extern public static bool HasFullscreenCamera(); public static Bounds CalculateSelectionBounds(bool usePivotOnlyForParticles, bool onlyUseActiveSelection) { return CalculateSelectionBounds(usePivotOnlyForParticles, onlyUseActiveSelection, false); } [FreeFunction] extern public static Bounds CalculateSelectionBounds(bool usePivotOnlyForParticles, bool onlyUseActiveSelection, bool ignoreEditableField); internal static Bounds CalculateSelectionBoundsInSpace(Vector3 position, Quaternion rotation, bool rectBlueprintMode) { Quaternion inverseRotation = Quaternion.Inverse(rotation); Vector3 min = new Vector3(float.MaxValue - 1f, float.MaxValue - 1f, float.MaxValue - 1f); Vector3 max = new Vector3(float.MinValue + 1f, float.MinValue + 1f, float.MinValue + 1f); Vector3[] minmax = new Vector3[2]; foreach (GameObject gameObject in Selection.gameObjects) { Bounds localBounds = GetLocalBounds(gameObject); minmax[0] = localBounds.min; minmax[1] = localBounds.max; for (int x = 0; x < 2; x++) { for (int y = 0; y < 2; y++) { for (int z = 0; z < 2; z++) { Vector3 point = new Vector3(minmax[x].x, minmax[y].y, minmax[z].z); if (rectBlueprintMode && SupportsRectLayout(gameObject.transform)) { Vector3 localPosXY = gameObject.transform.localPosition; localPosXY.z = 0; point = gameObject.transform.parent.TransformPoint(point + localPosXY); } else { point = gameObject.transform.TransformPoint(point); } point = inverseRotation * (point - position); for (int axis = 0; axis < 3; axis++) { min[axis] = Mathf.Min(min[axis], point[axis]); max[axis] = Mathf.Max(max[axis], point[axis]); } } } } } return new Bounds((min + max) * 0.5f, max - min); } internal static bool SupportsRectLayout(Transform tr) { if (tr == null || tr.parent == null) return false; if (tr.GetComponent<RectTransform>() == null || tr.parent.GetComponent<RectTransform>() == null) return false; return true; } private static Bounds GetLocalBounds(GameObject gameObject) { if (gameObject.TryGetComponent(out RectTransform rectTransform)) return new Bounds(rectTransform.rect.center, rectTransform.rect.size); // Account for case where there is a mesh filter but no renderer if (gameObject.TryGetComponent(out MeshFilter filter) && filter.sharedMesh != null) return filter.sharedMesh.bounds; if (gameObject.TryGetComponent(out Renderer renderer)) { if (renderer is SpriteRenderer) return ((SpriteRenderer)renderer).GetSpriteBounds(); if (renderer is SpriteMask) return ((SpriteMask)renderer).GetSpriteBounds(); if (renderer is UnityEngine.U2D.SpriteShapeRenderer) return ((UnityEngine.U2D.SpriteShapeRenderer)renderer).GetLocalAABB(); if (renderer is UnityEngine.Tilemaps.TilemapRenderer && renderer.TryGetComponent(out UnityEngine.Tilemaps.Tilemap tilemap)) return tilemap.localBounds; } return new Bounds(Vector3.zero, Vector3.zero); } [FreeFunction("SetPlayerFocus")] extern public static void OnGameViewFocus(bool focus); [FreeFunction("OpenScriptFile")] extern public static bool OpenFileAtLineExternal(string filename, int line, int column); public static bool OpenFileAtLineExternal(string filename, int line) { if (!CodeEditor.Editor.CurrentCodeEditor.OpenProject(filename, line)) { return OpenFileAtLineExternal(filename, line, 0); } return true; } [FreeFunction("AssetDatabaseDeprecated::CanConnectToCacheServer")] extern public static bool CanConnectToCacheServer(); [FreeFunction] extern public static DllType DetectDotNetDll(string path); [FreeFunction] internal static extern bool IsDotNetDll(string path); public static bool IsDotNet4Dll(string path) { var dllType = DetectDotNetDll(path); switch (dllType) { case UnityEditorInternal.DllType.Unknown: case UnityEditorInternal.DllType.Native: case UnityEditorInternal.DllType.UnknownManaged: case UnityEditorInternal.DllType.ManagedNET35: return false; case UnityEditorInternal.DllType.ManagedNET40: case UnityEditorInternal.DllType.WinMDNative: case UnityEditorInternal.DllType.WinMDNET40: return true; default: throw new Exception(string.Format("Unknown dll type: {0}", dllType)); } } internal static bool RunningUnderWindows8(bool orHigher = true) { if (Application.platform == RuntimePlatform.WindowsEditor) { OperatingSystem sys = System.Environment.OSVersion; int major = sys.Version.Major; int minor = sys.Version.Minor; // Window 8 is technically version 6.2 if (orHigher) return major > 6 || (major == 6 && minor >= 2); else return major == 6 && minor == 2; } return false; } [FreeFunction("UnityExtensions::IsValidExtensionPath")] extern internal static bool IsValidUnityExtensionPath(string path); [StaticAccessor("UnityExtensions::Get()", StaticAccessorType.Dot)] [NativeMethod("IsRegistered")] extern internal static bool IsUnityExtensionRegistered(string filename); [StaticAccessor("UnityExtensions::Get()", StaticAccessorType.Dot)] [NativeMethod("IsCompatibleWithEditor")] extern internal static bool IsUnityExtensionCompatibleWithEditor(BuildTarget target, string path); [FreeFunction(IsThreadSafe = true)] extern public static bool CurrentThreadIsMainThread(); // Internal property to check if the currently selected Assets can be renamed, used to unify rename logic between native and c# extern internal static bool canRenameSelectedAssets { [FreeFunction("CanRenameSelectedAssets")] get; } [FreeFunction("InternalEditorUtilityBindings::GetCrashReportFolder")] extern public static string GetCrashReportFolder(); [FreeFunction("InternalEditorUtilityBindings::GetCrashHandlerProcessID")] extern public static UInt32 GetCrashHandlerProcessID(); [FreeFunction("InternalEditorUtilityBindings::DrawSkyboxMaterial")] extern internal static void DrawSkyboxMaterial([NotNull] Material mat, [NotNull] Camera cam); [FreeFunction("InternalEditorUtilityBindings::ResetCursor")] extern public static void ResetCursor(); [FreeFunction("InternalEditorUtilityBindings::VerifyCacheServerIntegrity")] extern public static UInt64 VerifyCacheServerIntegrity(); [FreeFunction("InternalEditorUtilityBindings::FixCacheServerIntegrityErrors")] extern public static UInt64 FixCacheServerIntegrityErrors(); [FreeFunction] extern public static int DetermineDepthOrder(Transform lhs, Transform rhs); internal static PrecompiledAssembly[] GetUnityAssemblies(bool buildingForEditor, BuildTarget target) { return GetUnityAssembliesInternal(buildingForEditor, target); } [FreeFunction("GetUnityAssembliesManaged")] extern private static PrecompiledAssembly[] GetUnityAssembliesInternal(bool buildingForEditor, BuildTarget target); [FreeFunction("GetPrecompiledAssemblyPathsManaged")] extern internal static string[] GetPrecompiledAssemblyPaths(); [FreeFunction("GetEditorAssembliesPath")] extern internal static string GetEditorScriptAssembliesPath(); [Obsolete("The Module Manager is deprecated", error: true)] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static void ShowPackageManagerWindow() { throw new NotSupportedException("The Module Manager is deprecated"); } // For testing Vector2 marshalling [FreeFunction("InternalEditorUtilityBindings::PassAndReturnVector2")] extern public static Vector2 PassAndReturnVector2(Vector2 v); // For testing Color32 marshalling [FreeFunction("InternalEditorUtilityBindings::PassAndReturnColor32")] extern public static Color32 PassAndReturnColor32(Color32 c); [FreeFunction("InternalEditorUtilityBindings::SaveCursorToFile")] extern public static bool SaveCursorToFile(string path, Texture2D image, Vector2 hotSpot); [FreeFunction("InternalEditorUtilityBindings::SaveCursorToInMemoryResource")] extern internal static bool SaveCursorToInMemoryResource(Texture2D image, Vector2 hotSpot, ushort cursorDataResourceId, IntPtr cursorDirectoryBuffer, uint cursorDirectoryBufferSize, IntPtr cursorDataBuffer, uint cursorDataBufferSize); [FreeFunction("GetScriptCompilationDefines")] extern internal static string[] GetCompilationDefines(EditorScriptCompilationOptions options, BuildTarget target, int subtarget, ApiCompatibilityLevel apiCompatibilityLevel, string[] extraDefines = null); //Launches an application that is kept alive, even during a domain reload [FreeFunction("LaunchApplication")] extern internal static bool LaunchApplication(string path, string[] arguments); public static string CountToString(ulong count) { string[] names = {"G", "M", "k", ""}; float[] magnitudes = {1000000000.0f, 1000000.0f, 1000.0f, 1.0f}; int index = 0; while (index < 3 && count < (magnitudes[index] / 2.0f)) { index++; } float result = count / magnitudes[index]; return result.ToString("0.0", CultureInfo.InvariantCulture.NumberFormat) + names[index]; } [StaticAccessor("GetSceneManager()", StaticAccessorType.Dot)] [NativeMethod("EnsureUntitledSceneHasBeenSaved")] [Obsolete("use EditorSceneManager.EnsureUntitledSceneHasBeenSaved")] extern public static bool EnsureSceneHasBeenSaved(string operation); internal static void PrepareDragAndDropTesting(EditorWindow editorWindow) { if (editorWindow.m_Parent != null) PrepareDragAndDropTestingInternal(editorWindow.m_Parent); } [FreeFunction("InternalEditorUtilityBindings::PrepareDragAndDropTestingInternal")] extern internal static void PrepareDragAndDropTestingInternal(GUIView guiView); [FreeFunction("InternalEditorUtilityBindings::LayerMaskToConcatenatedLayersMaskInternal")] extern private static int LayerMaskToConcatenatedLayersMaskInternal(int mask); [StaticAccessor("GetApplication()", StaticAccessorType.Dot)] internal static extern bool IsScriptReloadRequested(); [FreeFunction("HandleProjectWindowFileDrag")] internal static extern DragAndDropVisualMode HandleProjectWindowFileDrag(string newParentPath, string[] paths, bool perform, int defaultPromptAction); //Drag and drop current selection to project window //Set prefabVariantCreationModeDialogChoice to -1 to allow dialogs to be shown. //If set to 0 or 1 no dialogs will be shown. Using a value of 0 is similar to choosing PrefabVariantCreationMode::kOriginal and a value of 1 is similar to choosing PrefabVariantCreationMode::kVariant from the "Create Prefab or Variant" dialog if dropping a Prefab instance to the Project Browser. //Non-zero values also blocks the "Cyclic References" error dialog, and it defaults the "Possibly unwanted Prefab replacement" menu to return "Replace Anyway". [FreeFunction("InternalEditorUtilityBindings::DragAndDropPrefabsFromHierarchyToProjectWindow")] internal static extern DragAndDropVisualMode DragAndDropPrefabsFromHierarchyToProjectWindow(string destAssetGuid, bool perform, int prefabVariantCreationModeDialogChoice); [FreeFunction] [NativeHeader("Editor/Src/Undo/DefaultParentObjectUndo.h")] internal static extern void RegisterSetDefaultParentObjectUndo(string sceneGUID, int instanceID, string undoName); // Aux window functionality is quite brittle. It is strongly advised to avoid // using this method but if you really need it, consult Desktop team first. [StaticAccessor("GetAuxWindowManager()", StaticAccessorType.Dot)] internal static extern void RetainAuxWindows(); } }
UnityCsReference/Editor/Mono/InternalEditorUtility.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/InternalEditorUtility.bindings.cs", "repo_id": "UnityCsReference", "token_count": 17241 }
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.Linq; using UnityEngine; using UnityEngine.Bindings; namespace UnityEditor { [NativeHeader("Editor/Src/BuildPipeline/ModuleMetadata.h")] internal enum ModuleIncludeSetting { Auto = 0, ForceExclude = 1, ForceInclude = 2 } [StaticAccessor("ModuleMetadata::Get()", StaticAccessorType.Dot)] [NativeHeader("Editor/Src/BuildPipeline/ModuleMetadata.h")] [NativeHeader("Editor/Mono/ModuleMetadata.bindings.h")] internal sealed class ModuleMetadata { [FreeFunction("ModuleMetadataBindings::GetModuleNames")] public extern static string[] GetModuleNames(); [FreeFunction("ModuleMetadataBindings::GetModuleDependencies")] public extern static string[] GetModuleDependencies(string moduleName); [FreeFunction("ModuleMetadataBindings::IsStrippableModule")] extern public static bool IsStrippableModule(string moduleName); public static UnityType[] GetModuleTypes(string moduleName) { var runtimeTypeIndices = GetModuleTypeIndices(moduleName); return runtimeTypeIndices.Select(index => UnityType.GetTypeByRuntimeTypeIndex(index)).ToArray(); } [NativeName("GetModuleIncludeSetting")] extern public static ModuleIncludeSetting GetModuleIncludeSettingForModule(string module); [FreeFunction("ModuleMetadataBindings::SetModuleIncludeSettingForModule")] extern public static void SetModuleIncludeSettingForModule(string module, ModuleIncludeSetting setting); [FreeFunction("ModuleMetadataBindings::GetModuleIncludeSettingForObject")] extern internal static ModuleIncludeSetting GetModuleIncludeSettingForObject(Object o); [FreeFunction("ModuleMetadataBindings::GetModuleForObject")] extern internal static string GetModuleForObject(Object o); [FreeFunction("ModuleMetadataBindings::GetModuleTypeIndices")] extern internal static uint[] GetModuleTypeIndices(string moduleName); extern public static string GetICallModule(string icall); } }
UnityCsReference/Editor/Mono/ModuleMetadata.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/ModuleMetadata.bindings.cs", "repo_id": "UnityCsReference", "token_count": 765 }
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.Bindings; using UnityEngine.Scripting; using System.Runtime.InteropServices; namespace UnityEditor { [NativeHeader("Editor/Src/Animation/MuscleClipQualityInfo.h")] [RequiredByNativeCode] [NativeAsStruct] [StructLayout(LayoutKind.Sequential)] internal class MuscleClipQualityInfo { [NativeName("m_Loop")] public float loop = 0; [NativeName("m_LoopOrientation")] public float loopOrientation = 0; [NativeName("m_LoopPositionY")] public float loopPositionY = 0; [NativeName("m_LoopPositionXZ")] public float loopPositionXZ = 0; } internal struct QualityCurvesTime { public float fixedTime; public float variableEndStart; public float variableEndEnd; public int q; } [NativeHeader("Editor/Src/Animation/MuscleClipQualityInfo.h")] internal class MuscleClipUtility { [FreeFunction] extern internal static MuscleClipQualityInfo GetMuscleClipQualityInfo([NotNull] AnimationClip clip, float startTime, float stopTime); internal static void CalculateQualityCurves(AnimationClip clip, QualityCurvesTime time, Vector2[] poseCurve, Vector2[] rotationCurve, Vector2[] heightCurve, Vector2[] positionCurve) { if (poseCurve.Length != rotationCurve.Length || rotationCurve.Length != heightCurve.Length || heightCurve.Length != positionCurve.Length) { throw new ArgumentException(string.Format( "poseCurve '{0}', rotationCurve '{1}', heightCurve '{2}' and positionCurve '{3}' Length must be equals.", poseCurve.Length, rotationCurve.Length, heightCurve.Length, positionCurve.Length)); } CalculateQualityCurves(clip, time.fixedTime, time.variableEndStart, time.variableEndEnd, time.q, poseCurve, rotationCurve, heightCurve, positionCurve); } [FreeFunction] extern protected static void CalculateQualityCurves([NotNull] AnimationClip clip, float fixedTime, float variableEndStart, float variableEndEnd, int q, [Out] Vector2[] poseCurve, [Out] Vector2[] rotationCurve, [Out] Vector2[] heightCurve, [Out] Vector2[] positionCurve); } }
UnityCsReference/Editor/Mono/MuscleClipUtility.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/MuscleClipUtility.bindings.cs", "repo_id": "UnityCsReference", "token_count": 912 }
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 System.ComponentModel; using UnityEditor.Toolbars; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.Overlays { [Flags] public enum Layout { HorizontalToolbar = 1 << 0, VerticalToolbar = 1 << 1, Panel = 1 << 2, All = Panel | HorizontalToolbar | VerticalToolbar, } // See also OverlayPlacement.cs public abstract partial class Overlay { const string k_UxmlPath = "UXML/Overlays/overlay.uxml"; public static readonly string ussClassName = "unity-overlay"; const string k_Highlight = "overlay-box-highlight"; const string k_Floating = "overlay--floating"; internal const string headerTitle = "overlay-header__title"; const string k_Collapsed = "unity-overlay--collapsed"; internal const string k_Header = "overlay-header"; const string k_Expanded = "unity-overlay--expanded"; internal const string k_CollapsedContent = "overlay-collapsed-content"; const string k_CollapsedIconButton = "unity-overlay-collapsed-dropdown__icon"; internal const string k_ToolbarHorizontalLayout = "overlay-layout--toolbar-horizontal"; internal const string k_ToolbarVerticalLayout = "overlay-layout--toolbar-vertical"; const string k_PanelLayout = "overlay-layout--freesize"; internal const string draggerName = "unity-overlay-collapse__dragger"; string m_Id, m_RootVisualElementName, m_DisplayName; Layout m_ActiveLayout = Layout.Panel; internal bool dontSaveInLayout {get; set;} internal bool m_HasMenuEntry = true; [SerializeField] Layout m_Layout = Layout.Panel; [SerializeField] bool m_Collapsed; [SerializeField] bool m_Floating; [SerializeField] Vector2 m_FloatingSnapOffset; [SerializeField] internal Vector2 m_SnapOffsetDelta = Vector2.zero; [SerializeField] SnapCorner m_FloatingSnapCorner = SnapCorner.TopLeft; //Min and Max being 0 means the resizing is disabled for that axis without enforcing an actual size //Resizing is disabled by default [SerializeField] Vector2 m_Size; [SerializeField] bool m_SizeOverridden; Vector2 m_MinSize = Vector2.zero; Vector2 m_MaxSize = Vector2.zero; Vector2 m_DefaultSize = Vector2.zero; // Temporary Variables bool m_LockAnchor = false; bool m_ContentsChanged = true; internal bool m_DisableContentModification = false; // Connections public EditorWindow containerWindow => canvas.containerWindow; internal OverlayCanvas canvas { get; set; } internal bool isPopup { get; set; } OverlayContainer m_Container; internal OverlayContainer tempTargetContainer { get; set; } // Instantiated VisualElement contents VisualElement m_CurrentContent; VisualElement m_CollapsedContent; OverlayPopup m_ModalPopup; // collapsed popup root VisualElement m_RootVisualElement; VisualElement m_ResizeTarget; internal VisualElement resizeTarget => m_ResizeTarget; OverlayDropZone m_BeforeDropZone; OverlayDropZone m_AfterDropZone; internal OverlayDropZone insertBeforeDropZone => m_BeforeDropZone; internal OverlayDropZone insertAfterDropZone => m_AfterDropZone; // Callbacks public event Action<Layout> layoutChanged; public event Action<bool> collapsedChanged; public event Action<bool> displayedChanged; internal event Action<OverlayContainer> containerChanged; internal event Action minSizeChanged; internal event Action maxSizeChanged; internal event Action defaultSizeChanged; internal event Action sizeOverridenChanged; // Invoked in partial class OverlayPlacement.cs #pragma warning disable 67 public event Action<bool> floatingChanged; public event Action<Vector3> floatingPositionChanged; #pragma warning restore 67 public string id { get => m_Id; internal set { m_Id = value; } } static VisualTreeAsset s_TreeAsset; event Action displayNameChanged; VisualElement m_ContentRoot; // Properties internal bool hasMenuEntry => m_HasMenuEntry; internal Rect collapsedButtonRect => collapsedContent.worldBound; Texture2D m_CollapsedIcon = null; public Texture2D collapsedIcon { set { if(m_CollapsedIcon != null && m_CollapsedIcon.Equals(value)) return; m_CollapsedIcon = value; if (m_CollapsedContent == null) return; var iconElement = collapsedContent.Q<Label>(classes: k_CollapsedIconButton); if(iconElement != null) { var iconTexture = m_CollapsedIcon == null ? EditorGUIUtility.LoadIcon(EditorGUIUtility.GetIconPathFromAttribute(GetType())) : m_CollapsedIcon; var collapsedIcon = GetCollapsedIconContent(); var image = collapsedIcon.image as Texture2D; iconElement.style.backgroundImage = image; iconElement.text = image != null ? null : OverlayUtilities.GetSignificantLettersForIcon(displayName); } } } VisualElement collapsedContent { get { if (m_CollapsedContent != null) return m_CollapsedContent; m_CollapsedContent = rootVisualElement.Q(k_CollapsedContent); m_CollapsedContent.Q<Button>().clicked += ToggleCollapsedPopup; var iconElement = rootVisualElement.Q<Label>(classes: k_CollapsedIconButton); var collapsedIcon = GetCollapsedIconContent(); if (collapsedIcon.image != null) iconElement.style.backgroundImage = collapsedIcon.image as Texture2D; else iconElement.text = collapsedIcon.text; return m_CollapsedContent; } } public Layout layout { get => m_Layout; internal set { if(m_DisableContentModification) { Debug.LogError(GetEventTypeErrorMessage("Overlay.layout")); return; } if (m_Layout == value) return; m_Layout = value; RebuildContent(); } } // layout is the preferred layout, active layout is what this overlay is actually using protected internal Layout activeLayout => m_ActiveLayout; public bool collapsed { get => m_CollapsedContent != null && m_CollapsedContent.parent == contentRoot; set { if(m_DisableContentModification) { Debug.LogError(GetEventTypeErrorMessage("Overlay.collapsed")); return; } m_Collapsed = value; if (m_Collapsed != (m_CollapsedContent != null && m_CollapsedContent.parent == contentRoot)) RebuildContent(); } } public string displayName { get { if (String.IsNullOrEmpty(m_DisplayName)) return rootVisualElement.name; return m_DisplayName; } set { if (m_DisplayName != value) { m_DisplayName = value; displayNameChanged?.Invoke(); } } } internal bool userControlledVisibility => !(this is IControlVisibility || this is ITransientOverlay); internal OverlayContainer container { get => m_Container; set { if (m_Container == value) return; m_Container = value; containerChanged?.Invoke(m_Container); } } internal DockZone dockZone => floating ? DockZone.Floating : OverlayCanvas.GetDockZone(container); internal DockPosition dockPosition => container.GetSection(OverlayContainerSection.BeforeSpacer).Contains(this) ? DockPosition.Top : DockPosition.Bottom; internal static VisualTreeAsset treeAsset { get { if (s_TreeAsset != null) return s_TreeAsset; return s_TreeAsset = (VisualTreeAsset)EditorGUIUtility.Load(k_UxmlPath); } } public bool displayed { get => rootVisualElement.style.display == DisplayStyle.Flex; set { if (rootVisualElement.style.display != (value ? DisplayStyle.Flex : DisplayStyle.None)) { if(m_DisableContentModification) { Debug.LogError(GetEventTypeErrorMessage("Overlay.displayed")); return; } rootVisualElement.style.display = value ? DisplayStyle.Flex : DisplayStyle.None; RebuildContent(); displayedChanged?.Invoke(value); } } } // Externally supported layouts are enforced by implementing ICreate interfaces. Internally we need a dynamic // solution to handle CustomEditors. This isn't exposed because it would require much more validation to ensure // that `supportedLayouts` is correct when coming from external code, whereas internally we can trust that this // value is correct. [EditorBrowsable(EditorBrowsableState.Never)] protected internal virtual Layout supportedLayouts { get { var supported = Layout.Panel; if (this is ICreateToolbar) supported |= Layout.HorizontalToolbar | Layout.VerticalToolbar; if (this is ICreateHorizontalToolbar) supported |= Layout.HorizontalToolbar; if (this is ICreateVerticalToolbar) supported |= Layout.VerticalToolbar; return supported; } } public VisualElement rootVisualElement { get { if (m_RootVisualElement != null) return m_RootVisualElement; m_RootVisualElement = new VisualElement(); treeAsset.CloneTree(m_RootVisualElement); m_RootVisualElement.name = m_RootVisualElementName; m_RootVisualElement.usageHints = UsageHints.DynamicTransform; m_RootVisualElement.AddToClassList(ussClassName); var dragger = new OverlayDragger(this); var contextClick = new ContextualMenuManipulator(BuildContextMenu); var header = m_RootVisualElement.Q(null, k_Header); header.AddManipulator(contextClick); header.AddManipulator(dragger); var title = m_RootVisualElement.Q<Label>(headerTitle); title.text = displayName; displayNameChanged += () => title.text = displayName; var dockArea = new VisualElement() { name = "OverlayDockArea" }; dockArea.pickingMode = PickingMode.Ignore; dockArea.StretchToParentSize(); m_RootVisualElement.Add(dockArea); dockArea.Add(m_BeforeDropZone = new OverlayDropZone(this, OverlayDropZone.Placement.Before)); dockArea.Add(m_AfterDropZone = new OverlayDropZone(this, OverlayDropZone.Placement.After)); m_RootVisualElement.tooltip = L10n.Tr(displayName); m_ResizeTarget = m_RootVisualElement.Q("unity-overlay"); m_ResizeTarget.style.overflow = Overflow.Hidden; m_ResizeTarget.Add(new OverlayResizerGroup(this)); return m_RootVisualElement; } } // used by tests internal VisualElement contentRoot { get { if(m_ContentRoot != null) return m_ContentRoot; m_ContentRoot = rootVisualElement.Q("overlay-content"); m_ContentRoot.renderHints = RenderHints.ClipWithScissors; return m_ContentRoot; } } public bool isInToolbar => container is ToolbarOverlayContainer; internal bool sizeOverridden { get => m_SizeOverridden; set { if (m_SizeOverridden == value) return; m_SizeOverridden = value; sizeOverridenChanged?.Invoke(); } } internal Vector2 sizeToSave => m_Size; public Vector2 size { get { return m_ResizeTarget.layout.size; } set { if (m_Size == value && sizeOverridden) return; m_Size = value; sizeOverridden = true; UpdateSize(); } } public Vector2 minSize { get => m_MinSize; set { if (m_MinSize == value) return; m_MinSize = value; minSizeChanged?.Invoke(); UpdateSize(); } } public Vector2 maxSize { get => m_MaxSize; set { if (m_MaxSize == value) return; m_MaxSize = value; maxSizeChanged?.Invoke(); UpdateSize(); } } public Vector2 defaultSize { get => m_DefaultSize; set { if (m_DefaultSize == value) return; m_DefaultSize = value; defaultSizeChanged?.Invoke(); UpdateSize(); } } internal static string GetEventTypeErrorMessage(string errorEvent) { return L10n.Tr($"Cannot modify {errorEvent} during event of type EventType.Layout"); } internal void ResetSize() { if (!sizeOverridden) return; sizeOverridden = false; UpdateSize(); } bool CanCreateRequestedLayout(Layout requested) { // Is layout requesting a toolbar while Overlay is not implementing ICreateToolbar? if ((int)(requested & supportedLayouts) < 1) return false; if (tempTargetContainer != null) return tempTargetContainer.IsOverlayLayoutSupported(requested); return floating || container == null || container.IsOverlayLayoutSupported(requested); } Layout GetBestLayoutForState() { // Always prefer the user-set layout if (CanCreateRequestedLayout(layout)) return layout; for (int i = 0; i < 3; i++) { if (CanCreateRequestedLayout((Layout)(1 << i))) return (Layout)(1 << i); } return 0; } internal VisualElement GetSimpleHeader() { var header = new VisualElement(); var title = new Label(displayName); title.name = headerTitle; header.Add(title); return header; } // Rebuild the Overlay contents, taking into account the container and layout. If the container does not support // the requested layout, the overlay will be collapsed (the collapsed property will not be modified, and the // next time RebuildContent is invoked this method will try again to build the requested layout and un-collapse // the Overlay). internal void RebuildContent() { if (m_Container == null) return; // We need to invoke a callback if the collapsed state changes (either from user request or invalid layout) bool wasCollapsed = collapsedContent.parent == contentRoot; var prevLayout = m_ActiveLayout; m_ActiveLayout = GetBestLayoutForState(); // Clear any existing contents. m_CurrentContent?.RemoveFromHierarchy(); collapsedContent.RemoveFromHierarchy(); m_CurrentContent = null; if (!displayed) return; // An Overlay can collapsed by request, or by necessity. If collapsed due to invalid layout/container match, // the collapsed property is not modified. The next time a content rebuild is requested we'll try again to // create the contents with the stored state. bool isCollapsed = m_Collapsed || activeLayout == 0; var targetContainer = tempTargetContainer ?? container; if (isCollapsed) { if (collapsedContent.parent != contentRoot) contentRoot.Add(collapsedContent); } else { m_CurrentContent = CreateContent(m_ActiveLayout); contentRoot.Add(m_CurrentContent); } m_ContentsChanged = true; m_ActiveLayout = m_ActiveLayout == 0 ? targetContainer.preferredLayout : m_ActiveLayout; // Update styling if (floating) { rootVisualElement.style.position = Position.Absolute; rootVisualElement.AddToClassList(k_Floating); } else { rootVisualElement.style.position = Position.Relative; rootVisualElement.transform.position = Vector3.zero; rootVisualElement.RemoveFromClassList(k_Floating); } rootVisualElement.EnableInClassList(k_ToolbarVerticalLayout, m_ActiveLayout == Layout.VerticalToolbar); rootVisualElement.EnableInClassList(k_ToolbarHorizontalLayout, m_ActiveLayout == Layout.HorizontalToolbar); rootVisualElement.EnableInClassList(k_PanelLayout, m_ActiveLayout == Layout.Panel); rootVisualElement.EnableInClassList(k_Collapsed, isCollapsed); rootVisualElement.EnableInClassList(k_Expanded, !isCollapsed); // Disable drop zone previews when floating var dropZonesDisplay = !floating ? DisplayStyle.Flex : DisplayStyle.None; m_BeforeDropZone.style.display = dropZonesDisplay; m_AfterDropZone.style.display = dropZonesDisplay; UpdateSize(); // Invoke callbacks after content is created and styling has been applied if(wasCollapsed != isCollapsed) collapsedChanged?.Invoke(isCollapsed); if (prevLayout != m_ActiveLayout) layoutChanged?.Invoke(m_ActiveLayout); } internal GUIContent GetCollapsedIconContent() { var icon = m_CollapsedIcon == null ? EditorGUIUtility.LoadIcon(EditorGUIUtility.GetIconPathFromAttribute(GetType())) : m_CollapsedIcon; if (icon != null) return new GUIContent(icon); return new GUIContent(OverlayUtilities.GetSignificantLettersForIcon(displayName)); } internal bool IsResizable() { return activeLayout == Layout.Panel && !collapsed; } bool IsSizeAuto(float size) { return size <= 0 || float.IsNegativeInfinity(size); } void UpdateSize() { if (m_ResizeTarget == null) return; ApplySize(m_ResizeTarget, IsResizable(), sizeOverridden); var position = canvas.ClampToOverlayWindow(new Rect(floatingPosition, m_Size)).position; UpdateSnapping(position); } void ApplySize(VisualElement element, bool resizableLayout, bool sizeOverridden) { element.style.minWidth = resizableLayout && !IsSizeAuto(m_MinSize.x) ? m_MinSize.x : new StyleLength(StyleKeyword.Auto); element.style.minHeight = resizableLayout && !IsSizeAuto(m_MinSize.y) ? m_MinSize.y : new StyleLength(StyleKeyword.Auto); element.style.maxWidth = resizableLayout && !IsSizeAuto(m_MaxSize.x) ? m_MaxSize.x : new StyleLength(StyleKeyword.Auto); element.style.maxHeight = resizableLayout && !IsSizeAuto(m_MaxSize.y) ? m_MaxSize.y : new StyleLength(StyleKeyword.Auto); if (resizableLayout && sizeOverridden) { element.style.width = m_Size.x; element.style.height = m_Size.y; } else { element.style.width = defaultSize.x > 0 && resizableLayout ? defaultSize.x : new StyleLength(StyleKeyword.Auto); element.style.height = defaultSize.y > 0 && resizableLayout ? defaultSize.y : new StyleLength(StyleKeyword.Auto); } } // CreateContent always returns a new VisualElement tree with the Overlay contents. It does not modify the // m_CurrentContent or m_ContentRoot properties. Use RebuildContent() to update an Overlay contents. // CreateContent will try to return content in the requested layout, regardless of whether the container // supports it. The only reason that content would not be created with the requested layout is if the Overlay // does not implement the correct ICreate{Horizontal, Vertical}Toolbar interface. // To rebuild content taking into account the parent container, use RebuildContent(). public VisualElement CreateContent(Layout requestedLayout) { var previousContent = m_ContentRoot; try { VisualElement content = null; switch (requestedLayout) { case Layout.HorizontalToolbar: if (!(this is ICreateHorizontalToolbar horizontal) || (content = horizontal.CreateHorizontalToolbarContent()) == null) goto default; break; case Layout.VerticalToolbar: if (!(this is ICreateVerticalToolbar vertical) || (content = vertical.CreateVerticalToolbarContent()) == null) goto default; break; case Layout.Panel: content = CreatePanelContent(); break; default: if (!(this is ICreateToolbar toolbar)) { Debug.LogError($"Overlay {GetType()} attempting to set unsupported layout: {requestedLayout}"); goto case Layout.Panel; } content = new EditorToolbar(toolbar.toolbarElements, canvas.containerWindow).rootVisualElement; break; } if (content != null) { // When this happens styling isn't applied correctly when transitioning between popup window and // floating/docked. if (content == previousContent) Debug.LogError($"Overlay named \"{displayName}\" returned a reference to the previous " + $" content. This is not allowed; CreateContent() must return a new instance."); return content; } } catch (Exception e) { Debug.LogError($"Failed loading overlay \"{displayName}\"!\n{e}"); return new Label($"{displayName} failed to load"); } Debug.LogError($"Overlay \"{displayName}\" returned a null VisualElement."); return new Label($"{displayName} failed to load"); } public abstract VisualElement CreatePanelContent(); // Invoked when an Overlay is added to an OverlayCanvas public virtual void OnCreated() {} public virtual void OnWillBeDestroyed() {} public void Close() => canvas?.Remove(this); // Used by tests internal VisualElement popup => m_ModalPopup; // Used by tests internal void ToggleCollapsedPopup() { if (m_ModalPopup != null) { ClosePopup(); return; } m_ModalPopup = OverlayPopup.CreateUnderOverlay(this); ApplySize(m_ModalPopup.Q(className: "overlay-box-background"), true, sizeOverridden); m_ModalPopup.RegisterCallback<FocusOutEvent>(evt => { if (evt.relatedTarget is VisualElement target && (m_ModalPopup == target || m_ModalPopup.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_ModalPopup.containsCursor) EditorApplication.delayCall += m_ModalPopup.Focus; else ClosePopup(); }); canvas.rootVisualElement.Add(m_ModalPopup); m_ModalPopup.Focus(); } void ClosePopup() { m_ModalPopup?.RemoveFromHierarchy(); m_ModalPopup = null; } static DropdownMenuAction.Status GetMenuItemState(bool isChecked) { return isChecked ? DropdownMenuAction.Status.Checked : DropdownMenuAction.Status.Normal; } void BuildContextMenu(ContextualMenuPopulateEvent evt) { var menu = evt.menu; menu.AppendAction(L10n.Tr("Hide"), (action) => displayed = false, userControlledVisibility ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled); if (collapsed) { if (container == null || container.IsOverlayLayoutSupported(supportedLayouts)) menu.AppendAction(L10n.Tr("Expand"), (action) => collapsed = false); } else menu.AppendAction(L10n.Tr("Collapse"), (action) => collapsed = true); if (!isInToolbar) { menu.AppendAction(L10n.Tr("Reset Size"), action => ResetSize()); menu.AppendSeparator(); var layouts = supportedLayouts; // Panel layout is always supported by default, we only add this option in the menu if other options are available if ((layouts & Layout.HorizontalToolbar) != 0 || (layouts & Layout.VerticalToolbar) != 0) menu.AppendAction(L10n.Tr("Panel"), action => { layout = Layout.Panel; collapsed = false; }, GetMenuItemState(layout == Layout.Panel)); if ((layouts & Layout.HorizontalToolbar) != 0) menu.AppendAction(L10n.Tr("Horizontal"), action => { layout = Layout.HorizontalToolbar; collapsed = false; }, GetMenuItemState(layout == Layout.HorizontalToolbar)); if ((layouts & Layout.VerticalToolbar) != 0) menu.AppendAction(L10n.Tr("Vertical"), action => { layout = Layout.VerticalToolbar; collapsed = false; }, GetMenuItemState(layout == Layout.VerticalToolbar)); } } internal void SetHighlightEnabled(bool highlight) { rootVisualElement.EnableInClassList(k_Highlight, highlight); } internal void Initialize(OverlayAttribute attrib) => Initialize(attrib.id, attrib.ussName, attrib.displayName, attrib.defaultSize, attrib.minSize, attrib.maxSize); internal void Initialize(string _id, string _uss, string _display, Vector2 defaultSize, Vector2 minSize, Vector2 maxSize) { m_RootVisualElementName = _uss; string name = string.IsNullOrEmpty(_display) ? m_RootVisualElementName : _display; m_Id = string.IsNullOrEmpty(_id) ? name : _id; displayName = L10n.Tr(name); rootVisualElement.style.display = DisplayStyle.None; // Taking into account the case where the user modifies the sizes in their overlay constructor. if (!float.IsNegativeInfinity(defaultSize.x) && !float.IsNegativeInfinity(defaultSize.y)) m_DefaultSize = defaultSize; if (!float.IsNegativeInfinity(minSize.x) && !float.IsNegativeInfinity(minSize.y)) m_MinSize = minSize; if (!float.IsNegativeInfinity(maxSize.x) && !float.IsNegativeInfinity(maxSize.y)) m_MaxSize = maxSize; } // marked obsolete by @karlh 2023/03/13 [Obsolete("No longer necessary, Overlay data is serialized by the OverlayCanvas.", false)] [EditorBrowsable(EditorBrowsableState.Never)] internal void ApplySaveData(SaveData data) { floatingSnapCorner = data.snapCorner; m_Floating = data.floating; m_Collapsed = data.collapsed; m_Layout = data.layout; m_FloatingSnapOffset = data.snapOffset; m_SnapOffsetDelta = data.snapOffsetDelta; m_SizeOverridden = data.sizeOverridden; m_Size = data.size; } internal void Reset(OverlayAttribute attrib) { if (attrib != null) { if (!float.IsNegativeInfinity(attrib.defaultSize.x) && !float.IsNegativeInfinity(attrib.defaultSize.y)) m_DefaultSize = attrib.defaultSize; if (!float.IsNegativeInfinity(attrib.minSize.x) && !float.IsNegativeInfinity(attrib.minSize.y)) m_MinSize = attrib.minSize; if (!float.IsNegativeInfinity(attrib.maxSize.x) && !float.IsNegativeInfinity(attrib.maxSize.y)) m_MaxSize = attrib.maxSize; m_Floating = attrib.defaultDockZone == DockZone.Floating; m_Collapsed = false; m_Layout = attrib.defaultLayout; } } } }
UnityCsReference/Editor/Mono/Overlays/Overlay.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Overlays/Overlay.cs", "repo_id": "UnityCsReference", "token_count": 14586 }
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 UnityEngine; namespace UnityEditor.Overlays { sealed class OverlayPreset : ScriptableObject, ISerializationCallbackReceiver { [SerializeField, HideInInspector] string m_RawWindowType; [SerializeField, HideInInspector] SaveData[] m_SaveData; Type m_TargetType; public Type targetWindowType { get => m_TargetType; set => m_TargetType = value; } public SaveData[] saveData { get => m_SaveData; set => m_SaveData = value; } void OnEnable() { hideFlags = HideFlags.DontSave; } public void OnBeforeSerialize() { m_RawWindowType = targetWindowType.AssemblyQualifiedName; } public void OnAfterDeserialize() { targetWindowType = Type.GetType(m_RawWindowType); } public bool CanApplyToWindow(Type windowType) { return targetWindowType != null && targetWindowType.IsAssignableFrom(windowType); } } }
UnityCsReference/Editor/Mono/Overlays/OverlayPreset.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Overlays/OverlayPreset.cs", "repo_id": "UnityCsReference", "token_count": 567 }
329
// Unity 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.Text; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Experimental.Rendering; using UnityEditor.Rendering; using UnityEditor; namespace UnityEditorInternal.FrameDebuggerInternal { internal class FrameDebuggerHelper { // Constants private const int k_ArraySizeBitMask = 0x3FF; private const int k_ShaderTypeBits = (int)ShaderType.Count; // Properties internal static bool isOnLinuxOpenGL => Application.platform == RuntimePlatform.LinuxEditor && SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLCore; internal static Material frameDebuggerMaterial { get { if (s_Material == null) s_Material = new Material(Resources.GetBuiltinResource<Material>("PerformanceTools/FrameDebuggerRenderTargetDisplay.mat")); return s_Material; } } // Utility functions... internal static bool IsAValidFrame(int curEventIndex, int descsLength) => (curEventIndex >= 0 && curEventIndex < descsLength); internal static bool IsAClearEvent(FrameEventType eventType) => eventType >= FrameEventType.ClearNone && eventType <= FrameEventType.ClearAll; internal static bool IsAResolveEvent(FrameEventType eventType) => eventType == FrameEventType.ResolveRT || eventType == FrameEventType.ResolveDepth; internal static bool IsAComputeEvent(FrameEventType eventType) => eventType == FrameEventType.ComputeDispatch; internal static bool IsARayTracingEvent(FrameEventType eventType) => eventType == FrameEventType.RayTracingDispatch; internal static bool IsAConfigureFoveatedRenderingEvent(FrameEventType eventType) => eventType == FrameEventType.ConfigureFoveatedRendering; internal static bool IsAHiddenEvent(FrameEventType eventType) => eventType == FrameEventType.BeginSubpass; internal static bool IsAHierarchyLevelBreakEvent(FrameEventType eventType) => eventType == FrameEventType.HierarchyLevelBreak; internal static bool IsCurrentEventMouseDown() => Event.current.type == EventType.MouseDown; internal static bool IsClickingRect(Rect rect) => rect.Contains(Event.current.mousePosition) && Event.current.type == EventType.MouseDown; internal static bool IsHoveringRect(Rect rect) => rect.Contains(Event.current.mousePosition); internal static bool IsARenderTexture(ref Texture t) => t != null && (t as RenderTexture) != null; internal static bool IsADepthTexture(ref Texture t) => IsARenderTexture(ref t) && ((t as RenderTexture).graphicsFormat == GraphicsFormat.None); // Private Static Variables private static Material s_Material = null; private static StringBuilder s_StringBuilder = new StringBuilder(); // Functions private struct ShaderPropertyIDs { internal const string _MSAA_2 = "_MSAA_2"; internal const string _MSAA_4 = "_MSAA_4"; internal const string _MSAA_8 = "_MSAA_8"; internal const string _TEX2DARRAY = "_TEX2DARRAY"; internal const string _CUBEMAP = "_CUBEMAP"; internal static int _Levels = Shader.PropertyToID("_Levels"); internal static int _MainTex = Shader.PropertyToID("_MainTex"); internal static int _MainTexDepth = Shader.PropertyToID("_MainTexDepth"); internal static int _Channels = Shader.PropertyToID("_Channels"); internal static int _ShouldYFlip = Shader.PropertyToID("_ShouldYFlip"); internal static int _UndoOutputSRGB = Shader.PropertyToID("_UndoOutputSRGB"); internal static int _MainTexWidth = Shader.PropertyToID("_MainTexWidth"); internal static int _MainTexHeight = Shader.PropertyToID("_MainTexHeight"); } internal static void BlitToRenderTexture( ref Texture t, ref RenderTexture output, int width, int height, int depth, Vector4 channels, Vector4 levels, bool shouldYFlip, bool undoOutputSRGB) { if (t == null || output == null) return; output.name = t.name; int msaaValue = GetMSAAValue(ref t); TextureDimension samplerType = t.dimension; SetMaterialProperties(width, height, depth, samplerType, msaaValue, channels, levels, shouldYFlip, undoOutputSRGB); frameDebuggerMaterial.SetTexture(ShaderPropertyIDs._MainTex, t); Blit(ref output); } internal static void BlitToRenderTexture( ref RenderTexture rt, ref RenderTexture output, int width, int height, Vector4 channels, Vector4 levels, bool shouldYFlip, bool undoOutputSRGB) { if (rt == null || output == null) return; output.name = rt.name; int msaaValue = GetMSAAValue(ref rt); TextureDimension samplerType = rt.dimension; SetMaterialProperties(width, height, rt.volumeDepth, samplerType, msaaValue, channels, levels, shouldYFlip, undoOutputSRGB); frameDebuggerMaterial.SetTexture(ShaderPropertyIDs._MainTex, rt); Blit(ref output); } private static void SetMaterialProperties( int width, int height, int depth, TextureDimension samplerType, int msaaValue, Vector4 channels, Vector4 levels, bool shouldYFlip, bool undoOutputSRGB) { Material mat = frameDebuggerMaterial; frameDebuggerMaterial.DisableKeyword(ShaderPropertyIDs._TEX2DARRAY); frameDebuggerMaterial.DisableKeyword(ShaderPropertyIDs._CUBEMAP); if (samplerType == TextureDimension.Tex2DArray) frameDebuggerMaterial.EnableKeyword(ShaderPropertyIDs._TEX2DARRAY); else if (samplerType == TextureDimension.CubeArray) frameDebuggerMaterial.EnableKeyword(ShaderPropertyIDs._CUBEMAP); mat.DisableKeyword(ShaderPropertyIDs._MSAA_2); mat.DisableKeyword(ShaderPropertyIDs._MSAA_4); mat.DisableKeyword(ShaderPropertyIDs._MSAA_8); if (msaaValue == 2) mat.EnableKeyword(ShaderPropertyIDs._MSAA_2); else if (msaaValue == 4) mat.EnableKeyword(ShaderPropertyIDs._MSAA_4); else if (msaaValue == 8) mat.EnableKeyword(ShaderPropertyIDs._MSAA_8); // Create the RenderTexture mat.SetFloat(ShaderPropertyIDs._MainTexWidth, width); mat.SetFloat(ShaderPropertyIDs._MainTexHeight, height); mat.SetFloat(ShaderPropertyIDs._MainTexDepth, depth); mat.SetVector(ShaderPropertyIDs._Channels, channels); mat.SetVector(ShaderPropertyIDs._Levels, levels); mat.SetFloat(ShaderPropertyIDs._ShouldYFlip, shouldYFlip ? 1.0f : 0.0f); mat.SetFloat(ShaderPropertyIDs._UndoOutputSRGB, undoOutputSRGB ? 1.0f : 0.0f); } private static void Blit(ref RenderTexture rt) { // Remember currently active render texture RenderTexture currentActiveRT = RenderTexture.active; // Blit to the Render Texture Graphics.Blit(null, rt, frameDebuggerMaterial, 0); // Restore previously active render texture RenderTexture.active = currentActiveRT; } internal static int GetVolumeDepth(ref Texture t) { RenderTexture rt = t as RenderTexture; return GetVolumeDepth(ref rt); } internal static int GetVolumeDepth(ref RenderTexture rt) { if (rt != null) return rt.volumeDepth; return 1; } internal static int GetMSAAValue(ref Texture t) { RenderTexture rt = t as RenderTexture; return GetMSAAValue(ref rt); } internal static int GetMSAAValue(ref RenderTexture rt) { if (rt != null && rt.bindTextureMS) return rt.antiAliasing; return 1; } internal static string GetFoveatedRenderingModeString(int fovMode) { switch ((FoveatedRenderingMode)fovMode) { case FoveatedRenderingMode.Disabled: return "Disabled"; default: return "Enabled"; } } internal static string GetStencilString(int stencil) { const int k_NumOfUsedStencilBits = 8; return $"(0b{Convert.ToString(stencil, 2).PadLeft(k_NumOfUsedStencilBits, '0')}) {stencil}"; } internal static string GetColorMask(uint mask) { string colorMask = String.Empty; if (mask == 0) colorMask = "0"; else { if ((mask & 8) != 0) colorMask += 'R'; if ((mask & 4) != 0) colorMask += 'G'; if ((mask & 2) != 0) colorMask += 'B'; if ((mask & 1) != 0) colorMask += 'A'; } return colorMask; } internal static string GetColorFormat(ref Texture t) { if (t == null) return string.Empty; if (t is Texture2D) return (t as Texture2D).format.ToString(); else if (t is Cubemap) return (t as Cubemap).format.ToString(); else if (t is Texture2DArray) return (t as Texture2DArray).format.ToString(); else if (t is Texture3D) return (t as Texture3D).format.ToString(); else if (t is CubemapArray) return (t as CubemapArray).format.ToString(); else if (t is RenderTexture) return (t as RenderTexture).graphicsFormat.ToString(); return string.Empty; } internal static string GetDepthStencilFormat(ref Texture t) { // Render Textures are the only ones who have this as they are split in to 2 textures... if (IsARenderTexture(ref t)) return (t as RenderTexture).depthStencilFormat.ToString(); return FrameDebuggerStyles.EventDetails.k_NotAvailable; } internal static int GetNumberOfValuesFromFlags(int flags) { return (flags >> k_ShaderTypeBits) & k_ArraySizeBitMask; } internal static string GetShaderStageString(int flags) { s_StringBuilder.Clear(); // Lowest bits of flags are set for each shader stage that property is used in; matching ShaderType C++ enum const int k_VertexShaderFlag = (1 << 1); const int k_FragmentShaderFlag = (1 << 2); const int k_GeometryShaderFlag = (1 << 3); const int k_HullShaderFlag = (1 << 4); const int k_DomainShaderFlag = (1 << 5); if ((flags & k_VertexShaderFlag) != 0) s_StringBuilder.Append("vs/"); if ((flags & k_FragmentShaderFlag) != 0) s_StringBuilder.Append("fs/"); if ((flags & k_GeometryShaderFlag) != 0) s_StringBuilder.Append("gs/"); if ((flags & k_HullShaderFlag) != 0) s_StringBuilder.Append("hs/"); if ((flags & k_DomainShaderFlag) != 0) s_StringBuilder.Append("ds/"); if (s_StringBuilder.Length == 0) return FrameDebuggerStyles.EventDetails.k_NotAvailable; s_StringBuilder.Remove(s_StringBuilder.Length - 1, 1); return s_StringBuilder.ToString(); } internal static void DestroyTexture(ref Texture t) { if (t == null) return; RenderTexture rt = t as RenderTexture; if (rt != null) DestroyTexture(ref rt); else { Texture.DestroyImmediate(t); t = null; } } internal static void DestroyTexture(ref RenderTexture rt) { if (rt == null) return; rt.Release(); RenderTexture.DestroyImmediate(rt); rt = null; } internal static void ReleaseTemporaryTexture(ref RenderTexture rt) { if (rt == null) return; RenderTexture.ReleaseTemporary(rt); rt = null; } // May look a bit silly but seems to be a pretty fast way of doing this :) // https://stackoverflow.com/a/51099524 internal static int CountDigits(int num) { if (num >= 0) { if (num < 10) return 1; if (num < 100) return 2; if (num < 1000) return 3; if (num < 10000) return 4; if (num < 100000) return 5; if (num < 1000000) return 6; if (num < 10000000) return 7; if (num < 100000000) return 8; if (num < 1000000000) return 9; return 10; } else { if (num > -10) return 2; if (num > -100) return 3; if (num > -1000) return 4; if (num > -10000) return 5; if (num > -100000) return 6; if (num > -1000000) return 7; if (num > -10000000) return 8; if (num > -100000000) return 9; return 10; } } internal static void SpliceText(ref string text, int maxWidth) { if (string.IsNullOrEmpty(text) || text.Length <= maxWidth) return; StringBuilder sb = new StringBuilder(text.Length * 2); while (text.Length > 0) { if (text.Length <= maxWidth) { sb.Append(text); break; } string chunk = text.Substring(0, maxWidth); if (char.IsWhiteSpace(text[maxWidth])) { sb.AppendLine(chunk); text = text.Substring(chunk.Length + 1); } else { int splitIndex = chunk.LastIndexOf(' '); if (splitIndex != -1) chunk = chunk.Substring(0, splitIndex); text = text.Substring(chunk.Length + (splitIndex == -1 ? 0 : 1)); sb.AppendLine(chunk); } } text = sb.ToString(); } } }
UnityCsReference/Editor/Mono/PerformanceTools/FrameDebuggerHelper.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/PerformanceTools/FrameDebuggerHelper.cs", "repo_id": "UnityCsReference", "token_count": 7236 }
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 System.Collections.Generic; using UnityEngine; using UnityEditor; using UnityEditorInternal; using System.Linq; using UnityEngine.Networking.PlayerConnection; using UnityEditor.Networking.PlayerConnection; using System.Text; namespace UnityEditor { internal class PlayerConnectionLogReceiver : ScriptableSingleton<PlayerConnectionLogReceiver> { static readonly Guid logMessageId = new Guid("394ada03-8ba0-4f26-b001-1a6cdeb05a62"); static readonly Guid cleanLogMessageId = new Guid("3ded2dda-cdf2-46d8-a3f6-01741741e7a9"); static readonly Guid logMessageIdMultiple = new Guid("5970345b-a9ef-448e-9706-aa42fb3e68e1"); static readonly Guid cleanLogMessageIdMultiple = new Guid("b86c7bd8-e37d-4b1c-9a63-72f4b5d8112d"); const string prefsKey = "PlayerConnectionLoggingState"; internal enum ConnectionState { Disconnected, CleanLog, FullLog } [SerializeField] ConnectionState state = ConnectionState.Disconnected; void OnEnable() { State = (ConnectionState)EditorPrefs.GetInt(prefsKey, (int)ConnectionState.CleanLog); } internal ConnectionState State { get { return state; } set { if (state == value) return; switch (state) { case ConnectionState.CleanLog: EditorConnection.instance.Unregister(cleanLogMessageId, LogMessage); EditorConnection.instance.Unregister(cleanLogMessageIdMultiple, LogMessageMultiple); break; case ConnectionState.FullLog: EditorConnection.instance.Unregister(logMessageId, LogMessage); EditorConnection.instance.Unregister(logMessageIdMultiple, LogMessageMultiple); break; } state = value; switch (state) { case ConnectionState.CleanLog: EditorConnection.instance.Register(cleanLogMessageId, LogMessage); EditorConnection.instance.Register(cleanLogMessageIdMultiple, LogMessageMultiple); break; case ConnectionState.FullLog: EditorConnection.instance.Register(logMessageId, LogMessage); EditorConnection.instance.Register(logMessageIdMultiple, LogMessageMultiple); break; } EditorPrefs.SetInt(prefsKey, (int)state); } } [ThreadStatic] static System.Text.StringBuilder s_LogBuilder; void LogMessage(MessageEventArgs messageEventArgs) { if (s_LogBuilder == null) s_LogBuilder = new System.Text.StringBuilder(1024); else s_LogBuilder.Clear(); var logType = (LogType)messageEventArgs.data[0]; if (!Enum.IsDefined(typeof(LogType), logType)) logType = LogType.Log; var oldStackTraceType = Application.GetStackTraceLogType(logType); // We don't want stack traces from editor code in player log messages. Application.SetStackTraceLogType(logType, StackTraceLogType.None); var name = ConnectionUIHelper.GetPlayerNameFromId(messageEventArgs.playerId); var t = ConnectionUIHelper.GetPlayerType(ProfilerDriver.GetConnectionIdentifier(messageEventArgs.playerId)); s_LogBuilder.Append("<i>"); s_LogBuilder.Append(t); s_LogBuilder.Append(" \""); s_LogBuilder.Append(name); s_LogBuilder.Append("\"</i> "); ReadOnlySpan<byte> utf8String = messageEventArgs.data.AsSpan<byte>(4); s_LogBuilder.Append(System.Text.Encoding.UTF8.GetString(utf8String)); Debug.unityLogger.Log(logType, s_LogBuilder.ToString()); Application.SetStackTraceLogType(logType, oldStackTraceType); } void LogMessageMultiple(MessageEventArgs messageEventArgs) { ReadOnlySpan<byte> payload = messageEventArgs.data.AsSpan<byte>(); var payloadLength = payload.Length; if (payloadLength <= 0) return; var name = ConnectionUIHelper.GetPlayerNameFromId(messageEventArgs.playerId); var t = ConnectionUIHelper.GetPlayerType(ProfilerDriver.GetConnectionIdentifier(messageEventArgs.playerId)); var prefix = $"<i>{t} \"{name}\"</i> "; var prefixUtf8Length = Encoding.UTF8.GetByteCount(prefix); var prefixUtf8Bytes = new byte[prefixUtf8Length]; var prefixUtf8Span = new Span<byte>(prefixUtf8Bytes); Encoding.UTF8.GetBytes(prefix, prefixUtf8Span); var messagePrefix = new UTF8StringView(prefixUtf8Span); static UTF8StringView ReadString(ReadOnlySpan<byte> payload, ref int offset) { var bytesLength = BitConverter.ToInt32(payload.Slice(offset, 4)); offset += 4; if (bytesLength == 0) return default; if (bytesLength < 0) throw new Exception("Received corrupted message"); var utf8String = payload.Slice(offset, bytesLength); offset += bytesLength; unsafe { fixed(byte* ptr = &utf8String[0]) return new UTF8StringView(ptr, bytesLength); } } static LogMessageFlags FlagsFromType(LogType type) { switch (type) { case LogType.Warning: return LogMessageFlags.DebugWarning; case LogType.Error: return LogMessageFlags.DebugError; case LogType.Assert: return LogMessageFlags.DebugAssert; case LogType.Exception: return LogMessageFlags.DebugException; } return LogMessageFlags.DebugLog; } for (var offset = 0; offset < payloadLength;) { var logType = (LogType)BitConverter.ToInt32(payload.Slice(offset, 4)); offset += 4; var message = ReadString(payload, ref offset); var timestamp = ReadString(payload, ref offset); var stacktrace = ReadString(payload, ref offset); var log = new LogEntryStruct { messagePrefix = messagePrefix, message = message, timestamp = timestamp, callstack = stacktrace, mode = FlagsFromType(logType) | LogMessageFlags.kStacktraceIsPostprocessed }; ConsoleWindow.AddMessage(ref log); Console.WriteLine(messagePrefix.ToString() + message.ToString()); } } } }
UnityCsReference/Editor/Mono/PlayerConnectionLogReceiver.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/PlayerConnectionLogReceiver.cs", "repo_id": "UnityCsReference", "token_count": 3528 }
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; using System.Collections.Generic; using UnityEditor.Build; using UnityEngine; using UnityEngine.Bindings; namespace UnityEditor { public enum tvOSSdkVersion { Device = 0, Simulator = 1 } [System.Obsolete("targetOSVersion is obsolete. Use targetOSVersionString instead.", false)] public enum tvOSTargetOSVersion { Unknown = 0, tvOS_9_0 = 900, tvOS_9_1 = 901, } // 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. public partial class PlayerSettings : UnityEngine.Object { // tvOS specific player settings [NativeHeader("Runtime/Misc/PlayerSettings.h")] [NativeHeader("Editor/Src/EditorUserBuildSettings.h")] [StaticAccessor("GetPlayerSettings()")] public partial class tvOS { private static extern int sdkVersionInt { [NativeMethod("GettvOSSdkVersion")] get; [NativeMethod("SettvOSSdkVersion")] set; } public static tvOSSdkVersion sdkVersion { get { return (tvOSSdkVersion)sdkVersionInt; } set { sdkVersionInt = (int)value; } } // tvOS bundle build number public static string buildNumber { get { return PlayerSettings.GetBuildNumber(NamedBuildTarget.tvOS.TargetName); } set { PlayerSettings.SetBuildNumber(NamedBuildTarget.tvOS.TargetName, value); } } [System.Obsolete("targetOSVersion is obsolete. Use targetOSVersionString instead.", false)] public static tvOSTargetOSVersion targetOSVersion { get { string version = targetOSVersionString; if (version == "9.0") return tvOSTargetOSVersion.tvOS_9_0; else if (version == "9.1") return tvOSTargetOSVersion.tvOS_9_1; return tvOSTargetOSVersion.Unknown; } set { string version = ""; if (value == tvOSTargetOSVersion.tvOS_9_0) version = "9.0"; else if (value == tvOSTargetOSVersion.tvOS_9_1) version = "9.1"; targetOSVersionString = version; } } [StaticAccessor("GetPlayerSettings().GetEditorOnly()", StaticAccessorType.Dot)] [NativeMethod("GettvOSMinimumVersionString")] static extern string GetMinimumVersionString(); internal static readonly Version minimumOsVersion = new Version(GetMinimumVersionString()); public static extern string targetOSVersionString { [NativeMethod("GettvOSTargetOSVersion")] get; [NativeMethod("SettvOSTargetOSVersion")] set; } [NativeProperty("tvOSSmallIconLayers", TargetType.Function)] private static extern Texture2D[] smallIconLayers { [StaticAccessor("GetPlayerSettings().GetEditorOnly()", StaticAccessorType.Dot)] get; [StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()", StaticAccessorType.Dot)] set; } internal static Texture2D[] GetSmallIconLayers() { return smallIconLayers; } internal static void SetSmallIconLayers(Texture2D[] layers) { smallIconLayers = layers; } [NativeProperty("tvOSSmallIconLayers2x", TargetType.Function)] private static extern Texture2D[] smallIconLayers2x { [StaticAccessor("GetPlayerSettings().GetEditorOnly()", StaticAccessorType.Dot)] get; [StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()", StaticAccessorType.Dot)] set; } internal static Texture2D[] GetSmallIconLayers2x() { return smallIconLayers2x; } internal static void SetSmallIconLayers2x(Texture2D[] layers) { smallIconLayers2x = layers; } [NativeProperty("tvOSLargeIconLayers", TargetType.Function)] private static extern Texture2D[] largeIconLayers { [StaticAccessor("GetPlayerSettings().GetEditorOnly()", StaticAccessorType.Dot)] get; [StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()", StaticAccessorType.Dot)] set; } internal static Texture2D[] GetLargeIconLayers() { return largeIconLayers; } internal static void SetLargeIconLayers(Texture2D[] layers) { largeIconLayers = layers; } [NativeProperty("tvOSLargeIconLayers2x", TargetType.Function)] private static extern Texture2D[] largeIconLayers2x { [StaticAccessor("GetPlayerSettings().GetEditorOnly()", StaticAccessorType.Dot)] get; [StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()", StaticAccessorType.Dot)] set; } internal static Texture2D[] GetLargeIconLayers2x() { return largeIconLayers2x; } internal static void SetLargeIconLayers2x(Texture2D[] layers) { largeIconLayers2x = layers; } [NativeProperty("tvOSTopShelfImageLayers", TargetType.Function)] private static extern Texture2D[] topShelfImageLayers { [StaticAccessor("GetPlayerSettings().GetEditorOnly()", StaticAccessorType.Dot)] get; [StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()", StaticAccessorType.Dot)] set; } internal static Texture2D[] GetTopShelfImageLayers() { return topShelfImageLayers; } internal static void SetTopShelfImageLayers(Texture2D[] layers) { topShelfImageLayers = layers; } [NativeProperty("tvOSTopShelfImageLayers2x", TargetType.Function)] private static extern Texture2D[] topShelfImageLayers2x { [StaticAccessor("GetPlayerSettings().GetEditorOnly()", StaticAccessorType.Dot)] get; [StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()", StaticAccessorType.Dot)] set; } internal static Texture2D[] GetTopShelfImageLayers2x() { return topShelfImageLayers2x; } internal static void SetTopShelfImageLayers2x(Texture2D[] layers) { topShelfImageLayers2x = layers; } [NativeProperty("tvOSTopShelfImageWideLayers", TargetType.Function)] private static extern Texture2D[] topShelfImageWideLayers { [StaticAccessor("GetPlayerSettings().GetEditorOnly()", StaticAccessorType.Dot)] get; [StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()", StaticAccessorType.Dot)] set; } internal static Texture2D[] GetTopShelfImageWideLayers() { return topShelfImageWideLayers; } internal static void SetTopShelfImageWideLayers(Texture2D[] layers) { topShelfImageWideLayers = layers; } [NativeProperty("tvOSTopShelfImageWideLayers2x", TargetType.Function)] private static extern Texture2D[] topShelfImageWideLayers2x { [StaticAccessor("GetPlayerSettings().GetEditorOnly()", StaticAccessorType.Dot)] get; [StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()", StaticAccessorType.Dot)] set; } internal static Texture2D[] GetTopShelfImageWideLayers2x() { return topShelfImageWideLayers2x; } internal static void SetTopShelfImageWideLayers2x(Texture2D[] layers) { topShelfImageWideLayers2x = layers; } [StaticAccessor("GetPlayerSettings().GetEditorOnly()", StaticAccessorType.Dot)] [NativeProperty("appleTVSplashScreen", TargetType.Field)] internal static extern Texture2D splashScreen { get; } [StaticAccessor("GetPlayerSettings().GetEditorOnly()", StaticAccessorType.Dot)] [NativeProperty("appleTVSplashScreen2x", TargetType.Field)] internal static extern Texture2D splashScreen2x { get; } // AppleTV Enable extended game controller public static extern bool requireExtendedGameController { [NativeMethod("GettvOSRequireExtendedGameController")] get; [NativeMethod("SettvOSRequireExtendedGameController")] set; } } } }
UnityCsReference/Editor/Mono/PlayerSettingsTVOS.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/PlayerSettingsTVOS.bindings.cs", "repo_id": "UnityCsReference", "token_count": 4139 }
332
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; namespace UnityEditor { [InitializeOnLoad] class PrefabInstanceChangedListener { static PrefabInstanceChangedListener() { ObjectChangeEvents.changesPublished += OnObjectChanged; } private static void OnObjectChanged(ref ObjectChangeEventStream stream) { for (int i = 0; i < stream.length; ++i) { var eventType = stream.GetEventType(i); switch (eventType) { case ObjectChangeKind.ChangeGameObjectOrComponentProperties: { stream.GetChangeGameObjectOrComponentPropertiesEvent(i, out var e); OnGameObjectChanged(TryGetGameObject(e.instanceId)); } break; case ObjectChangeKind.ChangeGameObjectParent: { stream.GetChangeGameObjectParentEvent(i, out var e); if (e.previousParentInstanceId != 0) OnGameObjectChanged(TryGetGameObject(e.previousParentInstanceId)); if (e.newParentInstanceId != 0) OnGameObjectChanged(TryGetGameObject(e.newParentInstanceId)); } break; case ObjectChangeKind.ChangeGameObjectStructure: { stream.GetChangeGameObjectStructureEvent(i, out var e); OnGameObjectChanged(TryGetGameObject(e.instanceId)); } break; case ObjectChangeKind.ChangeGameObjectStructureHierarchy: { stream.GetChangeGameObjectStructureHierarchyEvent(i, out var e); OnGameObjectChanged(TryGetGameObject(e.instanceId)); } break; case ObjectChangeKind.UpdatePrefabInstances: { stream.GetUpdatePrefabInstancesEvent(i, out var e); for (int index = 0; index < e.instanceIds.Length; index++) OnGameObjectChanged(TryGetGameObject(e.instanceIds[index])); } break; case ObjectChangeKind.CreateGameObjectHierarchy: { stream.GetCreateGameObjectHierarchyEvent(i, out var e); GameObject go = TryGetGameObject(e.instanceId); if (go != null && go.transform.parent) { go = go.transform.parent.gameObject; OnGameObjectChanged(go); } } break; case ObjectChangeKind.DestroyGameObjectHierarchy: { stream.GetDestroyGameObjectHierarchyEvent(i, out var e); GameObject goParent = TryGetGameObject(e.parentInstanceId); if (goParent != null) OnGameObjectChanged(goParent); } break; } } } private static GameObject TryGetGameObject(int instanceId) { Component comp = EditorUtility.InstanceIDToObject(instanceId) as Component; if (comp) return comp.gameObject; return EditorUtility.InstanceIDToObject(instanceId) as GameObject; } private static void OnGameObjectChanged(GameObject go) { if (!go) return; PrefabUtility.ClearPrefabInstanceNonDefaultOverridesCache(go); PrefabUtility.ClearPrefabInstanceUnusedOverridesCache(go); } } }
UnityCsReference/Editor/Mono/Prefabs/PrefabInstanceChangedListener.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Prefabs/PrefabInstanceChangedListener.cs", "repo_id": "UnityCsReference", "token_count": 2222 }
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.Collections.Generic; using UnityEditorInternal; using UnityEngine; namespace UnityEditor { internal enum CurveLibraryType { Unbounded, NormalizedZeroToOne } internal class CurvePresetsContentsForPopupWindow : PopupWindowContent { PresetLibraryEditor<CurvePresetLibrary> m_CurveLibraryEditor; PresetLibraryEditorState m_CurveLibraryEditorState; AnimationCurve m_Curve; CurveLibraryType m_CurveLibraryType; bool m_WantsToClose = false; System.Action<AnimationCurve> m_PresetSelectedCallback; public AnimationCurve curveToSaveAsPreset {get {return m_Curve; } set {m_Curve = value; }} public CurvePresetsContentsForPopupWindow(AnimationCurve animCurve, CurveLibraryType curveLibraryType, System.Action<AnimationCurve> presetSelectedCallback) { m_CurveLibraryType = curveLibraryType; m_Curve = animCurve; m_PresetSelectedCallback = presetSelectedCallback; } public static string GetBasePrefText(CurveLibraryType curveLibraryType) { return GetExtension(curveLibraryType); } public string currentPresetLibrary { get { InitIfNeeded(); return m_CurveLibraryEditor.currentLibraryWithoutExtension; } set { InitIfNeeded(); m_CurveLibraryEditor.currentLibraryWithoutExtension = value; } } static string GetExtension(CurveLibraryType curveLibraryType) { switch (curveLibraryType) { case CurveLibraryType.NormalizedZeroToOne: return PresetLibraryLocations.GetCurveLibraryExtension(true); case CurveLibraryType.Unbounded: return PresetLibraryLocations.GetCurveLibraryExtension(false); default: Debug.LogError("Enum not handled!"); return "curves"; } } public override void OnClose() { m_CurveLibraryEditorState.TransferEditorPrefsState(false); } public PresetLibraryEditor<CurvePresetLibrary> GetPresetLibraryEditor() { return m_CurveLibraryEditor; } public void InitIfNeeded() { if (m_CurveLibraryEditorState == null) { m_CurveLibraryEditorState = new PresetLibraryEditorState(GetBasePrefText(m_CurveLibraryType)); m_CurveLibraryEditorState.TransferEditorPrefsState(true); } if (m_CurveLibraryEditor == null) { var saveLoadHelper = new ScriptableObjectSaveLoadHelper<CurvePresetLibrary>(GetExtension(m_CurveLibraryType), SaveType.Text); m_CurveLibraryEditor = new PresetLibraryEditor<CurvePresetLibrary>(saveLoadHelper, m_CurveLibraryEditorState, ItemClickedCallback); m_CurveLibraryEditor.addDefaultPresets += AddDefaultPresetsToLibrary; m_CurveLibraryEditor.presetsWasReordered += OnPresetsWasReordered; m_CurveLibraryEditor.previewAspect = 4f; m_CurveLibraryEditor.minMaxPreviewHeight = new Vector2(24f, 24f); m_CurveLibraryEditor.showHeader = true; } } void OnPresetsWasReordered() { InternalEditorUtility.RepaintAllViews(); } public override void OnGUI(Rect rect) { InitIfNeeded(); m_CurveLibraryEditor.OnGUI(rect, m_Curve); if (m_WantsToClose) editorWindow.Close(); } void ItemClickedCallback(int clickCount, object presetObject) { AnimationCurve curve = presetObject as AnimationCurve; if (curve == null) Debug.LogError("Incorrect object passed " + presetObject); m_PresetSelectedCallback(curve); } public override Vector2 GetWindowSize() { return new Vector2(240, 330); } void AddDefaultPresetsToLibrary(PresetLibrary presetLibrary) { CurvePresetLibrary curveDefaultLib = presetLibrary as CurvePresetLibrary; if (curveDefaultLib == null) { Debug.Log("Incorrect preset library, should be a CurvePresetLibrary but was a " + presetLibrary.GetType()); return; } List<AnimationCurve> defaults = new List<AnimationCurve>(); defaults.Add(new AnimationCurve(CurveEditorWindow.GetConstantKeys(1f))); defaults.Add(new AnimationCurve(CurveEditorWindow.GetLinearKeys())); defaults.Add(new AnimationCurve(CurveEditorWindow.GetEaseInKeys())); defaults.Add(new AnimationCurve(CurveEditorWindow.GetEaseOutKeys())); defaults.Add(new AnimationCurve(CurveEditorWindow.GetEaseInOutKeys())); foreach (AnimationCurve preset in defaults) curveDefaultLib.Add(preset, ""); } } }
UnityCsReference/Editor/Mono/PresetLibraries/CurvePresetsContentsForPopupWindow.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/PresetLibraries/CurvePresetsContentsForPopupWindow.cs", "repo_id": "UnityCsReference", "token_count": 2359 }
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; using UnityEditor.ProjectWindowCallback; using UnityEngine; using System.Collections.Generic; using System.Linq; using System.IO; using System.Text.RegularExpressions; using UnityEditor.AssetImporters; using UnityEditor.IMGUI.Controls; using UnityEditor.PackageManager; using UnityEditor.TreeViewExamples; using UnityEditorInternal; using UnityEngine.Scripting; using Object = UnityEngine.Object; namespace UnityEditor { // The title is also used for fetching the project window tab icon: Project.png [EditorWindowTitle(title = "Project", icon = "Project")] internal class ProjectBrowser : EditorWindow, IHasCustomMenu { public const int kPackagesFolderInstanceId = int.MaxValue; public const int kAssetCreationInstanceID_ForNonExistingAssets = Int32.MaxValue - 1; private static readonly Color kFadedOutAssetsColor = new Color(1, 1, 1, 0.5f); public static Color GetAssetItemColor(int instanceID) { return (EditorUtility.isInSafeMode && !InternalEditorUtility.AssetReference.IsAssetImported(instanceID)) || AssetClipboardUtility.HasCutAsset(instanceID) ? GUI.color * kFadedOutAssetsColor : GUI.color; } private static readonly int[] k_EmptySelection = new int[0]; private bool isFolderTreeViewContextClicked = false; private const string k_WarningImmutableSelectionFormat = "The operation \"{0}\" cannot be executed because the selection or package is read-only."; private const string k_WarningRootFolderDeletionFormat = "The operation \"{0}\" cannot be executed because the selection is a root folder."; private const string k_ImmutableSelectionActionFormat = " The operation \"{0}\" is not allowed in an immutable package."; // Alive ProjectBrowsers private static List<ProjectBrowser> s_ProjectBrowsers = new List<ProjectBrowser>(); public static List<ProjectBrowser> GetAllProjectBrowsers() { return s_ProjectBrowsers; } public static ProjectBrowser s_LastInteractedProjectBrowser; internal enum ItemType { Asset, SavedFilter, } enum ViewMode { OneColumn, TwoColumns } public enum SearchViewState { NotSearching, AllAssets, InAssetsOnly, InPackagesOnly, SubFolders } // Styles used in the object selector class Styles { public GUIStyle bottomBarBg = "ProjectBrowserBottomBarBg"; public GUIStyle topBarBg = "ProjectBrowserTopBarBg"; public GUIStyle selectedPathLabel = "Label"; public GUIStyle exposablePopup = GetStyle("ExposablePopupMenu"); public GUIStyle exposablePopupItem = GetStyle("ExposablePopupItem"); public GUIStyle lockButton = "IN LockButton"; public GUIStyle separator = "ArrowNavigationRight"; public GUIContent m_FilterByLabel = EditorGUIUtility.TrIconContent("FilterByLabel", "Search by Label"); public GUIContent m_FilterByType = EditorGUIUtility.TrIconContent("FilterByType", "Search by Type"); public GUIContent m_FilterByImportLog = EditorGUIUtility.TrIconContent("d_console.erroricon.inactive.sml", "Search by Import Log Type"); public GUIContent m_CreateDropdownContent = EditorGUIUtility.IconContent("CreateAddNew"); public GUIContent m_SaveFilterContent = EditorGUIUtility.TrIconContent("Favorite", "Save search"); public GUIContent m_PackagesVisibilityContent = EditorGUIUtility.TrIconContent("SceneViewVisibility", "Number of hidden packages, click to toggle hidden packages visibility"); public GUIContent m_EmptyFolderText = EditorGUIUtility.TrTextContent("This folder is empty"); public GUIContent m_SearchIn = EditorGUIUtility.TrTextContent("Search:"); public Styles() { selectedPathLabel.alignment = TextAnchor.MiddleLeft; } static GUIStyle GetStyle(string styleName) { return styleName; // Implicit construction of GUIStyle } } static Styles s_Styles; static int s_HashForSearchField = "ProjectBrowserSearchField".GetHashCode(); // Search filter [SerializeField] SearchFilter m_SearchFilter; string m_OldSearch; bool m_SyncSearch; [NonSerialized] string m_SearchFieldText = ""; // Display state [SerializeField] ViewMode m_ViewMode = ViewMode.TwoColumns; [SerializeField] int m_StartGridSize = 16; [SerializeField] string[] m_LastFolders = new string[0]; [SerializeField] float m_LastFoldersGridSize = -1f; [SerializeField] string m_LastProjectPath; [SerializeField] EditorGUIUtility.EditorLockTracker m_LockTracker = new EditorGUIUtility.EditorLockTracker(); internal bool isLocked { get { return m_LockTracker.isLocked; } set { m_LockTracker.isLocked = value; } } bool m_EnableOldAssetTree = true; bool m_FocusSearchField; string m_SelectedPath; GUIContent m_SelectedPathContent = new GUIContent(); bool m_DidSelectSearchResult = false; bool m_ItemSelectedByRightClickThisEvent = false; bool m_InternalSelectionChange = false; // to know when selection change originated in project view itself SearchFilter.SearchArea m_LastLocalAssetsSearchArea = SearchFilter.SearchArea.InAssetsOnly; PopupList.InputData m_AssetLabels; PopupList.InputData m_ObjectTypes; PopupList.InputData m_LogTypes; bool m_UseTreeViewSelectionInsteadOfMainSelection; bool useTreeViewSelectionInsteadOfMainSelection { get {return m_UseTreeViewSelectionInsteadOfMainSelection; } set {m_UseTreeViewSelectionInsteadOfMainSelection = value; } } // Folder TreeView [SerializeField] TreeViewStateWithAssetUtility m_FolderTreeState; TreeViewController m_FolderTree; int m_TreeViewKeyboardControlID; // Full Asset TreeViewState [SerializeField] TreeViewStateWithAssetUtility m_AssetTreeState; TreeViewController m_AssetTree; // Icon/List area [SerializeField] ObjectListAreaState m_ListAreaState; // state that survives assembly reloads ObjectListArea m_ListArea; internal ObjectListArea ListArea // Exposed for usage in tests { get { return m_ListArea; } // Used for tests only; set { m_ListArea = value; } } int m_ListKeyboardControlID; bool m_GrabKeyboardFocusForListArea = false; // List area header: breadcrumbs or search area menu List<KeyValuePair<GUIContent, string>> m_BreadCrumbs = new List<KeyValuePair<GUIContent, string>>(); bool m_BreadCrumbLastFolderHasSubFolders = false; ExposablePopupMenu m_SearchAreaMenu; // Keep/Skip Hidden Packages [SerializeField] bool m_SkipHiddenPackages; // Layout const float k_MinHeight = 250; const float k_MinWidthOneColumn = 230f;// could be 205 with special handling const float k_MinWidthTwoColumns = 230f; static float k_ToolbarHeight => EditorGUI.kWindowToolbarHeight; static float k_BottomBarHeight => EditorGUI.kWindowToolbarHeight; [SerializeField] float m_DirectoriesAreaWidth = k_MinWidthTwoColumns / 2; const float k_ResizerWidth = 5f; const float k_SliderWidth = 55f; [NonSerialized] float m_SearchAreaMenuOffset = -1f; [NonSerialized] Rect m_ListAreaRect; [NonSerialized] Rect m_TreeViewRect; [NonSerialized] Rect m_BottomBarRect; [NonSerialized] Rect m_ListHeaderRect; [NonSerialized] private int m_LastFramedID = -1; // Used by search menu bar [NonSerialized] public GUIContent m_SearchAllAssets = EditorGUIUtility.TrTextContent("All"); [NonSerialized] public GUIContent m_SearchInPackagesOnly = EditorGUIUtility.TrTextContent("In Packages"); [NonSerialized] public GUIContent m_SearchInAssetsOnly = EditorGUIUtility.TrTextContent("In Assets"); [NonSerialized] public GUIContent m_SearchInFolders = new GUIContent(""); // updated when needed [NonSerialized] private string m_lastSearchFilter; [NonSerialized] private Action m_NextSearchOffDelegate; internal static float searchUpdateDelaySeconds => SearchUtils.debounceThresholdMs / 1000f; ProjectBrowser() { } /* Keep for debugging void TestProjectItemOverlayCallback (string guid, Rect selectionRect) { GUI.Label (selectionRect, GUIContent.none, EditorStyles.helpBox); }*/ void OnEnable() { titleContent = GetLocalizedTitleContent(); s_ProjectBrowsers.Add(this); EditorApplication.projectChanged += OnProjectChanged; EditorApplication.pauseStateChanged += OnPauseStateChanged; EditorApplication.playModeStateChanged += OnPlayModeStateChanged; EditorApplication.assetLabelsChanged += OnAssetLabelsChanged; EditorApplication.assetBundleNameChanged += OnAssetBundleNameChanged; AssemblyReloadEvents.afterAssemblyReload += OnAfterAssemblyReload; s_LastInteractedProjectBrowser = this; SearchService.SearchService.syncSearchChanged += OnSyncSearchChanged; // Keep for debugging //EditorApplication.projectWindowItemOnGUI += TestProjectItemOverlayCallback; } void OnAfterAssemblyReload() { // Repaint to ensure ProjectBrowser UI is initialized. This fixes the issue where a new script is created from the application menu // bar while the project browser ui was not initialized. Repaint(); } void OnDisable() { SearchService.SearchService.syncSearchChanged -= OnSyncSearchChanged; EditorApplication.pauseStateChanged -= OnPauseStateChanged; EditorApplication.playModeStateChanged -= OnPlayModeStateChanged; EditorApplication.projectChanged -= OnProjectChanged; EditorApplication.assetLabelsChanged -= OnAssetLabelsChanged; EditorApplication.assetBundleNameChanged -= OnAssetBundleNameChanged; AssemblyReloadEvents.afterAssemblyReload -= OnAfterAssemblyReload; s_ProjectBrowsers.Remove(this); } private void OnSyncSearchChanged(SearchService.SearchService.SyncSearchEvent evt, string syncViewId, string searchQuery) { if (SearchService.ProjectSearch.HasEngineOverride()) { if (evt == SearchService.SearchService.SyncSearchEvent.StartSession) { m_OldSearch = m_SearchFilter.originalText; } if (syncViewId == SearchService.ProjectSearch.GetActiveSearchEngine().GetType().FullName) { SetSearch(searchQuery); m_SyncSearch = true; } else if (m_SyncSearch) { m_SyncSearch = false; SetSearch(m_OldSearch); TopBarSearchSettingsChanged(); } if (evt == SearchService.SearchService.SyncSearchEvent.EndSession) { m_SyncSearch = false; TopBarSearchSettingsChanged(false); } } } void OnPauseStateChanged(PauseState state) { EndRenaming(); } void OnPlayModeStateChanged(PlayModeStateChange state) { EndRenaming(); } void OnAssetLabelsChanged() { if (Initialized()) // Otherwise Init will handle this { SetupAssetLabelList(); if (m_SearchFilter.IsSearching()) InitListArea(); // Ensure to refresh search results: we could have results based on previous label settings } } void OnAssetBundleNameChanged() { if (m_ListArea != null) InitListArea(); } void Awake() { if (m_ListAreaState != null) { m_ListAreaState.OnAwake(); } if (m_FolderTreeState != null) { m_FolderTreeState.OnAwake(); m_FolderTreeState.expandedIDs = new List<int>(InternalEditorUtility.expandedProjectWindowItems); } if (m_AssetTreeState != null) { m_AssetTreeState.OnAwake(); m_AssetTreeState.expandedIDs = new List<int>(InternalEditorUtility.expandedProjectWindowItems); } if (m_SearchFilter != null) { EnsureValidFolders(); } } static internal ItemType GetItemType(int instanceID) { if (SavedSearchFilters.IsSavedFilter(instanceID)) return ItemType.SavedFilter; return ItemType.Asset; } // Return the logical path that user has active. Used when you need to create new assets from outside the project browser. internal string GetActiveFolderPath() { if (m_ViewMode == ViewMode.TwoColumns && m_SearchFilter.GetState() == SearchFilter.State.FolderBrowsing && m_SearchFilter.folders.Length > 0) return m_SearchFilter.folders[0]; return "Assets"; } private bool IsInsideHiddenPackage(string path) { if (!m_SkipHiddenPackages) return false; return !PackageManagerUtilityInternal.IsPathInVisiblePackage(path); } void EnsureValidFolders() { if (m_SearchFilter == null) return; HashSet<string> validFolders = new HashSet<string>(); foreach (string folder in m_SearchFilter.folders) { if (folder == PackageManager.Folders.GetPackagesPath()) { validFolders.Add(folder); continue; } if (AssetDatabase.IsValidFolder(folder)) { if (IsInsideHiddenPackage(folder)) continue; validFolders.Add(folder); } else { // The folder does not exist (could have been deleted) now find first valid parent folder string parentFolder = folder; for (int i = 0; i < 30; ++i) { if (String.IsNullOrEmpty(parentFolder)) break; parentFolder = ProjectWindowUtil.GetContainingFolder(parentFolder); if (!String.IsNullOrEmpty(parentFolder) && AssetDatabase.IsValidFolder(parentFolder)) { if (IsInsideHiddenPackage(parentFolder)) continue; validFolders.Add(parentFolder); break; } } } } m_SearchFilter.folders = validFolders.ToArray(); } private void ResetViews() { if (m_AssetTree != null) { m_AssetTree.ReloadData(); SetSearchFoldersFromCurrentSelection(); // We could have moved, deleted or renamed a folder so ensure we get folder paths by instanceID } if (m_FolderTree != null) { m_FolderTree.ReloadData(); SetSearchFolderFromFolderTreeSelection(); // We could have moved, deleted or renamed a folder so ensure we get folders paths by instanceID } EnsureValidFolders(); if (m_ListArea != null) InitListArea(); RefreshSelectedPath(); m_BreadCrumbs.Clear(); } private void OnProjectChanged() { ResetViews(); } public bool Initialized() { return m_ListArea != null; } public void Init() { if (Initialized()) return; if (s_Styles == null) { s_Styles = new Styles(); } m_FocusSearchField = false; bool firstTimeInit = m_SearchFilter == null; if (firstTimeInit) m_DirectoriesAreaWidth = Mathf.Min(position.width / 2, 200); // m_SearchFilter is serialized if (m_SearchFilter == null) m_SearchFilter = new SearchFilter(); m_SearchFieldText = m_SearchFilter.FilterToSearchFieldString(); CalculateRects(); // setup m_TreeViewRect and m_ListAreaRect before calling InitListArea and TreeViews RefreshSelectedPath(); SetupDroplists(); // m_ListAreaState is serialized if (m_ListAreaState == null) m_ListAreaState = new ObjectListAreaState(); m_ListAreaState.m_RenameOverlay.isRenamingFilename = true; m_ListArea = new ObjectListArea(m_ListAreaState, this, false); m_ListArea.allowDeselection = true; m_ListArea.allowDragging = true; m_ListArea.allowFocusRendering = true; m_ListArea.allowMultiSelect = true; m_ListArea.allowRenaming = true; m_ListArea.allowBuiltinResources = false; m_ListArea.allowUserRenderingHook = true; m_ListArea.allowFindNextShortcut = true; m_ListArea.foldersFirst = GetShouldShowFoldersFirst(); m_ListArea.repaintCallback += Repaint; m_ListArea.itemSelectedCallback += ListAreaItemSelectedCallback; m_ListArea.keyboardCallback += ListAreaKeyboardCallback; m_ListArea.gotKeyboardFocus += ListGotKeyboardFocus; m_ListArea.drawLocalAssetHeader += DrawLocalAssetHeader; m_ListArea.gridSize = m_StartGridSize; m_StartGridSize = Mathf.Clamp(m_StartGridSize, m_ListArea.minGridSize, m_ListArea.maxGridSize); m_LastFoldersGridSize = Mathf.Min(m_LastFoldersGridSize, m_ListArea.maxGridSize); m_SearchAreaMenu = new ExposablePopupMenu(); // m_FolderTreeState is our serialized state (ensure not to reassign it if our serialization system has created it for us) if (m_FolderTreeState == null) m_FolderTreeState = new TreeViewStateWithAssetUtility(); m_FolderTreeState.renameOverlay.isRenamingFilename = true; // Full asset treeview if (m_AssetTreeState == null) m_AssetTreeState = new TreeViewStateWithAssetUtility(); m_AssetTreeState.renameOverlay.isRenamingFilename = true; InitViewMode(m_ViewMode); EnsureValidSetup(); RefreshSearchText(); SyncFilterGUI(); InitListArea(); } public void SetSearch(string searchString) { SetSearch(SearchFilter.CreateSearchFilterFromString(searchString)); } public void SetSearch(SearchFilter searchFilter) { if (!Initialized()) Init(); m_SearchFilter = searchFilter; m_SearchFieldText = searchFilter.FilterToSearchFieldString(); TopBarSearchSettingsChanged(); } internal void RefreshSearchIfFilterContains(string searchString) { if (!Initialized() || !m_SearchFilter.IsSearching()) return; if (m_SearchFieldText.IndexOf(searchString) >= 0) { InitListArea(); } } void SetSearchViewState(SearchViewState state) { switch (state) { case SearchViewState.AllAssets: m_SearchFilter.searchArea = SearchFilter.SearchArea.AllAssets; break; case SearchViewState.InAssetsOnly: m_SearchFilter.searchArea = SearchFilter.SearchArea.InAssetsOnly; break; case SearchViewState.InPackagesOnly: m_SearchFilter.searchArea = SearchFilter.SearchArea.InPackagesOnly; break; case SearchViewState.SubFolders: m_SearchFilter.searchArea = SearchFilter.SearchArea.SelectedFolders; break; case SearchViewState.NotSearching: Debug.LogError("Invalid search mode as setter"); break; } // Sync gui to state InitSearchMenu(); InitListArea(); } SearchViewState GetSearchViewState() { switch (m_SearchFilter.GetState()) { case SearchFilter.State.SearchingInAllAssets: return SearchViewState.AllAssets; case SearchFilter.State.SearchingInAssetsOnly: return SearchViewState.InAssetsOnly; case SearchFilter.State.SearchingInPackagesOnly: return SearchViewState.InPackagesOnly; case SearchFilter.State.SearchingInFolders: return SearchViewState.SubFolders; } return SearchViewState.NotSearching; } void SearchButtonClickedCallback(ExposablePopupMenu.ItemData itemClicked) { if (!itemClicked.m_On) // Behave like radio buttons: a button that is on cannot be turned off { SetSearchViewState((SearchViewState)itemClicked.m_UserData); if (m_SearchFilter.searchArea == SearchFilter.SearchArea.AllAssets || m_SearchFilter.searchArea == SearchFilter.SearchArea.InAssetsOnly || m_SearchFilter.searchArea == SearchFilter.SearchArea.InPackagesOnly || m_SearchFilter.searchArea == SearchFilter.SearchArea.SelectedFolders) m_LastLocalAssetsSearchArea = m_SearchFilter.searchArea; } } void InitSearchMenu() { SearchViewState state = GetSearchViewState(); if (state == SearchViewState.NotSearching) return; List<ExposablePopupMenu.ItemData> buttonData = new List<ExposablePopupMenu.ItemData>(); GUIStyle onStyle = s_Styles.exposablePopupItem; GUIStyle offStyle = s_Styles.exposablePopupItem; bool hasFolderSelected = m_SearchFilter.folders.Length > 0; bool on = state == SearchViewState.AllAssets; buttonData.Add(new ExposablePopupMenu.ItemData(m_SearchAllAssets, on ? onStyle : offStyle, on, true, (int)SearchViewState.AllAssets)); on = state == SearchViewState.InPackagesOnly; buttonData.Add(new ExposablePopupMenu.ItemData(m_SearchInPackagesOnly, on ? onStyle : offStyle, on, true, (int)SearchViewState.InPackagesOnly)); on = state == SearchViewState.InAssetsOnly; buttonData.Add(new ExposablePopupMenu.ItemData(m_SearchInAssetsOnly, on ? onStyle : offStyle, on, true, (int)SearchViewState.InAssetsOnly)); on = state == SearchViewState.SubFolders; buttonData.Add(new ExposablePopupMenu.ItemData(m_SearchInFolders, on ? onStyle : offStyle, on, hasFolderSelected, (int)SearchViewState.SubFolders)); GUIContent popupButtonContent = m_SearchAllAssets; switch (state) { case SearchViewState.AllAssets: popupButtonContent = m_SearchAllAssets; break; case SearchViewState.InPackagesOnly: popupButtonContent = m_SearchInPackagesOnly; break; case SearchViewState.InAssetsOnly: popupButtonContent = m_SearchInAssetsOnly; break; case SearchViewState.SubFolders: popupButtonContent = m_SearchInFolders; break; case SearchViewState.NotSearching: popupButtonContent = m_SearchInAssetsOnly; break; default: Debug.LogError("Unhandled enum"); break; } ExposablePopupMenu.PopupButtonData popListData = new ExposablePopupMenu.PopupButtonData(popupButtonContent, s_Styles.exposablePopup); m_SearchAreaMenu.Init(buttonData, 10f, 450f, popListData, SearchButtonClickedCallback); } void RefreshSearchText() { if (m_SearchFilter.folders.Length > 0) { string[] baseFolders = ProjectWindowUtil.GetBaseFolders(m_SearchFilter.folders); string folderText = ""; string toolTip = ""; int maxShow = 3; for (int i = 0; i < baseFolders.Length && i < maxShow; ++i) { var baseFolder = baseFolders[i]; var packageInfo = PackageManager.PackageInfo.FindForAssetPath(baseFolder); if (packageInfo != null && !string.IsNullOrEmpty(packageInfo.displayName)) baseFolder = Regex.Replace(baseFolder, @"^" + packageInfo.assetPath, PackageManager.Folders.GetPackagesPath() + "/" + packageInfo.displayName); if (i > 0) folderText += ", "; string folderName = Path.GetFileName(baseFolder); folderText += "'" + folderName + "'"; if (i == 0 && folderName != "Assets" && folderName != PackageManager.Folders.GetPackagesPath()) toolTip = baseFolder; } if (baseFolders.Length > maxShow) folderText += " +"; m_SearchInFolders.text = folderText; m_SearchInFolders.tooltip = toolTip; } else { m_SearchInFolders.text = "Selected folder"; m_SearchInFolders.tooltip = ""; } m_BreadCrumbs.Clear(); InitSearchMenu(); } void EnsureValidSetup() { if (m_LastProjectPath != Directory.GetCurrentDirectory()) { // Clear project specific serialized state m_SearchFilter = new SearchFilter(); m_LastFolders = new string[0]; SyncFilterGUI(); // If we have a selection try to frame it (could be a non asset object) if (Selection.activeInstanceID != 0) FrameObjectPrivate(Selection.activeInstanceID, !m_LockTracker.isLocked, false); // If we did not frame anything above ensure to show Assets folder in two column mode if (m_ViewMode == ViewMode.TwoColumns && !IsShowingFolderContents()) SelectAssetsFolder(); m_LastProjectPath = Directory.GetCurrentDirectory(); } // In two column do not allow empty search filter, at least show the Assets folders if (m_ViewMode == ViewMode.TwoColumns && m_SearchFilter.GetState() == SearchFilter.State.EmptySearchFilter) { SelectAssetsFolder(); } } void OnGUIAssetCallback(int instanceID, Rect rect) { // User hook for rendering stuff on top of assets if (EditorApplication.projectWindowItemOnGUI != null) { string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(instanceID)); EditorApplication.projectWindowItemOnGUI(guid, rect); } if (EditorApplication.projectWindowItemInstanceOnGUI != null) { EditorApplication.projectWindowItemInstanceOnGUI(instanceID, rect); } } private void InitOneColumnView() { m_AssetTree = new TreeViewController(this, m_AssetTreeState); m_AssetTree.deselectOnUnhandledMouseDown = true; m_AssetTree.selectionChangedCallback += AssetTreeSelectionCallback; m_AssetTree.keyboardInputCallback += AssetTreeKeyboardInputCallback; m_AssetTree.contextClickItemCallback += AssetTreeViewContextClick; m_AssetTree.contextClickOutsideItemsCallback += AssetTreeViewContextClickOutsideItems; m_AssetTree.itemDoubleClickedCallback += AssetTreeItemDoubleClickedCallback; m_AssetTree.onGUIRowCallback += OnGUIAssetCallback; m_AssetTree.dragEndedCallback += AssetTreeDragEnded; var data = new AssetsTreeViewDataSource(m_AssetTree, m_SkipHiddenPackages); data.foldersFirst = GetShouldShowFoldersFirst(); m_AssetTree.Init(m_TreeViewRect, data, new AssetsTreeViewGUI(m_AssetTree), new AssetsTreeViewDragging(m_AssetTree) ); m_AssetTree.ReloadData(); } private void InitTwoColumnView() { m_FolderTree = new TreeViewController(this, m_FolderTreeState); m_FolderTree.deselectOnUnhandledMouseDown = false; m_FolderTree.selectionChangedCallback += FolderTreeSelectionCallback; m_FolderTree.contextClickItemCallback += FolderTreeViewContextClick; m_FolderTree.onGUIRowCallback += OnGUIAssetCallback; m_FolderTree.dragEndedCallback += FolderTreeDragEnded; m_FolderTree.Init(m_TreeViewRect, new ProjectBrowserColumnOneTreeViewDataSource(m_FolderTree, m_SkipHiddenPackages), new ProjectBrowserColumnOneTreeViewGUI(m_FolderTree), new ProjectBrowserColumnOneTreeViewDragging(m_FolderTree) ); m_FolderTree.ReloadData(); } void InitViewMode(ViewMode viewMode) { m_ViewMode = viewMode; // Reset m_FolderTree = null; m_AssetTree = null; useTreeViewSelectionInsteadOfMainSelection = false; switch (m_ViewMode) { case ViewMode.OneColumn: InitOneColumnView(); break; case ViewMode.TwoColumns: InitTwoColumnView(); break; } float minWidth = (m_ViewMode == ViewMode.OneColumn) ? k_MinWidthOneColumn : k_MinWidthTwoColumns; //if (position.width < minWidth) // Debug.LogError ("ProjectBrowser: Ensure that mode cannot be changed resulting in an invalid min width: " + minWidth + " (cur width " + position.width + ")"); minSize = new Vector2(minWidth, k_MinHeight); maxSize = new Vector2(10000, 10000); } private bool GetShouldShowFoldersFirst() { return Application.platform != RuntimePlatform.OSXEditor; } // Called when user changes view mode void SetViewMode(ViewMode newViewMode) { if (m_ViewMode == newViewMode) return; EndRenaming(); InitViewMode(m_ViewMode == ViewMode.OneColumn ? ViewMode.TwoColumns : ViewMode.OneColumn); // Ensure same selection is framed in new view mode if (Selection.activeInstanceID != 0) FrameObjectPrivate(Selection.activeInstanceID, !m_LockTracker.isLocked, false); RepaintImmediately(); } public void EndRenaming() { if (m_AssetTree != null) m_AssetTree.EndNameEditing(true); if (m_FolderTree != null) m_FolderTree.EndNameEditing(true); if (m_ListArea != null) m_ListArea.EndRename(true); } Dictionary<string, string[]> GetTypesDisplayNames() { return new Dictionary<string, string[]> { { "Animation Clip", new [] { "AnimationClip" } }, { "Audio Clip", new [] { "AudioClip"} }, { "Audio Mixer", new [] { "AudioMixer" } }, { "Compute Shader", new [] { "ComputeShader" } }, { "Font", new [] { "Font" } }, { "GUI Skin", new [] { "GUISkin" } }, { "Graph", new [] { "GraphAsset", "VisualEffectAsset", "ScriptGraphAsset" } }, { "Material", new [] { "Material" } }, { "Mesh", new [] { "Mesh" } }, { "Model", new [] { "Model" } }, { "Physics Material", new [] { "PhysicsMaterial" } }, { "Prefab", new [] { "Prefab" } }, { "Scene", new [] { "Scene"} }, { "Script", new [] { "Script" } }, { "Shader", new [] { "Shader" } }, { "Sprite", new [] { "Sprite" } }, { "Texture", new [] { "Texture" } }, { "Video Clip", new [] { "VideoClip" } }, { "Visual Effect Asset", new [] { "VisualEffectAsset", "VisualEffectSubgraph" } }, // "Texture2D", // "RenderTexture", // "Cubemap", // "MovieTexture", }; } public void TypeListCallback(PopupList.ListElement element) { if (!Event.current.control) { // Clear all selection except for clicked element foreach (var item in m_ObjectTypes.m_ListElements) if (item != element) item.selected = false; } // Toggle clicked element element.selected = !element.selected; string[] selectedDisplayNames = m_ObjectTypes.m_ListElements.Where(x => x.selected).SelectMany(x => x.types).ToArray(); m_SearchFilter.classNames = selectedDisplayNames; m_SearchFieldText = m_SearchFilter.FilterToSearchFieldString(); TopBarSearchSettingsChanged(); Repaint(); } public void AssetLabelListCallback(PopupList.ListElement element) { if (!Event.current.control) { // Clear all selection except for clicked element foreach (var item in m_AssetLabels.m_ListElements) if (item != element) item.selected = false; } // Toggle clicked element element.selected = !element.selected; m_SearchFilter.assetLabels = (from item in m_AssetLabels.m_ListElements where item.selected select item.text).ToArray(); m_SearchFieldText = m_SearchFilter.FilterToSearchFieldString(); TopBarSearchSettingsChanged(); Repaint(); } public void LogTypeListCallback(PopupList.ListElement element) { if (!Event.current.control) { // Clear all selection except for clicked element foreach (var item in m_LogTypes.m_ListElements) if (item != element) item.selected = false; } // Toggle clicked element element.selected = !element.selected; m_SearchFilter.importLogFlags = element.selected ? (UnityEditor.AssetImporters.ImportLogFlags) Enum.Parse(typeof(UnityEditor.AssetImporters.ImportLogFlags), element.types.First()) : ImportLogFlags.None; m_SearchFieldText = m_SearchFilter.FilterToSearchFieldString(); TopBarSearchSettingsChanged(); Repaint(); } void SetupDroplists() { SetupAssetLabelList(); SetupLogTypeList(); // Types m_ObjectTypes = new PopupList.InputData(); m_ObjectTypes.m_CloseOnSelection = false; m_ObjectTypes.m_AllowCustom = false; m_ObjectTypes.m_OnSelectCallback = TypeListCallback; m_ObjectTypes.m_SortAlphabetically = false; m_ObjectTypes.m_MaxCount = 0; var types = GetTypesDisplayNames(); foreach (var keyPair in types) { m_ObjectTypes.AddElement(keyPair.Key, keyPair.Value); } m_ObjectTypes.m_ListElements[0].selected = true; } void SetupAssetLabelList() { // List of predefined asset labels (and in the future also user defined ones) Dictionary<string, float> tags = AssetDatabase.GetAllLabels(); // AssetLabels m_AssetLabels = new PopupList.InputData(); m_AssetLabels.m_CloseOnSelection = false; m_AssetLabels.m_AllowCustom = true; m_AssetLabels.m_OnSelectCallback = AssetLabelListCallback; m_AssetLabels.m_MaxCount = 15; m_AssetLabels.m_SortAlphabetically = true; foreach (var pair in tags) { PopupList.ListElement element = m_AssetLabels.NewOrMatchingElement(pair.Key); if (element.filterScore < pair.Value) element.filterScore = pair.Value; } } void SetupLogTypeList() { m_LogTypes = new PopupList.InputData(); m_LogTypes.m_CloseOnSelection = false; m_LogTypes.m_AllowCustom = false; m_LogTypes.m_OnSelectCallback = LogTypeListCallback; m_LogTypes.m_MaxCount = 2; m_LogTypes.m_SortAlphabetically = true; m_LogTypes.AddElement("Warnings", new string[]{"Warning"}); m_LogTypes.AddElement("Errors", new string[]{"Error"}); } void SyncFilterGUI() { // Sync Labels List<string> assetLabels = new List<string>(m_SearchFilter.assetLabels); foreach (PopupList.ListElement item in m_AssetLabels.m_ListElements) item.selected = assetLabels.Contains(item.text); // Sync Type List<string> classNames = new List<string>(m_SearchFilter.classNames); foreach (PopupList.ListElement item in m_ObjectTypes.m_ListElements) item.selected = classNames.Contains(item.text); // Sync Text field m_SearchFieldText = m_SearchFilter.FilterToSearchFieldString(); } void ShowFolderContents(int folderInstanceID, bool revealAndFrameInFolderTree) { if (m_ViewMode != ViewMode.TwoColumns) Debug.LogError("ShowFolderContents should only be called in two column mode"); if (folderInstanceID == 0) return; string folderPath = AssetDatabase.GetAssetPath(folderInstanceID); if (folderInstanceID == kPackagesFolderInstanceId) folderPath = PackageManager.Folders.GetPackagesPath(); if (!m_SkipHiddenPackages || PackageManagerUtilityInternal.IsPathInVisiblePackage(folderPath)) { m_SearchFilter.ClearSearch(); m_SearchFilter.folders = new[] {folderPath}; m_SearchFilter.skipHidden = m_SkipHiddenPackages; m_FolderTree.SetSelection(new[] {folderInstanceID}, revealAndFrameInFolderTree); FolderTreeSelectionChanged(true); } } bool IsShowingFolderContents() { return m_SearchFilter.folders.Length > 0; } void ListGotKeyboardFocus() { } void ListAreaKeyboardCallback() { if (Event.current.type == EventType.KeyDown) { switch (Event.current.keyCode) { case KeyCode.Return: case KeyCode.KeypadEnter: if (Application.platform == RuntimePlatform.OSXEditor) { if (m_ListArea.BeginRename(0f)) Event.current.Use(); } else // WindowsEditor { Event.current.Use(); OpenListAreaSelection(); } break; case KeyCode.DownArrow: if (Application.platform == RuntimePlatform.OSXEditor && Event.current.command) { Event.current.Use(); OpenListAreaSelection(); } break; case KeyCode.UpArrow: if (Application.platform == RuntimePlatform.OSXEditor && Event.current.command && m_ViewMode == ViewMode.TwoColumns) { ShowParentFolderOfCurrentlySelected(); Event.current.Use(); } break; case KeyCode.Backspace: if (Application.platform != RuntimePlatform.OSXEditor && m_ViewMode == ViewMode.TwoColumns) { ShowParentFolderOfCurrentlySelected(); Event.current.Use(); } break; case KeyCode.F2: if (Application.platform != RuntimePlatform.OSXEditor) { if (m_ListArea.BeginRename(0f)) Event.current.Use(); } break; } } } void ShowParentFolderOfCurrentlySelected() { if (IsShowingFolderContents()) { int[] selectedFolderInstanceIDs = m_FolderTree.GetSelection(); if (selectedFolderInstanceIDs.Length == 1) { TreeViewItem item = m_FolderTree.FindItem(selectedFolderInstanceIDs[0]); if (item != null && item.parent != null && item.id != AssetDatabase.GetMainAssetOrInProgressProxyInstanceID("Assets")) { SetFolderSelection(new[] {item.parent.id}, true); m_ListArea.Frame(item.id, true, false); Selection.activeInstanceID = item.id; } } } } void OpenListAreaSelection() { int[] selectedInstanceIDs = m_ListArea.GetSelection(); int selectionCount = selectedInstanceIDs.Length; if (selectionCount > 0) { int numFolders = 0; foreach (int instanceID in selectedInstanceIDs) if (ProjectWindowUtil.IsFolder(instanceID)) numFolders++; bool allFolders = numFolders == selectionCount; if (allFolders) { OpenSelectedFolders(); GUIUtility.ExitGUI(); // Exit because if we are mouse clicking to open we are in the middle of iterating list area items.. } else { // If any assets in selection open them instead of opening folder OpenAssetSelection(selectedInstanceIDs); Repaint(); GUIUtility.ExitGUI(); // Exit because if we are mouse clicking to open we are in the middle of iterating list area items.. } } } static void OpenAssetSelection(int[] selectedInstanceIDs) { foreach (int id in selectedInstanceIDs) { if (AssetDatabase.Contains(id)) AssetDatabase.OpenAsset(id); } GUIUtility.ExitGUI(); } void SetAsLastInteractedProjectBrowser() { s_LastInteractedProjectBrowser = this; } void RefreshSelectedPath() { if (Selection.activeObject != null) { m_SelectedPath = AssetDatabase.GetAssetPath(Selection.activeObject); if (!string.IsNullOrEmpty(m_SelectedPath) && IsInsideHiddenPackage(m_SelectedPath)) { m_SelectedPath = string.Empty; Selection.activeObject = null; } } else { m_SelectedPath = string.Empty; } if (!string.IsNullOrEmpty(m_SelectedPath)) { m_SelectedPathContent = new GUIContent(m_SelectedPath, AssetDatabase.GetCachedIcon(m_SelectedPath)) { tooltip = m_SelectedPath }; } else { m_SelectedPathContent = new GUIContent(); } } static void OpenSelectedFolders() { ProjectBrowser projectBrowser = s_LastInteractedProjectBrowser; if (projectBrowser != null) { int[] selectedInstanceIDs = projectBrowser.m_ListArea?.GetSelection(); if (selectedInstanceIDs == null || selectedInstanceIDs.Length == 0) return; projectBrowser.EndPing(); if (projectBrowser.m_ViewMode == ViewMode.TwoColumns) { projectBrowser.SetFolderSelection(selectedInstanceIDs, false); } else if (projectBrowser.m_ViewMode == ViewMode.OneColumn) { projectBrowser.ClearSearch(); // shows tree instead of search projectBrowser.m_AssetTree.Frame(selectedInstanceIDs[0], true, false); projectBrowser.m_AssetTree.data.SetExpanded(selectedInstanceIDs[0], true); } projectBrowser.Repaint(); } } // Called from EditorHelper [RequiredByNativeCode] static void OpenSelectedFoldersInInternalExplorer() { if (!IsFolderTreeViewContextClick()) { OpenSelectedFolders(); } } // Also called from list when navigating by keys void ListAreaItemSelectedCallback(bool doubleClicked) { SetAsLastInteractedProjectBrowser(); int[] instanceIDs = m_ListArea.GetSelection(); if (instanceIDs.Length > 0) { Selection.instanceIDs = instanceIDs; m_SearchFilter.searchArea = m_LastLocalAssetsSearchArea; // local asset was selected m_InternalSelectionChange = true; } else { Selection.activeObject = null; } if (Selection.instanceIDs != m_ListArea.GetSelection()) { m_ListArea.InitSelection(Selection.instanceIDs); } m_FocusSearchField = false; if (Event.current.button == 1 && Event.current.type == EventType.MouseDown) m_ItemSelectedByRightClickThisEvent = true; RefreshSelectedPath(); m_DidSelectSearchResult = m_SearchFilter.IsSearching(); if (doubleClicked) OpenListAreaSelection(); } void OnGotFocus() { } void OnLostFocus() { isFolderTreeViewContextClicked = false; // Added because this window uses RenameOverlay EndRenaming(); } bool CanFrameAsset(int instanceID) { var path = AssetDatabase.GetAssetPath(instanceID); if (string.IsNullOrEmpty(path)) return false; HierarchyProperty h = new HierarchyProperty(HierarchyType.Assets, false); if (h.Find(instanceID, null)) return true; var packageInfo = PackageManager.PackageInfo.FindForAssetPath(path); if (packageInfo != null) { h = new HierarchyProperty(packageInfo.assetPath, false); if (h.Find(instanceID, null)) return true; } return false; } void OnSelectionChange() { // We do not want to init our UI on OnSelectionChange because EditorStyles might not be allocated yet (at play/stop) if (m_ListArea == null) return; // Keep for debugging //Debug.Log ("OnSelectionChange (ProjectBrowser): " + DebugUtils.ListToString(new List<int>(Selection.instanceIDs))); // The list area selection state is based on the main selection (both in search mode and folderbrowsing) m_ListArea.InitSelection(Selection.instanceIDs); int instanceID = Selection.instanceIDs.Length > 0 ? Selection.instanceIDs[Selection.instanceIDs.Length - 1] : 0; if (m_ViewMode == ViewMode.OneColumn) { // If searching we are not showing the asset tree but we set selection anyways to ensure its // setup when clearing search bool revealSelectionAndFrameLast = !m_LockTracker.isLocked && CanFrameAsset(instanceID) && Selection.instanceIDs.Length <= 1; m_AssetTree.SetSelection(Selection.instanceIDs, revealSelectionAndFrameLast); } else if (m_ViewMode == ViewMode.TwoColumns) { if (!m_InternalSelectionChange) { bool frame = !m_LockTracker.isLocked && Selection.instanceIDs.Length > 0 && CanFrameAsset(instanceID); if (frame) { // If searching we keep the search when framing. If folder browsing we change folder // and frame current selection in its folder if (m_SearchFilter.IsSearching()) { m_ListArea.Frame(instanceID, true, false); } else { FrameObjectInTwoColumnMode(instanceID, true, false); } } } } m_InternalSelectionChange = false; RefreshSelectedPath(); Repaint(); } void SetFoldersInSearchFilter(int[] selectedInstanceIDs) { m_SearchFilter.folders = GetFolderPathsFromInstanceIDs(selectedInstanceIDs); EnsureValidFolders(); if (selectedInstanceIDs.Length > 0) { if (m_LastFoldersGridSize > 0) m_ListArea.gridSize = (int)m_LastFoldersGridSize; } } internal void SetFolderSelection(int[] selectedInstanceIDs, bool revealSelectionAndFrameLastSelected) { SetFolderSelection(selectedInstanceIDs, revealSelectionAndFrameLastSelected, true); } private void SetFolderSelection(int[] selectedInstanceIDs, bool revealSelectionAndFrameLastSelected, bool folderWasSelected) { m_FolderTree.SetSelection(selectedInstanceIDs, revealSelectionAndFrameLastSelected); SetFoldersInSearchFilter(selectedInstanceIDs); FolderTreeSelectionChanged(folderWasSelected); } void AssetTreeItemDoubleClickedCallback(int instanceID) { OpenAssetSelection(Selection.instanceIDs); } void AssetTreeKeyboardInputCallback() { if (Event.current.type == EventType.KeyDown) { switch (Event.current.keyCode) { case KeyCode.Return: case KeyCode.KeypadEnter: if (Application.platform == RuntimePlatform.WindowsEditor) { Event.current.Use(); OpenAssetSelection(Selection.instanceIDs); } break; case KeyCode.DownArrow: if (Application.platform == RuntimePlatform.OSXEditor && Event.current.command) { Event.current.Use(); OpenAssetSelection(Selection.instanceIDs); } break; } } } void AssetTreeSelectionCallback(int[] selectedTreeViewInstanceIDs) { SetAsLastInteractedProjectBrowser(); if (selectedTreeViewInstanceIDs.Length > 0) Selection.SetSelectionWithActiveInstanceID(selectedTreeViewInstanceIDs, selectedTreeViewInstanceIDs[0]); else Selection.activeInstanceID = 0; // The selection could be cancelled if an Inspector with hasUnsavedChanges is opened. // In that case, let's update the tree so the highlight is set back to the actual selection. if(Selection.instanceIDs != selectedTreeViewInstanceIDs) m_AssetTree.SetSelection(Selection.instanceIDs, true); RefreshSelectedPath(); SetSearchFoldersFromCurrentSelection(); RefreshSearchText(); } void SetSearchFoldersFromCurrentSelection() { HashSet<string> folders = new HashSet<string>(); foreach (int instanceID in Selection.instanceIDs) { if (instanceID == kPackagesFolderInstanceId) { folders.Add(PackageManager.Folders.GetPackagesPath()); continue; } if (!AssetDatabase.Contains(instanceID)) continue; string path = AssetDatabase.GetAssetPath(instanceID); if (AssetDatabase.IsValidFolder(path)) { if (IsInsideHiddenPackage(path)) continue; folders.Add(path); } else { // Add containing folder of the selected asset string folderPath = ProjectWindowUtil.GetContainingFolder(path); if (!String.IsNullOrEmpty(folderPath)) { if (IsInsideHiddenPackage(folderPath)) continue; folders.Add(folderPath); } } } // Set them as folders in search filter (so search in folder works correctly) m_SearchFilter.folders = ProjectWindowUtil.GetBaseFolders(folders.ToArray()); // Keep for debugging // Debug.Log ("Search folders: " + DebugUtils.ListToString(new List<string>(m_SearchFilter.folders))); } void SetSearchFolderFromFolderTreeSelection() { if (m_FolderTree == null) return; m_SearchFilter.folders = GetFolderPathsFromInstanceIDs(m_FolderTree.GetSelection()); if (m_SearchFilter.folders.Length != 0) return; //If we fail to find the folder path from the selected ID then probably the selection could be from Favorites. //At any point of time there can only be one selection from Favorites.. //The Favorites have a custom InstanceID(starting from 1000000000) different from Assets and are saved in a cache, //Since we cant get the path from the AssetsUtility with these InstanceIDs we need to get them from cache. if (m_FolderTree.GetSelection().Length == 1) { int selectionID = m_FolderTree.GetSelection()[0]; ItemType type = GetItemType(selectionID); if (type == ItemType.SavedFilter) { SearchFilter filter = SavedSearchFilters.GetFilter(selectionID); // Check if the filter is valid (the root of filters are not an actual filter) if (ValidateFilter(selectionID, filter)) { m_SearchFilter = filter; } } } } void FolderTreeSelectionCallback(int[] selectedTreeViewInstanceIDs) { SetAsLastInteractedProjectBrowser(); // Assumes only asset folders can be multi selected int firstTreeViewInstanceID = 0; if (selectedTreeViewInstanceIDs.Length > 0) firstTreeViewInstanceID = selectedTreeViewInstanceIDs[0]; bool folderWasSelected = false; if (firstTreeViewInstanceID != 0) { ItemType type = GetItemType(firstTreeViewInstanceID); if (type == ItemType.Asset) { SetFoldersInSearchFilter(selectedTreeViewInstanceIDs); folderWasSelected = true; } if (type == ItemType.SavedFilter) { SearchFilter filter = SavedSearchFilters.GetFilter(firstTreeViewInstanceID); // Check if the filter is valid (the root of filters are not an actual filter) if (ValidateFilter(firstTreeViewInstanceID, filter)) { m_SearchFilter = filter; EnsureValidFolders(); float previewSize = filter.GetState() == SearchFilter.State.FolderBrowsing ? m_LastFoldersGridSize : SavedSearchFilters.GetPreviewSize(firstTreeViewInstanceID); if (previewSize > 0f) m_ListArea.gridSize = Mathf.Clamp((int)previewSize, m_ListArea.minGridSize, m_ListArea.maxGridSize); SyncFilterGUI(); } } } FolderTreeSelectionChanged(folderWasSelected); } bool ValidateFilter(int savedFilterID, SearchFilter filter) { if (filter == null) return false; // Folder validation SearchFilter.State state = filter.GetState(); if (state == SearchFilter.State.FolderBrowsing || state == SearchFilter.State.SearchingInFolders) { foreach (string folderPath in filter.folders) { int instanceID = AssetDatabase.GetMainAssetOrInProgressProxyInstanceID(folderPath); if (instanceID == 0) { if (EditorUtility.DisplayDialog("Folder not found", "The folder '" + folderPath + "' might have been deleted or belong to another project. Do you want to delete the favorite?", "Delete", "Cancel")) { SavedSearchFilters.RemoveSavedFilter(savedFilterID); GUIUtility.ExitGUI(); // exit gui since we are iterating items we just reloaded } return false; } } } return true; } void ShowAndHideFolderTreeSelectionAsNeeded() { if (m_ViewMode == ViewMode.TwoColumns && m_FolderTree != null) { bool isSavedFilterSelected = false; int[] selection = m_FolderTree.GetSelection(); if (selection.Length > 0) { isSavedFilterSelected = GetItemType(selection[0]) == ItemType.SavedFilter; } SearchViewState state = GetSearchViewState(); switch (state) { case SearchViewState.AllAssets: case SearchViewState.InAssetsOnly: case SearchViewState.InPackagesOnly: case SearchViewState.SubFolders: case SearchViewState.NotSearching: { if (!isSavedFilterSelected) m_FolderTree.SetSelection(GetFolderInstanceIDs(m_SearchFilter.folders), true); } break; } } } // This method is being used by the EditorTests/Searching tests public string[] GetCurrentVisibleNames() { return m_ListArea.GetCurrentVisibleNames(); } void InitListArea() { ShowAndHideFolderTreeSelectionAsNeeded(); m_SearchFilter.skipHidden = m_SkipHiddenPackages; m_ListArea.InitForSearch(m_ListAreaRect, HierarchyType.Assets, m_SearchFilter, false, s => AssetDatabase.GetMainAssetInstanceID(s)); m_ListArea.InitSelection(Selection.instanceIDs); } void OnInspectorUpdate() { if (m_ListArea != null) m_ListArea.OnInspectorUpdate(); } void OnDestroy() { if (m_ListArea != null) m_ListArea.OnDestroy(); if (this == s_LastInteractedProjectBrowser) s_LastInteractedProjectBrowser = null; } static void DeleteFilter(int filterInstanceID) { if (SavedSearchFilters.GetRootInstanceID() == filterInstanceID) { string title = "Cannot Delete"; EditorUtility.DisplayDialog(title, "Deleting the 'Filters' root is not allowed", "Ok"); } else { string title = "Delete selected favorite?"; if (EditorUtility.DisplayDialog(title, "You cannot undo this action.", "Delete", "Cancel")) { SavedSearchFilters.RemoveSavedFilter(filterInstanceID); } } } [UsedByNativeCode] internal static string GetSelectedPath() { if (s_LastInteractedProjectBrowser == null) return string.Empty; return s_LastInteractedProjectBrowser.m_SelectedPath; } // Also called from C++ (used for AssetsMenu check if selection is Packages folder) [UsedByNativeCode] internal static bool SelectionIsPackagesRootFolder() { var pb = s_LastInteractedProjectBrowser; if (pb == null) return false; if (pb.m_ViewMode == ViewMode.OneColumn && pb.m_AssetTree != null && pb.m_AssetTree.IsSelected(kPackagesFolderInstanceId)) { return true; } if (pb.m_ViewMode == ViewMode.TwoColumns && (pb.useTreeViewSelectionInsteadOfMainSelection || Selection.activeInstanceID == 0) && pb.m_FolderTree != null && pb.m_FolderTree.IsSelected(kPackagesFolderInstanceId)) { return true; } return Selection.activeInstanceID == kPackagesFolderInstanceId; } private static bool ShouldDiscardCommandsEventsForImmutablePackages() { var evt = Event.current; if ((evt.type == EventType.ExecuteCommand || evt.type == EventType.ValidateCommand || evt.keyCode == KeyCode.Escape) && (evt.commandName == EventCommandNames.Cut || evt.commandName == EventCommandNames.Paste || evt.commandName == EventCommandNames.Delete || evt.commandName == EventCommandNames.SoftDelete || evt.commandName == EventCommandNames.Duplicate)) { if (AssetsMenuUtility.SelectionHasImmutable()) return true; if (SelectionIsPackagesRootFolder()) return true; } return false; } private static bool ShouldDiscardCommandsEventsForRootFolders() { return ((Event.current.type == EventType.ExecuteCommand || Event.current.type == EventType.ValidateCommand) && Event.current.commandName == EventCommandNames.Delete || Event.current.commandName == EventCommandNames.SoftDelete) && !CanDeleteSelectedAssets(); } void HandleCommandEventsForTreeView() { // Handle all event for tree view var evt = Event.current; EventType eventType = evt.type; if (eventType == EventType.ExecuteCommand || eventType == EventType.ValidateCommand) { bool execute = eventType == EventType.ExecuteCommand; int[] instanceIDs = m_FolderTree.GetSelection(); if (instanceIDs.Length == 0) return; // Only one type can be selected at a time (and savedfilters can only be single-selected) ItemType itemType = GetItemType(instanceIDs[0]); // Check if event made on immutable package if (itemType == ItemType.Asset) { if (ShouldDiscardCommandsEventsForImmutablePackages()) { EditorUtility.DisplayDialog(L10n.Tr("Invalid Operation"), L10n.Tr(string.Format(k_ImmutableSelectionActionFormat, Event.current.commandName)), L10n.Tr("Ok")); return; } if (ShouldDiscardCommandsEventsForRootFolders()) { EditorUtility.DisplayDialog(L10n.Tr("Invalid Operation"), L10n.Tr("Deleting a root folder is not allowed."), L10n.Tr("Ok")); return; } } if (evt.commandName == EventCommandNames.Delete || evt.commandName == EventCommandNames.SoftDelete) { evt.Use(); if (execute) { if (itemType == ItemType.SavedFilter) { System.Diagnostics.Debug.Assert(instanceIDs.Length == 1); //We do not support multiselection for filters DeleteFilter(instanceIDs[0]); GUIUtility.ExitGUI(); // exit gui since we are iterating items we just reloaded } else if (itemType == ItemType.Asset) { bool askIfSure = Event.current.commandName == EventCommandNames.SoftDelete; DeleteSelectedAssets(askIfSure); if (askIfSure) Focus(); // Workaround that we do not get focus back when dialog is closed } } GUIUtility.ExitGUI(); } else if (evt.commandName == EventCommandNames.Duplicate) { if (execute) { if (itemType == ItemType.SavedFilter) { // TODO copy filter (get new name as assets) } else if (itemType == ItemType.Asset) { evt.Use(); int[] copiedFolders = AssetClipboardUtility.DuplicateFolders(instanceIDs); SetFolderSelection(copiedFolders, true); GUIUtility.ExitGUI(); } } else { evt.Use(); } } else if (evt.commandName == EventCommandNames.Cut) { evt.Use(); if (execute && itemType == ItemType.Asset) { AssetClipboardUtility.CutCopySelectedFolders(instanceIDs, AssetClipboardUtility.PerformedAction.Cut); GUIUtility.ExitGUI(); } } else if (evt.commandName == EventCommandNames.Copy) { evt.Use(); if (execute && itemType == ItemType.Asset) { AssetClipboardUtility.CutCopySelectedFolders(instanceIDs, AssetClipboardUtility.PerformedAction.Copy); GUIUtility.ExitGUI(); } } else if (evt.commandName == EventCommandNames.Paste) { evt.Use(); if (execute && itemType == ItemType.Asset && AssetClipboardUtility.CanPaste()) { int[] copiedFolders = AssetClipboardUtility.PasteFolders(); SetFolderSelection(copiedFolders, true); GUIUtility.ExitGUI(); } } else if (evt.keyCode == KeyCode.Escape) { evt.Use(); AssetClipboardUtility.CancelCut(); GUIUtility.ExitGUI(); } } } public const string FocusProjectWindowCommand = "FocusProjectWindow"; void HandleCommandEvents() { // Check if event made on immutable package if (ShouldDiscardCommandsEventsForImmutablePackages()) { Debug.LogFormat(LogType.Warning, LogOption.NoStacktrace, null, k_WarningImmutableSelectionFormat, Event.current.commandName); return; } // Check if event is delete on root folder if (ShouldDiscardCommandsEventsForRootFolders()) { Debug.LogFormat(LogType.Warning, LogOption.NoStacktrace, null, k_WarningRootFolderDeletionFormat, Event.current.commandName); return; } var evt = Event.current; EventType eventType = evt.type; if (eventType == EventType.ExecuteCommand || eventType == EventType.ValidateCommand || evt.keyCode == KeyCode.Escape) { bool execute = eventType == EventType.ExecuteCommand; if (evt.commandName == EventCommandNames.Delete || evt.commandName == EventCommandNames.SoftDelete) { evt.Use(); if (execute) { bool askIfSure = evt.commandName == EventCommandNames.SoftDelete; DeleteSelectedAssets(askIfSure); if (askIfSure) Focus(); // Workaround that we do not get focus back when dialog is closed } GUIUtility.ExitGUI(); } else if (evt.commandName == EventCommandNames.Duplicate) { if (execute) { evt.Use(); AssetClipboardUtility.DuplicateSelectedAssets(); GUIUtility.ExitGUI(); } else { Object[] selectedAssets = Selection.GetFiltered(typeof(Object), SelectionMode.Assets); if (selectedAssets.Length != 0) evt.Use(); } } else if (evt.commandName == EventCommandNames.Cut) { evt.Use(); AssetClipboardUtility.CutCopySelectedAssets(AssetClipboardUtility.PerformedAction.Cut); Repaint(); } else if (evt.commandName == EventCommandNames.Copy) { evt.Use(); AssetClipboardUtility.CutCopySelectedAssets(AssetClipboardUtility.PerformedAction.Copy); } else if (evt.commandName == EventCommandNames.Paste) { evt.Use(); if (execute) AssetClipboardUtility.PasteSelectedAssets(m_ViewMode == ViewMode.TwoColumns); } else if (evt.keyCode == KeyCode.Escape) { AssetClipboardUtility.CancelCut(); Repaint(); GUIUtility.ExitGUI(); } else if (evt.commandName == FocusProjectWindowCommand) { if (execute) { FrameObjectPrivate(Selection.activeInstanceID, true, false); evt.Use(); Focus(); GUIUtility.ExitGUI(); } else { evt.Use(); } } else if (evt.commandName == EventCommandNames.SelectAll) { if (execute) SelectAll(); evt.Use(); } // Frame selected assets else if (evt.commandName == EventCommandNames.FrameSelected) { if (execute) { FrameObjectPrivate(Selection.activeInstanceID, true, false); evt.Use(); GUIUtility.ExitGUI(); } evt.Use(); } else if (evt.commandName == EventCommandNames.Find) { if (execute) m_FocusSearchField = true; evt.Use(); } } } void SelectAll() { if (m_ViewMode == ViewMode.OneColumn) { if (m_SearchFilter.IsSearching()) { m_ListArea.SelectAll(); } else { int[] instanceIDs = m_AssetTree.GetRowIDs(); m_AssetTree.SetSelection(instanceIDs, false); AssetTreeSelectionCallback(instanceIDs); } } else if (m_ViewMode == ViewMode.TwoColumns) { m_ListArea.SelectAll(); } else { Debug.LogError("Missing implementation for ViewMode " + m_ViewMode); } } float GetListHeaderHeight() { if (!m_SearchFilter.IsSearching()) return k_ToolbarHeight; return m_SearchFilter.GetState() == SearchFilter.State.EmptySearchFilter ? 0f : k_ToolbarHeight; } void CalculateRects() { float listHeaderHeight = GetListHeaderHeight(); if (m_ViewMode == ViewMode.OneColumn) { m_ListAreaRect = new Rect(0, EditorGUI.kWindowToolbarHeight + listHeaderHeight, position.width, position.height - k_ToolbarHeight - listHeaderHeight - k_BottomBarHeight); m_TreeViewRect = new Rect(0, EditorGUI.kWindowToolbarHeight, position.width, position.height - k_ToolbarHeight - k_BottomBarHeight); m_BottomBarRect = new Rect(0, position.height - k_BottomBarHeight, position.width, k_BottomBarHeight); m_ListHeaderRect = new Rect(0, EditorGUI.kWindowToolbarHeight, position.width, listHeaderHeight); } else //if (m_ViewMode == ViewMode.TwoColumns) { float listWidth = position.width - m_DirectoriesAreaWidth; m_ListAreaRect = new Rect(m_DirectoriesAreaWidth, EditorGUI.kWindowToolbarHeight + listHeaderHeight, listWidth, position.height - k_ToolbarHeight - listHeaderHeight - k_BottomBarHeight); m_TreeViewRect = new Rect(0, EditorGUI.kWindowToolbarHeight, m_DirectoriesAreaWidth, position.height - k_ToolbarHeight); m_BottomBarRect = new Rect(m_DirectoriesAreaWidth, position.height - k_BottomBarHeight, listWidth, k_BottomBarHeight); m_ListHeaderRect = new Rect(m_ListAreaRect.x, EditorGUI.kWindowToolbarHeight, m_ListAreaRect.width, listHeaderHeight); } } void EndPing() { if (m_ViewMode == ViewMode.OneColumn) { m_AssetTree.EndPing(); } else { m_FolderTree.EndPing(); m_ListArea.EndPing(); } } void OnEvent() { // Let components handle new event if (m_AssetTree != null) m_AssetTree.OnEvent(); if (m_FolderTree != null) m_FolderTree.OnEvent(); if (m_ListArea != null) m_ListArea.OnEvent(); } void OnGUI() { // Initialize m_Styles if (s_Styles == null) s_Styles = new Styles(); if (!Initialized()) Init(); // We grab keyboard control ids early to ensure consistency (for focus rendering) m_ListKeyboardControlID = GUIUtility.GetControlID(FocusType.Keyboard); m_TreeViewKeyboardControlID = GUIUtility.GetControlID(FocusType.Keyboard); OnEvent(); m_ItemSelectedByRightClickThisEvent = false; // Size splitterRects for different areas of the browser ResizeHandling(position.height - k_ToolbarHeight); CalculateRects(); Event evt = Event.current; Rect ProjectBrowserRect = new Rect(0, 0, position.width, position.height); if (evt.type == EventType.MouseDown && ProjectBrowserRect.Contains(evt.mousePosition)) { EndPing(); SetAsLastInteractedProjectBrowser(); } if (m_GrabKeyboardFocusForListArea) { m_GrabKeyboardFocusForListArea = false; GUIUtility.keyboardControl = m_ListKeyboardControlID; } GUI.BeginGroup(ProjectBrowserRect, GUIContent.none); TopToolbar(); BottomBar(); if (m_ViewMode == ViewMode.OneColumn) { if (m_SearchFilter.IsSearching()) { SearchAreaBar(); if (GUIUtility.keyboardControl == m_TreeViewKeyboardControlID) GUIUtility.keyboardControl = m_ListKeyboardControlID; // AssetTree is not shown so we can steal keyboard control m_ListArea.OnGUI(m_ListAreaRect, m_ListKeyboardControlID); } else { if (GUIUtility.keyboardControl == m_ListKeyboardControlID) GUIUtility.keyboardControl = m_TreeViewKeyboardControlID; // List is not shown so we can steal keyboard control m_AssetTree.OnGUI(m_TreeViewRect, m_TreeViewKeyboardControlID); } } else // ViewMode.TwoColumns { if (m_SearchFilter.IsSearching()) SearchAreaBar(); else BreadCrumbBar(); // Folders m_FolderTree.OnGUI(m_TreeViewRect, m_TreeViewKeyboardControlID); // List Content m_ListArea.OnGUI(m_ListAreaRect, m_ListKeyboardControlID); // Vertical splitter line between folders and content (drawn before listarea so listarea ping is drawn on top of line) EditorGUIUtility.DrawHorizontalSplitter(new Rect(m_ListAreaRect.x + 1f, EditorGUI.kWindowToolbarHeight, 1, m_TreeViewRect.height)); if (m_SearchFilter.GetState() == SearchFilter.State.FolderBrowsing && m_ListArea.numItemsDisplayed == 0) { Vector2 size = EditorStyles.label.CalcSize(s_Styles.m_EmptyFolderText); Rect textRect = new Rect(m_ListAreaRect.x + 2f + Mathf.Max(0, (m_ListAreaRect.width - size.x) * 0.5f), m_ListAreaRect.y + 10f, size.x, 20f); using (new EditorGUI.DisabledScope(true)) { GUI.Label(textRect, s_Styles.m_EmptyFolderText, EditorStyles.label); } } } // Handle ListArea context click after ListArea.OnGUI HandleContextClickInListArea(m_ListAreaRect); // Ensure we save current grid size if (m_ListArea.gridSize != m_StartGridSize) { m_StartGridSize = m_ListArea.gridSize; if (m_SearchFilter.GetState() == SearchFilter.State.FolderBrowsing) m_LastFoldersGridSize = m_ListArea.gridSize; } GUI.EndGroup(); if (m_ViewMode == ViewMode.TwoColumns) useTreeViewSelectionInsteadOfMainSelection = GUIUtility.keyboardControl == m_TreeViewKeyboardControlID; // Handle command events AFTER tree and list view since commands events should be handled by text fields first (rename overlay + search field) // Let folder/filters tree view try to handle command events first if it has keyboard focus if (m_ViewMode == ViewMode.TwoColumns && GUIUtility.keyboardControl == m_TreeViewKeyboardControlID) HandleCommandEventsForTreeView(); HandleCommandEvents(); } void HandleContextClickInListArea(Rect listRect) { Event evt = Event.current; switch (evt.type) { case EventType.MouseDown: // This section handles selecting the folders showing their content, if right clicked outside items. // We do this to ensure our assets context menu is operating on the active folder(s) if (m_ViewMode == ViewMode.TwoColumns && m_SearchFilter.GetState() == SearchFilter.State.FolderBrowsing && evt.button == 1 && !m_ItemSelectedByRightClickThisEvent) { if (m_SearchFilter.folders.Length > 0 && listRect.Contains(evt.mousePosition)) { m_InternalSelectionChange = true; Selection.instanceIDs = GetFolderInstanceIDs(m_SearchFilter.folders); } } break; case EventType.ContextClick: if (listRect.Contains(evt.mousePosition)) { GUIUtility.hotControl = 0; // In safe mode non-scripts assets aren't selectable and therefore if you context click a non-script // asset, then a context menu shouldn't be displayed. if (!EditorUtility.isInSafeMode || Selection.instanceIDs.Length > 0) { // Context click in list area EditorUtility.DisplayPopupMenu(new Rect(evt.mousePosition.x, evt.mousePosition.y, 0, 0), "Assets/", null); } evt.Use(); } break; } } void AssetTreeViewContextClick(int clickedItemID) { Event evt = Event.current; if (clickedItemID == 0) { // For non selectable assets, don't show context menu. Selection is deselected m_AssetTree.SetSelection(k_EmptySelection, false); AssetTreeSelectionCallback(k_EmptySelection); } else { // Context click with a selected Asset EditorUtility.DisplayPopupMenu(new Rect(evt.mousePosition.x, evt.mousePosition.y, 0, 0), "Assets/", null); } evt.Use(); } void AssetTreeViewContextClickOutsideItems() { Event evt = Event.current; // Deselect all if (m_AssetTree.GetSelection().Length > 0) { m_AssetTree.SetSelection(k_EmptySelection, false); AssetTreeSelectionCallback(k_EmptySelection); } // Context click with no selected assets EditorUtility.DisplayPopupMenu(new Rect(evt.mousePosition.x, evt.mousePosition.y, 0, 0), "Assets/", null); evt.Use(); } void FolderTreeViewContextClick(int clickedItemID) { isFolderTreeViewContextClicked = true; Event evt = Event.current; System.Diagnostics.Debug.Assert(evt.type == EventType.ContextClick); if (SavedSearchFilters.IsSavedFilter(clickedItemID)) { // Context click with a selected Filter if (clickedItemID != SavedSearchFilters.GetRootInstanceID()) SavedFiltersContextMenu.Show(clickedItemID); } else { // Context click on a folder (asset) EditorUtility.DisplayPopupMenu(new Rect(evt.mousePosition.x, evt.mousePosition.y, 0, 0), "Assets/", null); } evt.Use(); } static bool IsFolderTreeViewContextClick() { ProjectBrowser projectBrowser = s_LastInteractedProjectBrowser; if (projectBrowser == null) { return true; // return true to ignore Context menu's 'Open' option in folder tree in the ProjectBrowser } else if (projectBrowser.isFolderTreeViewContextClicked) { projectBrowser.isFolderTreeViewContextClicked = false; return true; } else { return false; } } void AssetTreeDragEnded(int[] draggedInstanceIds, bool draggedItemsFromOwnTreeView) { // We only change selection if 'draggedItemsFromOwnTreeView' == true. // This ensures that we do not override the selection that might have been set before // calling this callback when dragging e.g a gameobject to the projectbrowser (case 628939) if (draggedInstanceIds != null && draggedItemsFromOwnTreeView) { m_AssetTree.SetSelection(draggedInstanceIds, true); m_AssetTree.NotifyListenersThatSelectionChanged(); // behave as if selection was performed in treeview Repaint(); GUIUtility.ExitGUI(); } } void FolderTreeDragEnded(int[] draggedInstanceIds, bool draggedItemsFromOwnTreeView) { // In the folder tree we do not want to change selection as we do in the full asset tree when dragging is performed. // We do not want to change folder when dragging assets to folders (convention of both OSX and Win) } // This is our search field void TopToolbar() { GUILayout.BeginHorizontal(EditorStyles.toolbar); { float listWidth = position.width - m_DirectoriesAreaWidth; float spaceBetween = 4f; bool compactMode = listWidth < 500; // We need quite some space for filtering text if (!compactMode) { spaceBetween = 10f; } CreateDropdown(); GUILayout.FlexibleSpace(); GUILayout.Space(spaceBetween * 2f); SearchField(); TypeDropDown(); AssetLabelsDropDown(); LogTypeDropDown(); if (m_ViewMode == ViewMode.TwoColumns) { ButtonSaveFilter(); } ToggleHiddenPackagesVisibility(); } GUILayout.EndHorizontal(); } void SetOneColumn() { SetViewMode(ViewMode.OneColumn); EnsureValidSetup(); } void SetTwoColumns() { SetViewMode(ViewMode.TwoColumns); EnsureValidSetup(); } internal bool IsTwoColumns() { return m_ViewMode == ViewMode.TwoColumns; } void OpenTreeViewTestWindow() { GetWindow<TreeViewTestWindow>(); } void ToggleExpansionAnimationPreference() { bool oldValue = EditorPrefs.GetBool(TreeViewController.kExpansionAnimationPrefKey, false); EditorPrefs.SetBool(TreeViewController.kExpansionAnimationPrefKey, !oldValue); EditorUtility.RequestScriptReload(); } public virtual void AddItemsToMenu(GenericMenu menu) { if (m_EnableOldAssetTree) { GUIContent assetTreeText = EditorGUIUtility.TrTextContent("One Column Layout"); GUIContent assetBrowserText = EditorGUIUtility.TrTextContent("Two Column Layout"); menu.AddItem(assetTreeText, m_ViewMode == ViewMode.OneColumn, SetOneColumn); if (position.width >= k_MinWidthTwoColumns) menu.AddItem(assetBrowserText, m_ViewMode == ViewMode.TwoColumns, SetTwoColumns); else menu.AddDisabledItem(assetBrowserText); m_LockTracker.AddItemsToMenu(menu); if (Unsupported.IsDeveloperMode()) { menu.AddItem(EditorGUIUtility.TrTextContent("DEVELOPER/Open TreeView Test Window..."), false, OpenTreeViewTestWindow); menu.AddItem(EditorGUIUtility.TrTextContent("DEVELOPER/Use TreeView Expansion Animation"), EditorPrefs.GetBool(TreeViewController.kExpansionAnimationPrefKey, false), ToggleExpansionAnimationPreference); } } } float DrawLocalAssetHeader(Rect r) { return 0; } void ResizeHandling(float height) { if (m_ViewMode == ViewMode.OneColumn) return; // Handle folders vs. items splitter const float minDirectoriesAreaWidth = 50f; const float minAssetsAreaWidth = 50f; Rect dragRect = new Rect(m_DirectoriesAreaWidth, EditorGUI.kWindowToolbarHeight, k_ResizerWidth, height); dragRect = EditorGUIUtility.HandleHorizontalSplitter(dragRect, position.width, minDirectoriesAreaWidth, minAssetsAreaWidth); m_DirectoriesAreaWidth = dragRect.x; } void ButtonSaveFilter() { // Only show when we have a active filter using (new EditorGUI.DisabledScope(!m_SearchFilter.IsSearching())) { if (GUILayout.Button(s_Styles.m_SaveFilterContent, EditorStyles.toolbarButtonRight)) { ProjectBrowserColumnOneTreeViewGUI ProjectBrowserTreeViewGUI = m_FolderTree.gui as ProjectBrowserColumnOneTreeViewGUI; if (ProjectBrowserTreeViewGUI != null) { bool createNewFilter = true; // If a filter is selected save to that filter int[] treeViewSelection = m_FolderTree.GetSelection(); if (treeViewSelection.Length == 1) { int instanceID = treeViewSelection[0]; bool isRootFilter = SavedSearchFilters.GetRootInstanceID() == instanceID; // Ask if filter should be overwritten if (SavedSearchFilters.IsSavedFilter(instanceID) && !isRootFilter) { createNewFilter = false; string title = "Overwrite Filter?"; string text = "Do you want to overwrite '" + SavedSearchFilters.GetName(instanceID) + "' or create a new filter?"; int result = 2; // cancel result = EditorUtility.DisplayDialogComplex(title, text, "Overwrite", "Create", "Cancel"); if (result == 0) SavedSearchFilters.UpdateExistingSavedFilter(instanceID, m_SearchFilter, listAreaGridSize); else if (result == 1) createNewFilter = true; } } // Otherwise create new item in tree if (createNewFilter) { // User wants to create new filter. We re-focus to ensure rename overlay gets input (dialog stole our focus and we might not get it back) Focus(); ProjectBrowserTreeViewGUI.BeginCreateSavedFilter(m_SearchFilter); } } } } } void CreateDropdown() { var isInReadOnlyContext = AssetsMenuUtility.SelectionHasImmutable() || SelectionIsPackagesRootFolder() || !ModeService.HasCapability(ModeCapability.AllowAssetCreation, true); EditorGUI.BeginDisabledGroup(isInReadOnlyContext); Rect r = GUILayoutUtility.GetRect(s_Styles.m_CreateDropdownContent, EditorStyles.toolbarCreateAddNewDropDown); if (EditorGUI.DropdownButton(r, s_Styles.m_CreateDropdownContent, FocusType.Passive, EditorStyles.toolbarCreateAddNewDropDown)) { GUIUtility.hotControl = 0; EditorUtility.DisplayPopupMenu(r, "Assets/Create", null); } EditorGUI.EndDisabledGroup(); } void AssetLabelsDropDown() { // Labels button Rect r = GUILayoutUtility.GetRect(s_Styles.m_FilterByLabel, EditorStyles.toolbarButton); if (EditorGUI.DropdownButton(r, s_Styles.m_FilterByLabel, FocusType.Passive, EditorStyles.toolbarButton)) { PopupWindow.Show(r, new PopupList(m_AssetLabels)); } } void TypeDropDown() { // Object type button Rect r = GUILayoutUtility.GetRect(s_Styles.m_FilterByType, EditorStyles.toolbarButton); if (EditorGUI.DropdownButton(r, s_Styles.m_FilterByType, FocusType.Passive, EditorStyles.toolbarButton)) { PopupWindow.Show(r, new PopupList(m_ObjectTypes)); } } void LogTypeDropDown() { //Log type button Rect r = GUILayoutUtility.GetRect(s_Styles.m_FilterByImportLog, EditorStyles.toolbarButton); if (EditorGUI.DropdownButton(r, s_Styles.m_FilterByImportLog, FocusType.Passive, EditorStyles.toolbarButton)) { PopupWindow.Show(r, new PopupList(m_LogTypes)); } } private void ToggleHiddenPackagesVisibility() { s_Styles.m_PackagesVisibilityContent.text = PackageManagerUtilityInternal.HiddenPackagesCount.ToString(); var skipHiddenPackage = GUILayout.Toggle(m_SkipHiddenPackages, s_Styles.m_PackagesVisibilityContent, EditorStyles.toolbarButtonRight); if (skipHiddenPackage != m_SkipHiddenPackages) { m_SkipHiddenPackages = skipHiddenPackage; EndRenaming(); if (m_AssetTree != null) { var dataSource = m_AssetTree.data as AssetsTreeViewDataSource; dataSource.skipHiddenPackages = m_SkipHiddenPackages; } if (m_FolderTree != null) { var dataSource = m_FolderTree.data as ProjectBrowserColumnOneTreeViewDataSource; dataSource.skipHiddenPackages = m_SkipHiddenPackages; } ResetViews(); } } void SearchField() { Rect rect = GUILayoutUtility.GetRect(0, EditorGUILayout.kLabelFloatMaxW * 1.5f, EditorGUI.kSingleLineHeight, EditorGUI.kSingleLineHeight, EditorStyles.toolbarSearchFieldWithJump, GUILayout.MinWidth(65), GUILayout.MaxWidth(300)); int searchFieldControlID = EditorGUIUtility.GetControlID(s_HashForSearchField, FocusType.Passive, rect); // We use 'Passive' to ensure we only tab between folder tree and list area. Focus search field by using Ctrl+F. if (m_FocusSearchField) { GUIUtility.keyboardControl = searchFieldControlID; EditorGUIUtility.editingTextField = true; if (Event.current.type == EventType.Repaint) m_FocusSearchField = false; } Event evt = Event.current; if (GUIUtility.keyboardControl == searchFieldControlID) { // On arrow down/up switch to control selection in list area if (evt.type == EventType.KeyDown && (evt.keyCode == KeyCode.DownArrow || evt.keyCode == KeyCode.UpArrow)) { if (!m_ListArea.IsLastClickedItemVisible()) m_ListArea.SelectFirst(); GUIUtility.keyboardControl = m_ListKeyboardControlID; evt.Use(); } SearchService.SearchService.HandleSearchEvent(this, evt, m_SearchFieldText); } m_lastSearchFilter = EditorGUI.ToolbarSearchField( searchFieldControlID, rect, m_SearchFieldText, m_SyncSearch ? EditorStyles.toolbarSearchFieldWithJumpSynced : EditorStyles.toolbarSearchFieldWithJump, string.IsNullOrEmpty(m_SearchFieldText) ? EditorStyles.toolbarSearchFieldCancelButtonWithJumpEmpty : EditorStyles.toolbarSearchFieldCancelButtonWithJump); if (m_lastSearchFilter != m_SearchFieldText || m_FocusSearchField) { // Update filter with string m_SearchFieldText = m_lastSearchFilter; m_NextSearchOffDelegate?.Invoke(); m_NextSearchOffDelegate = EditorApplication.CallDelayed(UpdateSearchDelayed, searchUpdateDelaySeconds); } SearchService.SearchService.DrawOpenSearchButton(this, m_SearchFieldText); } void UpdateSearchDelayed() { m_SearchFilter.SearchFieldStringToFilter(m_SearchFieldText); SyncFilterGUI(); TopBarSearchSettingsChanged(); Repaint(); } void TopBarSearchSettingsChanged(bool keyboardValidation = true) { if (!m_SearchFilter.IsSearching()) { if (m_DidSelectSearchResult) { m_DidSelectSearchResult = false; FrameObjectPrivate(Selection.activeInstanceID, true, false); if (GUIUtility.keyboardControl == 0 && keyboardValidation) { // Ensure item has focus for visual feedback and instant key navigation if (m_ViewMode == ViewMode.OneColumn) GUIUtility.keyboardControl = m_TreeViewKeyboardControlID; else if (m_ViewMode == ViewMode.TwoColumns) GUIUtility.keyboardControl = m_ListKeyboardControlID; } } else if (m_ViewMode == ViewMode.TwoColumns) { // Revert to last selected folders if (GUIUtility.keyboardControl == 0 || !keyboardValidation || SelectionIsFavorite()) { RevertToLastSelectedFolder(false); } } } else { if (m_ViewMode == ViewMode.TwoColumns && SelectionIsFavorite()) RevertToLastSelectedFolder(false); InitSearchMenu(); } InitListArea(); } internal static int GetFolderInstanceID(string folderPath) { return folderPath == PackageManager.Folders.GetPackagesPath() ? kPackagesFolderInstanceId : AssetDatabase.GetMainAssetOrInProgressProxyInstanceID(folderPath); } static int[] GetFolderInstanceIDs(string[] folders) { int[] folderInstanceIDs = new int[folders.Length]; for (int i = 0; i < folders.Length; ++i) { folderInstanceIDs[i] = GetFolderInstanceID(folders[i]); } return folderInstanceIDs; } static string[] GetFolderPathsFromInstanceIDs(int[] instanceIDs) { List<string> paths = new List<string>(); foreach (int instanceID in instanceIDs) { if (instanceID == kPackagesFolderInstanceId) { paths.Add(PackageManager.Folders.GetPackagesPath()); continue; } string path = AssetDatabase.GetAssetPath(instanceID); if (!String.IsNullOrEmpty(path)) paths.Add(path); } return paths.ToArray(); } void ClearSearch() { m_SearchFilter.ClearSearch(); m_SearchFilter.skipHidden = m_SkipHiddenPackages; // Clear GUI m_SearchFieldText = ""; m_AssetLabels.DeselectAll(); m_ObjectTypes.DeselectAll(); m_DidSelectSearchResult = false; } void FolderTreeSelectionChanged(bool folderWasSelected) { if (folderWasSelected) { SearchViewState state = GetSearchViewState(); if (state == SearchViewState.AllAssets || state == SearchViewState.InAssetsOnly || state == SearchViewState.InPackagesOnly) { // Clear all except folders if folder is set string[] folders = m_SearchFilter.folders; ClearSearch(); m_SearchFilter.folders = folders; // Ensures that when selecting folders we start local asset search next time we search m_SearchFilter.searchArea = m_LastLocalAssetsSearchArea; } m_LastFolders = m_SearchFilter.folders; } // End any rename that might be in progress. EndRenaming(); RefreshSearchText(); InitListArea(); } void IconSizeSlider(Rect r) { // Slider EditorGUI.BeginChangeCheck(); int newGridSize = (int)GUI.HorizontalSlider(r, m_ListArea.gridSize, m_ListArea.minGridSize, m_ListArea.maxGridSize); if (EditorGUI.EndChangeCheck()) { m_ListArea.gridSize = newGridSize; } } void SearchAreaBar() { // Background GUI.Label(m_ListHeaderRect, GUIContent.none, s_Styles.topBarBg); const float kMargin = 5f; Rect rect = m_ListHeaderRect; rect.x += kMargin; rect.height -= 1; rect.width -= 2 * kMargin; GUIStyle style = EditorStyles.boldLabel; GUI.Label(rect, s_Styles.m_SearchIn, style); if (m_SearchAreaMenuOffset < 0f) m_SearchAreaMenuOffset = style.CalcSize(s_Styles.m_SearchIn).x; rect.x += m_SearchAreaMenuOffset + 7f; rect.width -= m_SearchAreaMenuOffset + 7f; rect.width = m_SearchAreaMenu.OnGUI(rect); } void BreadCrumbBar() { if (m_ListHeaderRect.height <= 0f) return; if (m_SearchFilter.folders.Length == 0) return; Event evt = Event.current; // Give keyboard focus to list area if we mouse down in breadcrumbs if (evt.type == EventType.MouseDown && m_ListHeaderRect.Contains(evt.mousePosition)) { GUIUtility.keyboardControl = m_ListKeyboardControlID; Repaint(); } if (m_BreadCrumbs.Count == 0) { var path = m_SearchFilter.folders[0]; if (IsInsideHiddenPackage(path)) { m_BreadCrumbLastFolderHasSubFolders = false; } else { var folderNames = new List<string>(); var folderDisplayNames = new List<string>(); var packagesMountPoint = PackageManager.Folders.GetPackagesPath(); var packageInfo = PackageManager.PackageInfo.FindForAssetPath(path); if (packageInfo != null) { // Packages root folderNames.Add(packagesMountPoint); folderDisplayNames.Add(packagesMountPoint); // Package name/displayname folderNames.Add(packageInfo.name); folderDisplayNames.Add(string.IsNullOrEmpty(packageInfo.displayName) ? packageInfo.name : packageInfo.displayName); // Rest of the path; if (path != packageInfo.assetPath) { var subpaths = Regex.Replace(path, @"^" + packageInfo.assetPath + "/", "").Split('/'); folderNames.AddRange(subpaths); folderDisplayNames.AddRange(subpaths); } } else { folderNames.AddRange(path.Split('/')); folderDisplayNames = folderNames; } var folderPath = ""; var i = 0; foreach (var folderName in folderNames) { if (!string.IsNullOrEmpty(folderPath)) folderPath += "/"; folderPath += folderName; m_BreadCrumbs.Add(new KeyValuePair<GUIContent, string>(new GUIContent(folderDisplayNames[i++]), folderPath)); } if (path == packagesMountPoint) { m_BreadCrumbLastFolderHasSubFolders = PackageManagerUtilityInternal.GetAllVisiblePackages(m_SkipHiddenPackages).Length > 0; } } } // Background GUI.Label(m_ListHeaderRect, GUIContent.none, s_Styles.topBarBg); // Folders Rect rect = m_ListHeaderRect; rect.y += s_Styles.topBarBg.padding.top; rect.x += s_Styles.topBarBg.padding.left; if (m_SearchFilter.folders.Length == 1) { for (int i = 0; i < m_BreadCrumbs.Count; ++i) { bool lastElement = i == m_BreadCrumbs.Count - 1; GUIStyle style = lastElement ? EditorStyles.boldLabel : EditorStyles.label; //EditorStyles.miniBoldLabel : EditorStyles.miniLabel;// GUIContent folderContent = m_BreadCrumbs[i].Key; string folderPath = m_BreadCrumbs[i].Value; Vector2 size = style.CalcSize(folderContent); rect.width = size.x; if (GUI.Button(rect, folderContent, style)) { ShowFolderContents(GetFolderInstanceID(folderPath), false); } rect.x += size.x; if (!lastElement || m_BreadCrumbLastFolderHasSubFolders) { Rect buttonRect = new Rect(rect.x, rect.y + (rect.height - s_Styles.separator.fixedHeight) / 2, s_Styles.separator.fixedWidth, s_Styles.separator.fixedHeight); if (EditorGUI.DropdownButton(buttonRect, GUIContent.none, FocusType.Passive, s_Styles.separator)) { string currentSubFolder = ""; if (!lastElement) currentSubFolder = m_BreadCrumbs[i + 1].Value; BreadCrumbListMenu.Show(folderPath, currentSubFolder, buttonRect, this); } } rect.x += s_Styles.separator.fixedWidth; } } else if (m_SearchFilter.folders.Length > 1) { GUI.Label(rect, GUIContent.Temp("Showing multiple folders..."), EditorStyles.miniLabel); } } void BottomBar() { if (m_BottomBarRect.height == 0f) return; Rect rect = m_BottomBarRect; // Background GUI.Label(rect, GUIContent.none, s_Styles.bottomBarBg); // Icons are fixed size in One Column mode, so only show icon size slider in Two Columns mode bool showIconSizeSlider = m_ViewMode == ViewMode.TwoColumns || m_SearchFilter.IsSearching(); if (showIconSizeSlider) { Rect sliderRect = new Rect(rect.x + rect.width - k_SliderWidth - 16f , rect.y + rect.height - (m_BottomBarRect.height + EditorGUI.kSingleLineHeight) / 2, k_SliderWidth, m_BottomBarRect.height); IconSizeSlider(sliderRect); } // File path EditorGUIUtility.SetIconSize(new Vector2(16, 16)); // If not set we see icons scaling down if text is being cropped const float k_Margin = 2; rect.width -= k_Margin * 2; rect.x += k_Margin; rect.height = k_BottomBarHeight; if (showIconSizeSlider) { rect.width -= k_SliderWidth + 14f; } GUI.Label(rect, m_SelectedPathContent, s_Styles.selectedPathLabel); EditorGUIUtility.SetIconSize(new Vector2(0, 0)); } public void SelectAssetsFolder() { ShowFolderContents(AssetDatabase.GetMainAssetOrInProgressProxyInstanceID("Assets"), true); } string ValidateCreateNewAssetPath(string pathName) { // Normally we create assets relative to current selected asset. If no asset is selected we normally create the asset in the root folder (Assets) // but in two column mode we want to create the asset in the currently shown folder if no asset is selected. (fix case 550484) if (m_ViewMode == ViewMode.TwoColumns && m_SearchFilter.GetState() == SearchFilter.State.FolderBrowsing && m_SearchFilter.folders.Length > 0) { // Ensure pathName is not already a full asset path if (!pathName.StartsWith("assets/", StringComparison.CurrentCultureIgnoreCase)) { // If no assets are selected we use first currently shown folder path if (Selection.GetFiltered(typeof(Object), SelectionMode.Assets).Length == 0) { pathName = Path.Combine(m_SearchFilter.folders[0], pathName); pathName = pathName.Replace("\\", "/"); } } } return pathName; } internal void BeginPreimportedNameEditing(int instanceID, EndNameEditAction endAction, string pathName, Texture2D icon, string resourceFile, bool selectAssetBeingCreated) { if (!Initialized()) Init(); // End any rename that might be active, this will also end any asset currently being created EndRenaming(); bool isCreatingNewFolder = endAction is DoCreateFolder; if (m_ViewMode == ViewMode.TwoColumns) { if (m_SearchFilter.GetState() != SearchFilter.State.FolderBrowsing) { // Force select the Assets folder as default when no folders are selected SelectAssetsFolder(); } pathName = ValidateCreateNewAssetPath(pathName); if (m_ListAreaState.m_CreateAssetUtility.BeginNewAssetCreation(instanceID, endAction, pathName, icon, resourceFile, selectAssetBeingCreated)) { ShowFolderContents(AssetDatabase.GetMainAssetOrInProgressProxyInstanceID(m_ListAreaState.m_CreateAssetUtility.folder), true); m_ListArea.BeginNamingNewAsset(m_ListAreaState.m_CreateAssetUtility.originalName, instanceID, isCreatingNewFolder); } } else if (m_ViewMode == ViewMode.OneColumn) { // If search is active put new asset under selected folder otherwise in Assets if (m_SearchFilter.IsSearching()) { ClearSearch(); } // Create in tree AssetsTreeViewGUI defaultTreeViewGUI = m_AssetTree.gui as AssetsTreeViewGUI; if (defaultTreeViewGUI != null) defaultTreeViewGUI.BeginCreateNewAsset(instanceID, endAction, pathName, icon, resourceFile, selectAssetBeingCreated); else Debug.LogError("Not valid defaultTreeViewGUI!"); } } public void FrameObject(int instanceID, bool ping) { m_LockTracker.StopPingIcon(); bool canFrame = CanFrameAsset(instanceID); if (!canFrame) { // Check if we can frame the main asset from the same asset path instead. // This ensures that Components or child GameObject of Prefabs or hidden sub assets will // still be located and pinged in the Project Browser (case 1262196). var path = AssetDatabase.GetAssetPath(instanceID); if (!string.IsNullOrEmpty(path)) { var mainObject = AssetDatabase.LoadMainAssetAtPath(path); if (mainObject != null) { canFrame = CanFrameAsset(mainObject.GetInstanceID()); if (canFrame) instanceID = mainObject.GetInstanceID(); } } } bool frame = ping || canFrame; if (frame && m_LockTracker.isLocked) { frame = false; // If the item is visible then we can ping it however if it requires revealing then we can not and should indicate why(locked project view). if (canFrame && ((m_ViewMode == ViewMode.TwoColumns && m_ListArea != null && !m_ListArea.IsShowing(instanceID)) || (m_ViewMode == ViewMode.OneColumn && m_AssetTree != null && m_AssetTree.data.GetRow(instanceID) == -1))) { Repaint(); m_LockTracker.PingIcon(); } } FrameObjectPrivate(instanceID, frame, ping); if (s_LastInteractedProjectBrowser == this) { m_GrabKeyboardFocusForListArea = true; } } private void FrameObjectPrivate(int instanceID, bool frame, bool ping) { if (instanceID == 0 || m_ListArea == null) return; // If framing the same instance as the last one we do not remove the ping // since issuing first a ping and then a framing should still show the ping. if (m_LastFramedID != instanceID) EndPing(); m_LastFramedID = instanceID; ClearSearch(); if (m_ViewMode == ViewMode.TwoColumns) { FrameObjectInTwoColumnMode(instanceID, frame, ping); } else if (m_ViewMode == ViewMode.OneColumn) { // Clear search to switch back to tree view m_AssetTree.Frame(instanceID, frame, ping); } } private void FrameObjectInTwoColumnMode(int instanceID, bool frame, bool ping) { int folderInstanceID = 0; if (instanceID == kPackagesFolderInstanceId) folderInstanceID = kPackagesFolderInstanceId; else { string assetPath = AssetDatabase.GetAssetPath(instanceID); if (!String.IsNullOrEmpty(assetPath)) { string containingFolder = ProjectWindowUtil.GetContainingFolder(assetPath); if (!String.IsNullOrEmpty(containingFolder)) folderInstanceID = GetFolderInstanceID(containingFolder); if (folderInstanceID == 0) folderInstanceID = AssetDatabase.GetMainAssetOrInProgressProxyInstanceID("Assets"); } } // Could be a scene gameobject if (folderInstanceID != 0) { m_FolderTree.Frame(folderInstanceID, frame, ping); if (frame) ShowFolderContents(folderInstanceID, true); m_ListArea.Frame(instanceID, frame, ping); } } // Also called from C++ (used for AssetSelection overriding) [UsedByNativeCode] internal static int[] GetTreeViewFolderSelection(bool forceUseTreeViewSelection = false) { // Since we can delete entire folder hierarchies with the returned selection we need to be very careful. We therefore require the following: // - The folder/favorite tree view must have keyboard focus // Note we cannot require window focus (focusedWindow) since on OSX window focus is lost to popup window when right clicking ProjectBrowser ob = s_LastInteractedProjectBrowser; if (ob != null && (ob.useTreeViewSelectionInsteadOfMainSelection || forceUseTreeViewSelection) && ob.m_FolderTree != null) { return s_LastInteractedProjectBrowser.m_FolderTree.GetSelection(); } return k_EmptySelection; } public float listAreaGridSize { get { return m_ListArea.gridSize; } } [UsedByNativeCode] internal static bool CanDeleteSelectedAssets() { var treeViewSelection = GetTreeViewFolderSelection(); var instanceIDs = treeViewSelection.Length > 0 ? new List<int>(treeViewSelection) : new List<int>(Selection.instanceIDs); var objectsToDelete = new HashSet<int>(); foreach (var instanceID in instanceIDs) { if (instanceID == AssetDatabase.GetMainAssetOrInProgressProxyInstanceID("Assets") || instanceID == kPackagesFolderInstanceId) { return false; } if (AssetDatabase.IsMainAsset(instanceID)) { var path = AssetDatabase.GetAssetPath(instanceID); bool isRootFolder, isImmutable; if (string.IsNullOrEmpty(path) || !AssetDatabase.TryGetAssetFolderInfo(path, out isRootFolder, out isImmutable) || isRootFolder || isImmutable) { return false; } objectsToDelete.Add(instanceID); } } return objectsToDelete.Count != 0; } [UsedByNativeCode] internal static void DeleteSelectedAssets(bool askIfSure) { int[] treeViewSelection = GetTreeViewFolderSelection(); List<int> instanceIDs; if (treeViewSelection.Length > 0) instanceIDs = new List<int>(treeViewSelection); else instanceIDs = new List<int>(Selection.instanceIDs); if (instanceIDs.Count == 0) return; if (ProjectWindowUtil.DeleteAssets(instanceIDs, askIfSure)) { // Ensure selection is cleared since StopAssetEditing() will restore selection from a backup saved in StartAssetEditing. Selection.instanceIDs = k_EmptySelection; } } [UsedByNativeCode] internal static void RenameSelectedAssets() { ProjectBrowser ob = s_LastInteractedProjectBrowser; if (ob != null) { if (ob.useTreeViewSelectionInsteadOfMainSelection && ob.m_FolderTree != null) { ob.m_FolderTree.BeginNameEditing(0f); } else if (ob.m_ViewMode == ViewMode.OneColumn && !ob.m_SearchFilter.IsSearching() && ob.m_AssetTree != null) { ob.m_AssetTree.BeginNameEditing(0f); } else if (ob.m_ListArea != null) { ob.m_ListArea.BeginRename(0f); } else { return; } // We need to ensure that we start with focus in the rename overlay (UUM-48858) ob.Focus(); ob.Repaint(); } } internal IHierarchyProperty GetHierarchyPropertyUsingFilter(string textFilter) { FilteredHierarchy filteredHierarchy = new FilteredHierarchy(HierarchyType.Assets); filteredHierarchy.searchFilter = SearchFilter.CreateSearchFilterFromString(textFilter); IHierarchyProperty property = FilteredHierarchyProperty.CreateHierarchyPropertyForFilter(filteredHierarchy); return property; } internal void ShowObjectsInList(int[] instanceIDs) { if (!Initialized()) Init(); if (m_ViewMode == ViewMode.TwoColumns) { m_ListArea.ShowObjectsInList(instanceIDs); m_FolderTree.SetSelection(k_EmptySelection, false); // Remove selection from folder tree since we show custom list (press F to focus) } else if (m_ViewMode == ViewMode.OneColumn) { foreach (int instanceID in Selection.instanceIDs) m_AssetTree.Frame(instanceID, true, false); } } // Called from AssetsMenu [RequiredByNativeCode] static void ShowSelectedObjectsInLastInteractedProjectBrowser() { // Only one ProjectBrowser can have focus at a time so if we find one just return that one if (s_LastInteractedProjectBrowser != null) { int[] instanceIDs = Selection.instanceIDs; s_LastInteractedProjectBrowser.ShowObjectsInList(instanceIDs); } } // Called from DockArea protected virtual void ShowButton(Rect r) { if (s_Styles == null) s_Styles = new Styles(); if (m_LockTracker.ShowButton(r, s_Styles.lockButton)) Repaint(); } internal bool SelectionIsFavorite() { if (m_FolderTree.GetSelection().Length != 1) return false; int selectionID = m_FolderTree.GetSelection()[0]; ItemType type = GetItemType(selectionID); return type == ItemType.SavedFilter; } private void RevertToLastSelectedFolder(bool folderWasSelected) { if (m_LastFolders != null && m_LastFolders.Length > 0) { m_SearchFilter.folders = m_LastFolders; if (m_FolderTree != null) SetFolderSelection(GetFolderInstanceIDs(m_LastFolders), true, folderWasSelected); } } internal class SavedFiltersContextMenu { int m_SavedFilterInstanceID; static internal void Show(int savedFilterInstanceID) { // Curve context menu GUIContent delete = EditorGUIUtility.TrTextContent("Delete"); GenericMenu menu = new GenericMenu(); menu.AddItem(delete, false, new SavedFiltersContextMenu(savedFilterInstanceID).Delete); menu.ShowAsContext(); } private SavedFiltersContextMenu(int savedFilterInstanceID) { m_SavedFilterInstanceID = savedFilterInstanceID; } private void Delete() { DeleteFilter(m_SavedFilterInstanceID); } } internal class BreadCrumbListMenu { static ProjectBrowser m_Caller; string m_SubFolder; static internal void Show(string folder, string currentSubFolder, Rect activatorRect, ProjectBrowser caller) { m_Caller = caller; // List of sub folders var subFolders = new List<string>(); var subFolderDisplayNames = new List<string>(); if (folder == Folders.GetPackagesPath()) { foreach (var package in PackageManagerUtilityInternal.GetAllVisiblePackages(caller.m_SkipHiddenPackages)) { subFolders.Add(package.assetPath); var displayName = !string.IsNullOrEmpty(package.displayName) ? package.displayName : package.name; subFolderDisplayNames.Add(displayName); } } else { subFolders.AddRange(AssetDatabase.GetSubFolders(folder)); foreach (var subFolderPath in subFolders) subFolderDisplayNames.Add(Path.GetFileName(subFolderPath)); } var menu = new GenericMenu {allowDuplicateNames = true}; if (subFolders.Count > 0) { var i = 0; foreach (var subFolderPath in subFolders) { menu.AddItem(new GUIContent(subFolderDisplayNames[i++]), subFolderPath == currentSubFolder, new BreadCrumbListMenu(subFolderPath).SelectSubFolder); menu.ShowAsContext(); } } else { menu.AddDisabledItem(EditorGUIUtility.TrTextContent("No sub folders...")); } menu.DropDown(activatorRect); } private BreadCrumbListMenu(string subFolder) { m_SubFolder = subFolder; } private void SelectSubFolder() { int folderInstanceID = AssetDatabase.GetMainAssetOrInProgressProxyInstanceID(m_SubFolder); if (folderInstanceID != 0) m_Caller.ShowFolderContents(folderInstanceID, false); } } } }
UnityCsReference/Editor/Mono/ProjectBrowser/ProjectBrowser.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/ProjectBrowser/ProjectBrowser.cs", "repo_id": "UnityCsReference", "token_count": 64763 }
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.Reflection; using UnityEngine; using UnityEngine.Assertions; using UnityEngine.Rendering; namespace UnityEditor.Rendering { /// <summary> /// Utility class for <see cref="RenderPipelineResources"/> in Editor /// </summary> static class RenderPipelineResourcesEditorUtils { public enum ResultStatus { NothingToUpdate, //There was nothing to reload InvalidPathOrNameFound, //Encountered a path that do not exist ResourceReloaded, //Some resources got reloaded SkipedDueToNotMainThread, //Worker Thread cannot fully load resources } /// <summary> /// Looks for resources in the given <paramref name="resource"/> object and reload /// the ones that are missing or broken. /// This version will still return null value without throwing error if the issue /// is due to AssetDatabase being not ready. But in this case the assetDatabaseNotReady /// result will be true. /// </summary> /// <param name="resource">The object containing reload-able resources</param> /// <returns> The status </returns> public static ResultStatus TryReloadContainedNullFields(IRenderPipelineResources resource) { if (AssetDatabase.IsAssetImportWorkerProcess()) return ResultStatus.SkipedDueToNotMainThread; try { if (new Reloader(resource).hasChanged) return ResultStatus.ResourceReloaded; else return ResultStatus.NothingToUpdate; } catch (InvalidImportException e) { Debug.LogError(e.Message); return ResultStatus.InvalidPathOrNameFound; } catch (Exception e) { throw e; } } // Important: This is not meant to work with resources in Unity. This is only for packages and User code. // If we need to make it work for Unity core, one want to update Reloader.GetRootPathForType(...) struct Reloader { IRenderPipelineResources mainContainer; string root; public bool hasChanged { get; private set; } public Reloader(IRenderPipelineResources container) { mainContainer = container; hasChanged = false; root = GetRootPathForType(container.GetType()); ReloadNullFields(container); } static string GetRootPathForType(Type type) { //Warning: PackageManager.PackageInfo.FindForAssembly will always provide null in Worker thread var packageInfo = PackageManager.PackageInfo.FindForAssembly(type.Assembly); return packageInfo == null ? "Assets/" : $"Packages/{packageInfo.name}/"; } (string[] paths, SearchType location, bool isField) GetResourcesPaths(FieldInfo fieldInfo) { var attr = fieldInfo.GetCustomAttribute<ResourcePathsBaseAttribute>(inherit: false); return (attr?.paths, attr?.location ?? default, attr?.isField ?? default); } string GetFullPath(string path, SearchType location) => location == SearchType.ProjectPath ? $"{root}{path}" : path; bool IsNull(System.Object container, FieldInfo info) => IsNull(info.GetValue(container)); bool IsNull(System.Object field) => field == null || field.Equals(null); bool ConstructArrayIfNeeded(System.Object container, FieldInfo info, int length) { if (IsNull(container, info) || ((Array)info.GetValue(container)).Length != length) { info.SetValue(container, Activator.CreateInstance(info.FieldType, length)); return true; } return false; } void ReloadNullFields(System.Object container) { foreach (var fieldInfo in container.GetType() .GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)) { //Skip element that do not have path (string[] paths, SearchType location, bool isField) = GetResourcesPaths(fieldInfo); if (paths == null) continue; //Field case: reload if null if (isField) { hasChanged |= SetAndLoadIfNull(container, fieldInfo, GetFullPath(paths[0], location), location); continue; } //Array case: Find each null element and reload them hasChanged |= ConstructArrayIfNeeded(container, fieldInfo, paths.Length); var array = (Array)fieldInfo.GetValue(container); for (int index = 0; index < paths.Length; ++index) hasChanged |= SetAndLoadIfNull(array, index, GetFullPath(paths[index], location), location); } } bool SetAndLoadIfNull(System.Object container, FieldInfo info, string path, SearchType location) { if (IsNull(container, info)) { info.SetValue(container, Load(path, info.FieldType, location)); return true; } return false; } bool SetAndLoadIfNull(Array array, int index, string path, SearchType location) { var element = array.GetValue(index); if (IsNull(element)) { array.SetValue(Load(path, array.GetType().GetElementType(), location), index); return true; } return false; } UnityEngine.Object Load(string path, Type type, SearchType location) { // Check if asset exist. // Direct loading can be prevented by AssetDatabase being reloading. var guid = AssetDatabase.AssetPathToGUID(path); if (location == SearchType.ProjectPath && String.IsNullOrEmpty(guid)) throw new InvalidImportException($"Failed to find {path} in {location}."); UnityEngine.Object result = type == typeof(Shader) ? LoadShader(path, location) : LoadNonShaderAssets(path, type, location); if (IsNull(result)) switch (location) { case SearchType.ProjectPath: throw new InvalidImportException($"Cannot load. Path {path} is correct but AssetDatabase cannot load now."); case SearchType.ShaderName: throw new InvalidImportException($"Failed to find {path} in {location}."); case SearchType.BuiltinPath: throw new InvalidImportException($"Failed to find {path} in {location}."); case SearchType.BuiltinExtraPath: throw new InvalidImportException($"Failed to find {path} in {location}."); } return result; } UnityEngine.Object LoadShader(string path, SearchType location) { switch (location) { case SearchType.ShaderName: case SearchType.BuiltinPath: case SearchType.BuiltinExtraPath: return Shader.Find(path); case SearchType.ProjectPath: return AssetDatabase.LoadAssetAtPath(path, typeof(Shader)); default: throw new NotImplementedException($"Unknown {location}"); } } UnityEngine.Object LoadNonShaderAssets(string path, Type type, SearchType location) => location switch { SearchType.BuiltinPath => UnityEngine.Resources.GetBuiltinResource(type, path), //log error if path is wrong and return null SearchType.BuiltinExtraPath => AssetDatabase.GetBuiltinExtraResource(type, path), //log error if path is wrong and return null SearchType.ProjectPath => AssetDatabase.LoadAssetAtPath(path, type), //return null if path is wrong SearchType.ShaderName => throw new ArgumentException($"{nameof(SearchType.ShaderName)} is only available for Shaders."), _ => throw new NotImplementedException($"Unknown {location}") }; } } }
UnityCsReference/Editor/Mono/RenderPipelineResourcesEditorUtils.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/RenderPipelineResourcesEditorUtils.cs", "repo_id": "UnityCsReference", "token_count": 4270 }
336
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; using UnityEditor.SceneManagement; using UnityEngine; using UnityEngine.SceneManagement; namespace UnityEditor { [Serializable] class MainStageHierarchyState { [SerializeField] float m_ScrollY; [SerializeField] List<int> m_ExpandedSceneGameObjectInstanceIDs = new List<int>(); [SerializeField] int m_LastClickedInstanceID; [SerializeField] string[] m_OpenSceneGUIDs = null; public void SaveStateFromHierarchy(SceneHierarchyWindow hierarchy, Stage stage) { var lastClickedGameObject = EditorUtility.InstanceIDToObject(hierarchy.sceneHierarchy.treeViewState.lastClickedID) as GameObject; m_LastClickedInstanceID = lastClickedGameObject != null ? lastClickedGameObject.GetInstanceID() : 0; m_ExpandedSceneGameObjectInstanceIDs = hierarchy.sceneHierarchy.treeViewState.expandedIDs; m_ScrollY = hierarchy.sceneHierarchy.treeViewState.scrollPos.y; m_OpenSceneGUIDs = GetCurrentSceneGUIDs(); if (SceneHierarchy.s_DebugPersistingExpandedState) DebugLog("Saving", stage); } public void LoadStateIntoHierarchy(SceneHierarchyWindow hierarchy, Stage stage) { // Restore expanded state always hierarchy.sceneHierarchy.treeViewState.expandedIDs = m_ExpandedSceneGameObjectInstanceIDs; // Restore selection and scroll value when requested if (stage.setSelectionAndScrollWhenBecomingCurrentStage) { Selection.activeInstanceID = m_LastClickedInstanceID; // We only want to set scroll position if none of the scene that were open // when the scroll was recorded have been closed in the mean time. // (Why do we apply selection and expanded state regardless then? // Because for those it still make sense to apply it even if only // some of the scenes that were open originally are still open, and // for the rest it will have no effect anyway.) bool anyOfScenesWereClosed = false; if (m_OpenSceneGUIDs != null) { var currentSceneGUIDs = GetCurrentSceneGUIDs(); for (int i = 0; i < m_OpenSceneGUIDs.Length; i++) { if (!currentSceneGUIDs.Contains(m_OpenSceneGUIDs[i])) { anyOfScenesWereClosed = true; break; } } } if (!anyOfScenesWereClosed) hierarchy.sceneHierarchy.treeViewState.scrollPos.y = m_ScrollY; } if (SceneHierarchy.s_DebugPersistingExpandedState) DebugLog("Restoring", stage); } void DebugLog(string prefix, Stage stage) { Debug.Log(prefix + (stage.GetType().ToString()) + string.Format("-main stage: {0}, -scrollY: {1}, -selection {2}, -setSelection {3}", DebugUtils.ListToString(m_ExpandedSceneGameObjectInstanceIDs), m_ScrollY, m_LastClickedInstanceID, stage.setSelectionAndScrollWhenBecomingCurrentStage)); } string[] GetCurrentSceneGUIDs() { int count = SceneManager.sceneCount; string[] sceneGUIDs = new string[count]; for (int i = 0; i < count; i++) sceneGUIDs[i] = SceneManager.GetSceneAt(i).guid; return sceneGUIDs; } } }
UnityCsReference/Editor/Mono/SceneManagement/StageManager/MainStageHierarchyState.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/SceneManagement/StageManager/MainStageHierarchyState.cs", "repo_id": "UnityCsReference", "token_count": 1773 }
337
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using UnityEditorInternal; using UnityEngine; using UnityEngineInternal; using UnityEngine.Rendering; using System.Text; using System.Globalization; using System.Linq; namespace UnityEditor { [EditorWindowTitle(title = "Lighting", icon = "Lighting")] internal class LightingWindow : EditorWindow { static class Styles { public static readonly GUIContent[] modeStrings = { EditorGUIUtility.TrTextContent("Scene"), EditorGUIUtility.TrTextContent("Environment"), EditorGUIUtility.TrTextContent("Realtime Lightmaps"), EditorGUIUtility.TrTextContent("Baked Lightmaps") }; public static readonly GUIStyle labelStyle = EditorStyles.wordWrappedMiniLabel; public static readonly GUIStyle buttonStyle = "LargeButton"; public static readonly GUIContent continuousBakeLabel = EditorGUIUtility.TrTextContent("Auto Generate", "Generate lighting data in the Scene when there are changes that affect Scene lighting, such as modifications to lights, materials, or geometry. This option is only available when there is a Lighting Settings Asset assigned in the Lighting Window."); public static readonly GUIContent bakeLabel = EditorGUIUtility.TrTextContent("Generate Lighting", "Generates the lightmap data for the current active scene. This lightmap data (for realtime and baked global illumination) is stored in the GI Cache. For GI Cache settings see the Preferences panel."); public static readonly GUIContent bakeLabelAnythingCompiling = EditorGUIUtility.TrTextContent("Generate Lighting", "Generate Lighting is currently unavailable. Waiting for asynchronous shader compilation."); public static readonly GUIContent cancelLabel = EditorGUIUtility.TrTextContent("Cancel"); public static readonly GUIContent progressiveGPUBakingDevice = EditorGUIUtility.TrTextContent("GPU Baking Device", "Will list all available GPU devices."); public static readonly GUIContent progressiveGPUUnknownDeviceInfo = EditorGUIUtility.TrTextContent("No devices found. Please start an initial bake to make this information available."); public static readonly GUIContent progressiveGPUChangeWarning = EditorGUIUtility.TrTextContent("Changing the compute device used by the Progressive GPU Lightmapper requires the editor to be relaunched. Do you want to change device and restart?"); public static readonly GUIContent gpuBakingProfile = EditorGUIUtility.TrTextContent("GPU Baking Profile", "The profile chosen for trading off between performance and memory usage when baking using the GPU."); public static readonly GUIContent invalidEnvironmentLabel = EditorGUIUtility.TrTextContentWithIcon("Baked environment lighting does not match the current Scene state. Generate Lighting to update this.", MessageType.Warning); public static readonly GUIContent unsupportedDenoisersLabel = EditorGUIUtility.TrTextContentWithIcon("Unsupported denoiser selected", MessageType.Error); public static readonly int[] progressiveGPUUnknownDeviceValues = { 0 }; public static readonly GUIContent[] progressiveGPUUnknownDeviceStrings = { EditorGUIUtility.TrTextContent("Unknown"), }; // Keep in sync with BakingProfile.h::BakingProfile public static readonly int bakingProfileDefault = 2; public static readonly int[] bakingProfileValues = { 0, 1, 2, 3, 4 }; public static readonly GUIContent[] bakingProfileStrings = { EditorGUIUtility.TrTextContent("Highest Performance"), EditorGUIUtility.TrTextContent("High Performance"), EditorGUIUtility.TrTextContent("Automatic"), EditorGUIUtility.TrTextContent("Low Memory Usage"), EditorGUIUtility.TrTextContent("Lowest Memory Usage"), }; public static string[] BakeModeStrings = { "Bake Reflection Probes", "Clear Baked Data" }; public static readonly string BakingPausedHelpText = $"{Styles.bakeLabel.text} is currently unavailable. Waiting for asynchronous shader compilation to finish..."; } public interface WindowTab { void OnEnable(); void OnDisable(); void OnGUI(); void OnSummaryGUI(); void OnSelectionChange(); bool HasHelpGUI(); } enum BakeMode { BakeReflectionProbes = 0, Clear = 1 } enum Mode { LightingSettings = 0, EnvironmentSettings, RealtimeLightmaps, BakedLightmaps } const string kGlobalIlluminationUnityManualPage = "https://docs.unity3d.com/Manual/lighting-window.html"; const string m_LightmappingDeviceIndexKey = "lightmappingDeviceIndex"; const string m_BakingProfileKey = "lightmappingBakingProfile"; int m_SelectedModeIndex = 0; List<Mode> m_Modes = null; GUIContent[] m_ModeStrings; Dictionary<Mode, WindowTab> m_Tabs = new Dictionary<Mode, WindowTab>(); static SerializedObject m_LightingSettings; bool m_IsRealtimeSupported = false; bool m_IsBakedSupported = false; bool m_IsEnvironmentSupported = false; static SerializedObject lightingSettings { get { // if we set a new scene as the active scene, we need to make sure to respond to those changes if (m_LightingSettings == null || m_LightingSettings.targetObject == null || m_LightingSettings.targetObject != Lightmapping.lightingSettingsInternal) { var targetObject = Lightmapping.lightingSettingsInternal; if (targetObject == null) { targetObject = Lightmapping.lightingSettingsDefaults; } m_LightingSettings = new SerializedObject(targetObject); } return m_LightingSettings; } } // for internal debug use only internal void SetSelectedTabIndex(int index) { m_SelectedModeIndex = index; } LightingWindow() { m_Tabs.Add(Mode.LightingSettings, new LightingWindowLightingTab()); m_Tabs.Add(Mode.EnvironmentSettings, new LightingWindowEnvironmentTab()); m_Tabs.Add(Mode.RealtimeLightmaps, new LightingWindowLightmapPreviewTab(LightmapType.DynamicLightmap)); m_Tabs.Add(Mode.BakedLightmaps, new LightingWindowLightmapPreviewTab(LightmapType.StaticLightmap)); var customWindowTabs = TypeCache.GetTypesDerivedFrom<LightingWindowTab>(); foreach (Type tabType in customWindowTabs) { var tab = Activator.CreateInstance(tabType) as LightingWindowTab; m_Tabs.Add((Mode)tabType.Name.GetHashCode(), tab); tab.m_Parent = this; } } // Repaint when MRays/sec changes float m_LastRepaintedMraysPerSec; protected void Update() { float totalNow = Lightmapping.GetLightmapBakePerformanceTotal(); if (Math.Abs(totalNow - m_LastRepaintedMraysPerSec) < s_MraysPerSecRepaintThreshold) return; m_LastRepaintedMraysPerSec = totalNow; Repaint(); } void OnEnable() { s_Window = this; titleContent = GetLocalizedTitleContent(); foreach (var pair in m_Tabs) pair.Value.OnEnable(); Undo.undoRedoEvent += OnUndoRedo; Lightmapping.lightingDataUpdated += Repaint; Repaint(); } void OnDisable() { foreach (var pair in m_Tabs) pair.Value.OnDisable(); Undo.undoRedoEvent -= OnUndoRedo; Lightmapping.lightingDataUpdated -= Repaint; } private void OnUndoRedo(in UndoRedoInfo info) { Repaint(); } void OnBecameVisible() { RepaintSceneAndGameViews(); } void OnBecameInvisible() { RepaintSceneAndGameViews(); } void OnSelectionChange() { if (m_Modes == null) return; foreach (var pair in m_Tabs) { if (m_Modes.Contains(pair.Key)) pair.Value.OnSelectionChange(); } Repaint(); } static internal void RepaintSceneAndGameViews() { SceneView.RepaintAll(); PlayModeView.RepaintAll(); } void OnGUI() { // This is done so that we can adjust the UI when the user swiches SRP SetupModes(); lightingSettings.Update(); // reset index to settings page if one of the tabs went away if (m_SelectedModeIndex < 0 || m_SelectedModeIndex >= m_Modes.Count) m_SelectedModeIndex = 0; Mode selectedMode = m_Modes[m_SelectedModeIndex]; DrawTopBarGUI(selectedMode); EditorGUILayout.Space(); if (m_Tabs.ContainsKey(selectedMode)) m_Tabs[selectedMode].OnGUI(); // Draw line to separate the bottom portion of the window from the tab being displayed Rect lineRect = GUILayoutUtility.topLevel.PeekNext(); lineRect.height = 1; EditorGUI.DrawDelimiterLine(lineRect); EditorGUILayout.Space(); DrawBottomBarGUI(selectedMode); lightingSettings.ApplyModifiedProperties(); } void SetupModes() { if (m_Modes == null) { m_Modes = new List<Mode>(); } bool isRealtimeSupported = SupportedRenderingFeatures.IsLightmapBakeTypeSupported(LightmapBakeType.Realtime); bool isBakedSupported = SupportedRenderingFeatures.IsLightmapBakeTypeSupported(LightmapBakeType.Baked); bool isEnvironmentSupported = !(SupportedRenderingFeatures.active.overridesEnvironmentLighting && SupportedRenderingFeatures.active.overridesFog && SupportedRenderingFeatures.active.overridesOtherLightingSettings); if (m_IsRealtimeSupported != isRealtimeSupported || m_IsBakedSupported != isBakedSupported || m_IsEnvironmentSupported != isEnvironmentSupported) { m_Modes.Clear(); m_IsBakedSupported = isBakedSupported; m_IsRealtimeSupported = isRealtimeSupported; m_IsEnvironmentSupported = isEnvironmentSupported; } // if nothing has changed since last time and we have data, we return if (m_Modes.Count > 0) return; List<GUIContent> modeStringList = new List<GUIContent>(); m_Modes.Add(Mode.LightingSettings); modeStringList.Add(Styles.modeStrings[(int)Mode.LightingSettings]); if (m_IsEnvironmentSupported) { m_Modes.Add(Mode.EnvironmentSettings); modeStringList.Add(Styles.modeStrings[(int)Mode.EnvironmentSettings]); } if (m_IsRealtimeSupported) { m_Modes.Add(Mode.RealtimeLightmaps); modeStringList.Add(Styles.modeStrings[(int)Mode.RealtimeLightmaps]); } if (m_IsBakedSupported) { m_Modes.Add(Mode.BakedLightmaps); modeStringList.Add(Styles.modeStrings[(int)Mode.BakedLightmaps]); } foreach (var pair in m_Tabs) { var customTab = pair.Value as LightingWindowTab; if (customTab == null) continue; int priority = customTab.priority < 0 ? m_Modes.Count : Mathf.Min(customTab.priority, m_Modes.Count); m_Modes.Insert(priority, pair.Key); modeStringList.Insert(priority, customTab.titleContent); } Debug.Assert(m_Modes.Count == modeStringList.Count); m_ModeStrings = modeStringList.ToArray(); } internal void SetToolbarDirty() { m_Modes = null; } void DrawHelpGUI() { var iconSize = EditorStyles.iconButton.CalcSize(EditorGUI.GUIContents.helpIcon); var rect = GUILayoutUtility.GetRect(iconSize.x, iconSize.y); if (GUI.Button(rect, EditorGUI.GUIContents.helpIcon, EditorStyles.iconButton)) { Help.ShowHelpPage(kGlobalIlluminationUnityManualPage); } } void DrawSettingsGUI(Mode mode) { if (mode == Mode.LightingSettings || mode == Mode.EnvironmentSettings) { var iconSize = EditorStyles.iconButton.CalcSize(EditorGUI.GUIContents.titleSettingsIcon); var rect = GUILayoutUtility.GetRect(iconSize.x, iconSize.y); if (EditorGUI.DropdownButton(rect, EditorGUI.GUIContents.titleSettingsIcon, FocusType.Passive, EditorStyles.iconButton)) { if (mode == Mode.LightingSettings) EditorUtility.DisplayCustomMenu(rect, new[] { EditorGUIUtility.TrTextContent("Reset") }, -1, ResetLightingSettings, null); else if (mode == Mode.EnvironmentSettings) EditorUtility.DisplayCustomMenu(rect, new[] { EditorGUIUtility.TrTextContent("Reset") }, -1, ResetEnvironmentSettings, null); } } } void ResetLightingSettings(object userData, string[] options, int selected) { if (Lightmapping.lightingSettingsInternal != null) { Undo.RecordObjects(new[] { Lightmapping.lightingSettingsInternal }, "Reset Lighting Settings"); Unsupported.SmartReset(Lightmapping.lightingSettingsInternal); } } void ResetEnvironmentSettings(object userData, string[] options, int selected) { Undo.RecordObjects(new[] { RenderSettings.GetRenderSettings() }, "Reset Environment Settings"); Unsupported.SmartReset(RenderSettings.GetRenderSettings()); } void DrawToolbarRange(int start, int end) { var strings = new GUIContent[end - start]; Array.Copy(m_ModeStrings, start, strings, 0, strings.Length); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); m_SelectedModeIndex = GUILayout.Toolbar(m_SelectedModeIndex - start, strings, Styles.buttonStyle, GUI.ToolbarButtonSize.FitToContents) + start; GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); } void DrawTopBarGUI(Mode selectedMode) { EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); if (m_Tabs[selectedMode].HasHelpGUI()) GUILayout.Space(EditorStyles.iconButton.CalcSize(EditorGUI.GUIContents.helpIcon).x); GUILayout.FlexibleSpace(); if (m_Modes.Count > 1) { // Split the toolbar if it doesn't fit horizontally bool requireSplit = false; float width = position.width - 2 * 16; for (int i = 0; i < m_ModeStrings.Length; i++) { width -= Styles.buttonStyle.CalcSize(m_ModeStrings[i]).x; if (width <= 0) { requireSplit = true; break; } } if (requireSplit) { // Simply split in two to avoid weird layouts int half = Mathf.CeilToInt(m_ModeStrings.Length / 2.0f); EditorGUILayout.BeginVertical(); DrawToolbarRange(0, half); DrawToolbarRange(half, m_ModeStrings.Length); EditorGUILayout.EndVertical(); } else m_SelectedModeIndex = GUILayout.Toolbar(m_SelectedModeIndex, m_ModeStrings, Styles.buttonStyle, GUI.ToolbarButtonSize.FitToContents); } GUILayout.FlexibleSpace(); var customTab = m_Tabs[selectedMode] as LightingWindowTab; if (customTab != null) customTab.OnHeaderSettingsGUI(); else { DrawHelpGUI(); DrawSettingsGUI(selectedMode); } EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); } internal static void FocusTab(LightingWindowTab tab) { EditorApplication.update += WaitForWindow; void WaitForWindow() { // Open window in case it's closed var window = GetWindow<LightingWindow>(utility: false, title: null, focus: false); if (window == null || window.m_Modes == null) return; EditorApplication.update -= WaitForWindow; // Select active tab var newMode = (Mode)tab.GetType().Name.GetHashCode(); if (window.m_Modes.Contains(newMode)) { window.m_SelectedModeIndex = window.m_Modes.IndexOf(newMode); window.Repaint(); } } } void BakeDropDownCallback(object data) { BakeMode mode = (BakeMode)data; switch (mode) { case BakeMode.Clear: DoClear(); break; case BakeMode.BakeReflectionProbes: DoBakeReflectionProbes(); break; } } void DrawGPUDeviceSelector() { // GPU lightmapper device selection. if (Lightmapping.GetLightingSettingsOrDefaultsFallback().lightmapper == LightingSettings.Lightmapper.ProgressiveGPU) { DeviceAndPlatform[] devicesAndPlatforms = Lightmapping.GetLightmappingGpuDevices(); if (devicesAndPlatforms.Length > 0) { int[] lightmappingDeviceIndices = Enumerable.Range(0, devicesAndPlatforms.Length).ToArray(); GUIContent[] lightmappingDeviceStrings = devicesAndPlatforms.Select(x => new GUIContent(x.name)).ToArray(); int bakingDeviceAndPlatform = -1; string configDeviceAndPlatform = EditorUserSettings.GetConfigValue(m_LightmappingDeviceIndexKey); if (configDeviceAndPlatform != null) { bakingDeviceAndPlatform = Int32.Parse(configDeviceAndPlatform); bakingDeviceAndPlatform = Mathf.Clamp(bakingDeviceAndPlatform, 0, devicesAndPlatforms.Length - 1); // Removing a GPU and rebooting invalidates the saved value. } else bakingDeviceAndPlatform = Lightmapping.GetLightmapBakeGPUDeviceIndex(); Debug.Assert(bakingDeviceAndPlatform != -1); EditorGUI.BeginChangeCheck(); using (new EditorGUI.DisabledScope(devicesAndPlatforms.Length < 2)) { bakingDeviceAndPlatform = EditorGUILayout.IntPopup(Styles.progressiveGPUBakingDevice, bakingDeviceAndPlatform, lightmappingDeviceStrings, lightmappingDeviceIndices); } if (EditorGUI.EndChangeCheck()) { if (EditorUtility.DisplayDialog("Warning", Styles.progressiveGPUChangeWarning.text, "OK", "Cancel")) { EditorUserSettings.SetConfigValue(m_LightmappingDeviceIndexKey, bakingDeviceAndPlatform.ToString()); DeviceAndPlatform selectedDeviceAndPlatform = devicesAndPlatforms[bakingDeviceAndPlatform]; EditorApplication.CloseAndRelaunch(new string[] { "-OpenCL-PlatformAndDeviceIndices", selectedDeviceAndPlatform.platformId.ToString(), selectedDeviceAndPlatform.deviceId.ToString() }); } } } else { // To show when we are still fetching info, so that the UI doesn't pop around too much for no reason using (new EditorGUI.DisabledScope(true)) { EditorGUILayout.IntPopup(Styles.progressiveGPUBakingDevice, 0, Styles.progressiveGPUUnknownDeviceStrings, Styles.progressiveGPUUnknownDeviceValues); } EditorGUILayout.HelpBox(Styles.progressiveGPUUnknownDeviceInfo.text, MessageType.Info); } } } void DrawBakingProfileSelector() { // Handle the baking profile setting using (new EditorGUI.DisabledScope(Lightmapping.GetLightingSettingsOrDefaultsFallback().lightmapper != LightingSettings.Lightmapper.ProgressiveGPU)) { int bakingProfile = Styles.bakingProfileDefault; string bakingProfileString = EditorUserSettings.GetConfigValue(m_BakingProfileKey); if (bakingProfileString != null) { if (Int32.TryParse(bakingProfileString, out int bakingProfileStoredValue)) { const Int32 maxBakingProfile = 4; // Keep in sync with kMaxBakingProfile (C++). if (bakingProfileStoredValue >= 0 && bakingProfileStoredValue <= maxBakingProfile) bakingProfile = bakingProfileStoredValue; } } bakingProfile = EditorGUILayout.IntPopup(Styles.gpuBakingProfile, bakingProfile, Styles.bakingProfileStrings, Styles.bakingProfileValues); EditorUserSettings.SetConfigValue(m_BakingProfileKey, bakingProfile.ToString()); } } void DrawBottomBarGUI(Mode selectedMode) { using (new EditorGUI.DisabledScope(EditorApplication.isPlayingOrWillChangePlaymode)) { // Preamble with warnings. if (Lightmapping.lightingDataAsset && !Lightmapping.lightingDataAsset.isValid) { EditorGUILayout.HelpBox(Lightmapping.lightingDataAsset.validityErrorMessage, MessageType.Warning); } // Bake settings. DrawGPUDeviceSelector(); DrawBakingProfileSelector(); { // Bake button if we are not currently baking bool showBakeButton = Lightmapping.shouldBakeInteractively || !Lightmapping.isRunning; if (showBakeButton) { bool anythingCompiling = ShaderUtil.anythingCompiling; using (new EditorGUI.DisabledScope(anythingCompiling)) { var customTab = m_Tabs[selectedMode] as LightingWindowTab; if (customTab != null) customTab.OnBakeButtonGUI(); else { GUIContent guiContent = anythingCompiling ? Styles.bakeLabelAnythingCompiling : Styles.bakeLabel; if (EditorGUI.LargeSplitButtonWithDropdownList(guiContent, Styles.BakeModeStrings, BakeDropDownCallback, disableMainButton: !SelectedDenoisersSupported())) { DoBake(); // DoBake could've spawned a save scene dialog. This breaks GUI on mac (Case 490388). // We work around this with an ExitGUI here. GUIUtility.ExitGUI(); } } } } // Cancel button if we are currently baking else { if (GUILayout.Button(Styles.cancelLabel, Styles.buttonStyle)) { Lightmapping.Cancel(); } } } // Per-tab summaries. if (m_Tabs.ContainsKey(selectedMode)) { GUILayout.BeginVertical(EditorStyles.helpBox); m_Tabs[selectedMode].OnSummaryGUI(); GUILayout.EndVertical(); } } } private void DoBake() { Lightmapping.BakeAsync(); } private void DoClear() { Lightmapping.ClearLightingDataAsset(); Lightmapping.Clear(); } private void DoBakeReflectionProbes() { Lightmapping.BakeAllReflectionProbesSnapshots(); } internal static VisualisationGITexture[] GetRealTimeLightmaps() { return LightmapVisualizationUtility.GetRealtimeGITextures(GITextureType.Irradiance); } internal static void GatherRealTimeLightmapStats(ref int lightmapCount, ref long totalMemorySize, ref Dictionary<LightmapSize, int> sizes) { var realTimeLightMaps = GetRealTimeLightmaps(); foreach (var lmap in realTimeLightMaps) { if (lmap.texture == null) continue; lightmapCount++; LightmapSize ls = new() { width = lmap.texture.width, height = lmap.texture.height}; if (sizes.ContainsKey(ls)) sizes[ls]++; else sizes.Add(ls, 1); totalMemorySize += TextureUtil.GetStorageMemorySizeLong(lmap.texture); } } internal static void GatherRunningBakeLightmapStats(ref int lightmapCount, ref long totalMemorySize, ref Dictionary<LightmapSize, int> sizes, ref bool shadowmaskMode) { RunningBakeInfo info = Lightmapping.GetRunningBakeInfo(); lightmapCount = info.lightmapSizes.Length; foreach (var ld in info.lightmapSizes) if (sizes.ContainsKey(ld)) sizes[ld]++; else sizes.Add(ld, 1); shadowmaskMode = false; } internal static void GatherBakedLightmapStats(ref int lightmapCount, ref long totalMemorySize, ref Dictionary<LightmapSize, int> sizes, ref bool shadowmaskMode) { foreach (LightmapData ld in LightmapSettings.lightmaps) { if (ld.lightmapColor == null) continue; lightmapCount++; LightmapSize ls = new() { width = ld.lightmapColor.width, height = ld.lightmapColor.height}; if (sizes.ContainsKey(ls)) sizes[ls]++; else sizes.Add(ls, 1); totalMemorySize += TextureUtil.GetStorageMemorySizeLong(ld.lightmapColor); if (ld.lightmapDir) totalMemorySize += TextureUtil.GetStorageMemorySizeLong(ld.lightmapDir); if (ld.shadowMask) { totalMemorySize += TextureUtil.GetStorageMemorySizeLong(ld.shadowMask); shadowmaskMode = true; } } } internal static void GatherProbeStats(ref ulong probeCount, ref long totalMemorySize) { RunningBakeInfo info = Lightmapping.GetRunningBakeInfo(); probeCount = info.probePositions; totalMemorySize = 0; } internal static void DisplaySummaryLine(string outputString, int lightmapCount, long totalMemorySize) { GUILayout.BeginVertical(); GUILayout.BeginHorizontal(); GUILayout.Label(outputString.ToString(), Styles.labelStyle); // Push the memory size stats to the right of the screen for better alignment GUILayout.FlexibleSpace(); if (totalMemorySize != 0) { GUILayout.Label(EditorUtility.FormatBytes(totalMemorySize), Styles.labelStyle, GUILayout.MinWidth(70)); } GUILayout.EndHorizontal(); GUILayout.EndVertical(); } static void FormatSizesString(ref StringBuilder sizesString, Dictionary<LightmapSize, int> sizes) { bool first = true; foreach (KeyValuePair<LightmapSize, int> s in sizes) { sizesString.Append(first ? ": " : ", "); first = false; sizesString.Append(s.Value.ToString(CultureInfo.InvariantCulture.NumberFormat)); sizesString.Append("x"); sizesString.Append("("); sizesString.Append(s.Key.width.ToString(CultureInfo.InvariantCulture.NumberFormat)); sizesString.Append("x"); sizesString.Append(s.Key.height.ToString(CultureInfo.InvariantCulture.NumberFormat)); sizesString.Append("px"); sizesString.Append(")"); } } internal static void AddPlural(ref StringBuilder s, int n) { if (n > 0) s.Append("s"); } internal static void Summary() { if (!SelectedDenoisersSupported() && !Lightmapping.isRunning) { using (new EditorGUIUtility.IconSizeScope(Vector2.one * 14)) { GUILayout.BeginVertical(); GUILayout.Label(Styles.unsupportedDenoisersLabel, EditorStyles.wordWrappedMiniLabel); GUILayout.EndVertical(); } } bool outdatedEnvironment = RenderSettings.WasUsingAutoEnvironmentBakingWithNonDefaultSettings(); if (outdatedEnvironment && !Lightmapping.isRunning) { using (new EditorGUIUtility.IconSizeScope(Vector2.one * 14)) { GUILayout.BeginVertical(); GUILayout.Label(Styles.invalidEnvironmentLabel, EditorStyles.wordWrappedMiniLabel); GUILayout.EndVertical(); } } // Show the number of lightmaps. These are the lightmaps that will be baked or is being baked. { StringBuilder outputString = new(); string prefix = Lightmapping.isRunning ? "Generating " : string.Empty; // Gather and show light probe stats (we only have this while baking is running) if (Lightmapping.isRunning) { ulong probesCount = 0; long probeMemorySize = 0; GatherProbeStats(ref probesCount, ref probeMemorySize); if (probesCount > 0) { outputString.Append($"{prefix}{probesCount.ToString("N0")} probe"); outputString.Append(probesCount > 1 ? "s" : string.Empty); DisplaySummaryLine(outputString.ToString(), 0, 0); outputString.Clear(); } } // Gather and show baked lightmap stats bool shadowmaskMode = false; long bakedTotalMemorySize = 0; int bakedLightmapCount = 0; var bakedLightmapSizes = new Dictionary<LightmapSize, int>(); if (Lightmapping.isRunning) GatherRunningBakeLightmapStats(ref bakedLightmapCount, ref bakedTotalMemorySize, ref bakedLightmapSizes, ref shadowmaskMode); else GatherBakedLightmapStats(ref bakedLightmapCount, ref bakedTotalMemorySize, ref bakedLightmapSizes, ref shadowmaskMode); if (bakedLightmapCount > 0) { outputString.Append($"{prefix}{bakedLightmapCount.ToString("N0")} baked lightmap"); outputString.Append(bakedLightmapCount > 1 ? "s" : string.Empty); outputString.Append(shadowmaskMode ? " with Shadowmask" : string.Empty); outputString.Append(shadowmaskMode && bakedLightmapCount > 1 ? "s" : string.Empty); FormatSizesString(ref outputString, bakedLightmapSizes); DisplaySummaryLine(outputString.ToString(), bakedLightmapCount, bakedTotalMemorySize); outputString.Clear(); } // Gather and show realtime lightmap stats long rtTotalMemorySize = 0; int rtLightmapCount = 0; var rtLightmapSizes = new Dictionary<LightmapSize, int>(); GatherRealTimeLightmapStats(ref rtLightmapCount, ref rtTotalMemorySize, ref rtLightmapSizes); if (rtLightmapCount > 0) { outputString.Append($"{prefix}{rtLightmapCount.ToString("N0")} realtime lightmap"); outputString.Append(rtLightmapCount > 1 ? "s" : string.Empty); FormatSizesString(ref outputString, rtLightmapSizes); DisplaySummaryLine(outputString.ToString(), rtLightmapCount, rtTotalMemorySize); outputString.Clear(); } } GUILayout.BeginVertical(); // We show baking device and performance even when not baking, so the user can see the information after a long bake: { string deviceName = Lightmapping.GetLightmapBakeGPUDeviceName(); if (deviceName.Length > 0) GUILayout.Label("Baking device: " + deviceName, Styles.labelStyle); float mraysPerSec = Lightmapping.GetLightmapBakePerformanceTotal(); { string text; if (mraysPerSec >= 0.0) text = @$"Bake Performance: {mraysPerSec.ToString("N2")} mrays/sec"; else text = ""; GUILayout.Label(text, Styles.labelStyle); } } if (!Lightmapping.isRunning) { float bakeTime = Lightmapping.GetLightmapBakeTimeTotal(); if (bakeTime >= 0.0) { int time = (int)bakeTime; int timeH = time / 3600; time -= 3600 * timeH; int timeM = time / 60; time -= 60 * timeM; int timeS = time; int decimalPart = (int)(bakeTime % 1 * 100); GUILayout.Label($"Total Bake Time: {timeH:00}:{timeM:00}:{timeS:00}.{decimalPart:00}", Styles.labelStyle); } } GUILayout.EndVertical(); } static bool SelectedDenoisersSupported() { // Only show the error if the user is in Advanced mode if (lightingSettings.FindProperty("m_PVRFilteringMode").enumValueIndex != 2) return true; bool usingAO = lightingSettings.FindProperty("m_AO").boolValue; LightingSettings lsa; return Lightmapping.TryGetLightingSettings(out lsa) && DenoiserSupported(lsa.denoiserTypeDirect) && DenoiserSupported(lsa.denoiserTypeIndirect) && (!usingAO || (usingAO && DenoiserSupported(lsa.denoiserTypeAO))); } static bool DenoiserSupported(LightingSettings.DenoiserType denoiserType) { if (denoiserType == LightingSettings.DenoiserType.Optix) return Lightmapping.IsOptixDenoiserSupported(); if (denoiserType == LightingSettings.DenoiserType.OpenImage) return Lightmapping.IsOpenImageDenoiserSupported(); return true; } internal static LightingWindow s_Window; private static readonly double s_MraysPerSecRepaintThreshold = 0.01; internal static bool isShown => s_Window && !s_Window.docked; [MenuItem("Window/Rendering/Lighting %9", false, 1)] internal static void CreateLightingWindow() { LightingWindow window = EditorWindow.GetWindow<LightingWindow>(); window.minSize = new Vector2(390, 390); window.Show(); s_Window = window; } internal static void DestroyLightingWindow() { s_Window.Close(); s_Window = null; } } } // namespace
UnityCsReference/Editor/Mono/SceneModeWindows/LightingWindow.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/SceneModeWindows/LightingWindow.cs", "repo_id": "UnityCsReference", "token_count": 18105 }
338
// Unity 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.AnimatedValues; using UnityEditor.ShortcutManagement; using UnityEngine; namespace UnityEditor { class SceneViewMotion { const string k_TemporaryPanTool2D1 = "Scene View/Temporary Pan Tool for 2D Mode 1"; const string k_TemporaryPanTool2D2 = "Scene View/Temporary Pan Tool for 2D Mode 2"; const string k_TemporaryPanTool1 = "Scene View/Temporary Pan Tool 1"; const string k_TemporaryPanTool2 = "Scene View/Temporary Pan Tool 2"; const string k_TemporaryPanTool3 = "Scene View/Temporary Pan Tool 3"; const string k_TemporaryPanTool4 = "Scene View/Temporary Pan Tool 4"; const string k_TemporaryZoomTool1 = "Scene View/Temporary Zoom Tool 1"; const string k_TemporaryZoomTool2 = "Scene View/Temporary Zoom Tool 2"; const string k_TemporaryOrbitTool = "Scene View/Temporary Orbit Tool"; const string k_TemporaryFpsTool = "Scene View/Temporary FPS Tool"; const string k_PanFocusTool = "Scene View/Pan Focus Tool"; const string k_LockedPanTool = "Scene View/Locked Pan Tool"; const string k_LockedPanFocusTool = "Scene View/Locked Pan Focus Tool"; const string k_PanFocusEventCommandName = "SceneViewPanFocusEventCommand"; internal const string k_SetSceneViewMotionHotControlEventCommandName = "SetSceneViewMotionHotControlEventCommand"; // Also used in tests. bool m_Moving; public bool viewportsUnderMouse { get; set; } static readonly CameraFlyModeContext s_CameraFlyModeContext = new CameraFlyModeContext(); // used by Tests/EditModeAndPlayModeTests/SceneView/CameraFlyModeContextTests internal AnimVector3 m_FlySpeed = new AnimVector3(Vector3.zero); public static event Action viewToolActiveChanged; Vector3 m_Motion; Vector2 m_StartMousePosition; // The start mouse position is used for the pan focus tool. float m_FlySpeedTarget = 0f; float m_StartZoom = 0f; float m_ZoomSpeed = 0f; float m_TotalMotion = 0f; float m_FPSScrollWheelMultiplier = .01f; const float k_FlySpeedAcceleration = 1.8f; public const float k_FlySpeed = 9f; // Also used in tests. readonly int k_ViewToolID = GUIUtility.GetPermanentControlID(); readonly char[] k_TrimChars = new char[] { '0' }; public Vector3 cameraSpeed { get { return m_FlySpeed.value; } } bool m_Drag; public bool isDragging // This is used in SceneView. { get { return m_Drag; } } static bool s_ViewToolIsActive = false; public static bool viewToolIsActive => UpdateViewToolState(); [InitializeOnLoadMethod] static void RegisterShortcutContexts() => EditorApplication.delayCall += () => { ShortcutIntegration.instance.contextManager.RegisterToolContext(new SceneViewViewport()); ShortcutIntegration.instance.contextManager.RegisterToolContext(new SceneViewViewport2D()); ShortcutIntegration.instance.contextManager.RegisterToolContext(new SceneViewViewport3D()); ShortcutIntegration.instance.contextManager.RegisterToolContext(new SceneViewViewportLockedPanTool()); ShortcutIntegration.instance.contextManager.RegisterToolContext(s_CameraFlyModeContext); }; internal abstract class SceneViewContext : IShortcutContext { public SceneView window => EditorWindow.focusedWindow as SceneView; public virtual bool active => ViewHasFocus; public static bool ViewHasFocus => (EditorWindow.focusedWindow is SceneView view) && view.sceneViewMotion != null; public static bool ViewHasFocusAndViewportUnderMouse => ViewHasFocus && (EditorWindow.focusedWindow as SceneView).sceneViewMotion.viewportsUnderMouse; } [ReserveModifiers(ShortcutModifiers.Shift)] internal class SceneViewViewport : SceneViewContext { public override bool active => ViewHasFocusAndViewportUnderMouse; } [ReserveModifiers(ShortcutModifiers.Shift)] class SceneViewViewport2D : SceneViewContext { public override bool active => ViewHasFocusAndViewportUnderMouse && (window.in2DMode || window.isRotationLocked); } [ReserveModifiers(ShortcutModifiers.Shift)] class SceneViewViewport3D : SceneViewContext { public override bool active => ViewHasFocusAndViewportUnderMouse && !window.in2DMode && !window.isRotationLocked; } [ReserveModifiers(ShortcutModifiers.Shift)] class SceneViewViewportLockedPanTool : SceneViewContext { public override bool active => ViewHasFocusAndViewportUnderMouse&& Tools.current == Tool.View; } [Shortcut(k_PanFocusTool, typeof(SceneViewViewport), KeyCode.Mouse2)] [Shortcut(k_LockedPanFocusTool, typeof(SceneViewViewportLockedPanTool), KeyCode.Mouse0)] static void PanFocus(ShortcutArguments args) { // Delaying the picking to a command event is necessary because some HandleUtility methods // need to be called in an OnGUI. if (args.context is SceneViewContext ctx && ctx.window != null) ctx.window.SendEvent(EditorGUIUtility.CommandEvent(k_PanFocusEventCommandName)); } void PanFocus(Vector2 mousePos, SceneView currentSceneView, Event evt) { // Move pivot to clicked point. RaycastHit hit; if (RaycastWorld(mousePos, out hit)) { Vector3 currentPosition = currentSceneView.pivot - currentSceneView.rotation * Vector3.forward * currentSceneView.cameraDistance; float targetSize = currentSceneView.size; if (!currentSceneView.orthographic) targetSize = currentSceneView.size * Vector3.Dot(hit.point - currentPosition, currentSceneView.rotation * Vector3.forward) / currentSceneView.cameraDistance; currentSceneView.LookAt(hit.point, currentSceneView.rotation, targetSize); } evt.Use(); } [ClutchShortcut(k_TemporaryPanTool2D1, typeof(SceneViewViewport2D), KeyCode.Mouse1)] [ClutchShortcut(k_TemporaryPanTool2D2, typeof(SceneViewViewport2D), KeyCode.Mouse0, ShortcutModifiers.Alt)] [ClutchShortcut(k_TemporaryPanTool1, typeof(SceneViewViewport), KeyCode.Mouse2)] [ClutchShortcut(k_TemporaryPanTool2, typeof(SceneViewViewport), KeyCode.Mouse2, ShortcutModifiers.Alt)] [ClutchShortcut(k_TemporaryPanTool3, typeof(SceneViewViewport), KeyCode.Mouse0, ShortcutModifiers.Action | ShortcutModifiers.Alt)] [ClutchShortcut(k_TemporaryPanTool4, typeof(SceneViewViewport), KeyCode.Mouse2, ShortcutModifiers.Action | ShortcutModifiers.Alt)] [ClutchShortcut(k_LockedPanTool, typeof(SceneViewViewportLockedPanTool), KeyCode.Mouse0)] static void TemporaryPan(ShortcutArguments args) { if (args.context is SceneViewContext ctx && ctx.window != null && ctx.window.sceneViewMotion != null) ctx.window.sceneViewMotion.HandleSceneViewMotionTool(args, ViewTool.Pan, ctx.window); } [ClutchShortcut(k_TemporaryZoomTool1, typeof(SceneViewViewport), KeyCode.Mouse1, ShortcutModifiers.Alt)] [ClutchShortcut(k_TemporaryZoomTool2, typeof(SceneViewViewport), KeyCode.Mouse1, ShortcutModifiers.Action | ShortcutModifiers.Alt)] static void TemporaryZoom(ShortcutArguments args) { if (args.context is SceneViewContext ctx && ctx.window != null && ctx.window.sceneViewMotion != null) ctx.window.sceneViewMotion.HandleSceneViewMotionTool(args, ViewTool.Zoom, ctx.window); } [ClutchShortcut(k_TemporaryOrbitTool, typeof(SceneViewViewport3D), KeyCode.Mouse0, ShortcutModifiers.Alt)] static void TemporaryOrbit(ShortcutArguments args) { if (args.context is SceneViewContext ctx && ctx.window != null && ctx.window.sceneViewMotion != null) ctx.window.sceneViewMotion.HandleSceneViewMotionTool(args, ViewTool.Orbit, ctx.window); } void HandleSceneViewMotionTool(ShortcutArguments args, ViewTool viewTool, SceneView view) { if (args.stage == ShortcutStage.Begin && GUIUtility.hotControl == 0) StartSceneViewMotionTool(viewTool, view); else if (args.stage == ShortcutStage.End && Tools.s_LockedViewTool == viewTool) CompleteSceneViewMotionTool(); } [ClutchShortcut(k_TemporaryFpsTool, typeof(SceneViewViewport3D), typeof(CameraFlyModeContext), KeyCode.Mouse1)] static void TemporaryFPS(ShortcutArguments args) { if (!(args.context is SceneViewViewport3D context) || context.window == null || context.window.sceneViewMotion == null) return; if (args.stage == ShortcutStage.Begin && GUIUtility.hotControl == 0) { s_CameraFlyModeContext.window = context.window; context.window.sceneViewMotion.StartSceneViewMotionTool(ViewTool.FPS, context.window); } else if (args.stage == ShortcutStage.End && Tools.s_LockedViewTool == ViewTool.FPS) { s_CameraFlyModeContext.window = null; context.window.sceneViewMotion.CompleteSceneViewMotionTool(); } } // slightly different logic for arrow keys - forward and backward axes are swapped for up and down when in // orthographic or 2D mode static void SetCameraMoveDirectionArrow(ShortcutArguments args, SceneInputAxis axis) { if (!(args.context is SceneViewContext ctx) || !(ctx.window is SceneView view)) return; if (args.stage == ShortcutStage.Begin) view.sceneViewMotion.StartSceneViewMotionTool(ViewTool.FPS, view); else if (args.stage == ShortcutStage.End) view.sceneViewMotion.CompleteSceneViewMotionTool(); if (view.in2DMode || view.orthographic) { axis = axis switch { SceneInputAxis.Forward => SceneInputAxis.Up, SceneInputAxis.Backward => SceneInputAxis.Down, _ => axis }; } SceneNavigationInput.input[axis] = args.stage == ShortcutStage.Begin; ctx.window.Repaint(); } [ClutchShortcut("3D Viewport/Fly Mode Forward (Alt)", typeof(SceneViewViewport), KeyCode.UpArrow)] static void WalkForwardArrow(ShortcutArguments args) => SetCameraMoveDirectionArrow(args, SceneInputAxis.Forward); [ClutchShortcut("3D Viewport/Fly Mode Backward (Alt)", typeof(SceneViewViewport), KeyCode.DownArrow)] static void WalkBackwardArrow(ShortcutArguments args) => SetCameraMoveDirectionArrow(args, SceneInputAxis.Backward); [ClutchShortcut("3D Viewport/Fly Mode Left (Alt)", typeof(SceneViewViewport), KeyCode.LeftArrow)] static void WalkLeftArrow(ShortcutArguments args) => SetCameraMoveDirectionArrow(args, SceneInputAxis.Left); [ClutchShortcut("3D Viewport/Fly Mode Right (Alt)", typeof(SceneViewViewport), KeyCode.RightArrow)] static void WalkRightArrow(ShortcutArguments args) => SetCameraMoveDirectionArrow(args, SceneInputAxis.Right); static void SetInputVector(ShortcutArguments args, SceneInputAxis axis) { SceneNavigationInput.input[axis] = args.stage == ShortcutStage.Begin; var context = (CameraFlyModeContext) args.context; context.window.Repaint(); } [ClutchShortcut("3D Viewport/Fly Mode Forward", typeof(CameraFlyModeContext), KeyCode.W)] [FormerlyPrefKeyAs("View/FPS Forward", "w")] static void WalkForward(ShortcutArguments args) => SetInputVector(args, SceneInputAxis.Forward); [ClutchShortcut("3D Viewport/Fly Mode Backward", typeof(CameraFlyModeContext), KeyCode.S)] [FormerlyPrefKeyAs("View/FPS Back", "s")] static void WalkBackward(ShortcutArguments args) => SetInputVector(args, SceneInputAxis.Backward); [ClutchShortcut("3D Viewport/Fly Mode Left", typeof(CameraFlyModeContext), KeyCode.A)] [FormerlyPrefKeyAs("View/FPS Strafe Left", "a")] static void WalkLeft(ShortcutArguments args) => SetInputVector(args, SceneInputAxis.Left); [ClutchShortcut("3D Viewport/Fly Mode Right", typeof(CameraFlyModeContext), KeyCode.D)] [FormerlyPrefKeyAs("View/FPS Strafe Right", "d")] static void WalkRight(ShortcutArguments args) => SetInputVector(args, SceneInputAxis.Right); [ClutchShortcut("3D Viewport/Fly Mode Up", typeof(CameraFlyModeContext), KeyCode.E)] [FormerlyPrefKeyAs("View/FPS Strafe Up", "e")] static void WalkUp(ShortcutArguments args) => SetInputVector(args, SceneInputAxis.Up); [ClutchShortcut("3D Viewport/Fly Mode Down", typeof(CameraFlyModeContext), KeyCode.Q)] [FormerlyPrefKeyAs("View/FPS Strafe Down", "q")] static void WalkDown(ShortcutArguments args) => SetInputVector(args, SceneInputAxis.Down); void StartSceneViewMotionTool(ViewTool viewTool, SceneView view) { Tools.s_LockedViewTool = Tools.viewTool = viewTool; // Set up zoom parameters m_StartZoom = view.size; m_ZoomSpeed = Mathf.Max(Mathf.Abs(m_StartZoom), .3f); m_TotalMotion = 0; if (Toolbar.get) Toolbar.get.Repaint(); EditorGUIUtility.SetWantsMouseJumping(1); UpdateViewToolState(); // The hot control needs to be set in an OnGUI call. view.SendEvent(EditorGUIUtility.CommandEvent(k_SetSceneViewMotionHotControlEventCommandName)); } public void CompleteSceneViewMotionTool() { Tools.viewTool = ViewTool.Pan; Tools.s_LockedViewTool = ViewTool.None; GUIUtility.hotControl = 0; if (viewToolActiveChanged != null) viewToolActiveChanged.Invoke(); Tools.s_ButtonDown = -1; if (Toolbar.get) Toolbar.get.Repaint(); EditorGUIUtility.SetWantsMouseJumping(0); m_Drag = false; } public void DoViewTool() { var view = SceneView.lastActiveSceneView; if (view == null) return; // In FPS mode we update the pivot for Orbit mode (see below and inside HandleMouseDrag) if (Tools.s_LockedViewTool == ViewTool.FPS) view.FixNegativeSize(); SceneNavigationInput.Update(); if (SceneNavigationInput.moving) view.viewIsLockedToObject = false; m_Motion = SceneNavigationInput.currentInputVector; // If a different mouse button is clicked while the current mouse button is held down, // reset the hot control to the correct id. if (GUIUtility.hotControl == 0 && Tools.s_LockedViewTool != ViewTool.None) GUIUtility.hotControl = k_ViewToolID; var evt = Event.current; switch (evt.GetTypeForControl(k_ViewToolID)) { case EventType.ScrollWheel: // Default to zooming to mouse position in 2D mode without alt. HandleScrollWheel(view, view.in2DMode == evt.alt); break; case EventType.MouseDown: if (GUIUtility.hotControl == 0) m_StartMousePosition = evt.mousePosition; break; case EventType.MouseUp: if (GUIUtility.hotControl == k_ViewToolID) GUIUtility.hotControl = 0; break; case EventType.KeyDown: // Escape HandleKeyDown(); break; case EventType.MouseDrag: HandleMouseDrag(view); break; case EventType.Layout: if (GUIUtility.hotControl == k_ViewToolID || m_FlySpeed.isAnimating || m_Moving) { view.pivot = view.pivot + view.rotation * GetMovementDirection(view); view.Repaint(); } break; case EventType.ExecuteCommand: if (evt.commandName == k_PanFocusEventCommandName) { PanFocus(m_StartMousePosition, view, evt); } else if (evt.commandName == k_SetSceneViewMotionHotControlEventCommandName) { GUIUtility.hotControl = k_ViewToolID; evt.Use(); } break; } } static bool UpdateViewToolState() { bool shouldBeActive = Tools.s_LockedViewTool != ViewTool.None || Tools.current == Tool.View; if (shouldBeActive != s_ViewToolIsActive) { s_ViewToolIsActive = shouldBeActive; if (viewToolActiveChanged != null) viewToolActiveChanged.Invoke(); } return s_ViewToolIsActive; } Vector3 GetMovementDirection(SceneView view) { m_Moving = m_Motion.sqrMagnitude > 0f; var deltaTime = SceneNavigationInput.deltaTime; var speedModifier = view.cameraSettings.speed; if (Event.current.shift) speedModifier *= 5f; if (m_Moving) { if (view.cameraSettings.accelerationEnabled) m_FlySpeedTarget = m_FlySpeedTarget < Mathf.Epsilon ? k_FlySpeed : m_FlySpeedTarget * Mathf.Pow(k_FlySpeedAcceleration, deltaTime); else m_FlySpeedTarget = k_FlySpeed; } else { m_FlySpeedTarget = 0f; } if (view.cameraSettings.easingEnabled) { m_FlySpeed.speed = 1f / view.cameraSettings.easingDuration; m_FlySpeed.target = m_Motion.normalized * m_FlySpeedTarget * speedModifier; } else { m_FlySpeed.value = m_Motion.normalized * m_FlySpeedTarget * speedModifier; } return m_FlySpeed.value * deltaTime; } public void ResetMotion() { m_Motion = Vector3.zero; m_FlySpeed.value = Vector3.zero; m_Moving = false; } bool RaycastWorld(Vector2 position, out RaycastHit hit) { hit = new RaycastHit(); GameObject picked = HandleUtility.PickGameObject(position, false); if (!picked) return false; Ray mouseRay = HandleUtility.GUIPointToWorldRay(position); // Loop through all meshes and find the RaycastHit closest to the ray origin. MeshFilter[] meshFil = picked.GetComponentsInChildren<MeshFilter>(); float minT = Mathf.Infinity; foreach (MeshFilter mf in meshFil) { Mesh mesh = mf.sharedMesh; if (!mesh || !mesh.canAccess) continue; RaycastHit localHit; if (HandleUtility.IntersectRayMesh(mouseRay, mesh, mf.transform.localToWorldMatrix, out localHit)) { if (localHit.distance < minT) { hit = localHit; minT = hit.distance; } } } if (minT == Mathf.Infinity) { // If we didn't find any surface based on meshes, try with colliders. Collider[] colliders = picked.GetComponentsInChildren<Collider>(); foreach (Collider col in colliders) { RaycastHit localHit; if (col.Raycast(mouseRay, out localHit, Mathf.Infinity)) { if (localHit.distance < minT) { hit = localHit; minT = hit.distance; } } } } if (minT == Mathf.Infinity) { // If we didn't hit any mesh or collider surface, then use the transform position projected onto the ray. hit.point = Vector3.Project(picked.transform.position - mouseRay.origin, mouseRay.direction) + mouseRay.origin; } return true; } private void OrbitCameraBehavior(SceneView view) { Event evt = Event.current; view.FixNegativeSize(); Quaternion rotation = view.m_Rotation.target; rotation = Quaternion.AngleAxis(evt.delta.y * .003f * Mathf.Rad2Deg, rotation * Vector3.right) * rotation; rotation = Quaternion.AngleAxis(evt.delta.x * .003f * Mathf.Rad2Deg, Vector3.up) * rotation; if (view.size < 0) { view.pivot = view.camera.transform.position; view.size = 0; } view.rotation = rotation; } private void HandleMouseDrag(SceneView view) { if (!Event.current.isMouse || GUIUtility.hotControl != k_ViewToolID) return; m_Drag = true; Event evt = Event.current; switch (Tools.s_LockedViewTool) { case ViewTool.Orbit: { if (!view.in2DMode && !view.isRotationLocked) { OrbitCameraBehavior(view); // todo gizmo update label // view.m_OrientationGizmo.UpdateGizmoLabel(view, view.rotation * Vector3.forward, view.m_Ortho.target); } } break; case ViewTool.FPS: { if (!view.in2DMode && !view.isRotationLocked) { if (!view.orthographic) { view.viewIsLockedToObject = false; // The reason we calculate the camera position from the pivot, rotation and distance, // rather than just getting it from the camera transform is that the camera transform // is the *output* of camera motion calculations. It shouldn't be input and output at the same time, // otherwise we easily get accumulated error. // We did get accumulated error before when we did this - the camera would continuously move slightly in FPS mode // even when not holding down any arrow/ASDW keys or moving the mouse. Vector3 camPos = view.pivot - view.rotation * Vector3.forward * view.cameraDistance; // Normal FPS camera behavior Quaternion rotation = view.rotation; rotation = Quaternion.AngleAxis(evt.delta.y * .003f * Mathf.Rad2Deg, rotation * Vector3.right) * rotation; rotation = Quaternion.AngleAxis(evt.delta.x * .003f * Mathf.Rad2Deg, Vector3.up) * rotation; view.rotation = rotation; view.pivot = camPos + rotation * Vector3.forward * view.cameraDistance; } else { // We want orbit behavior in orthograpic when using FPS OrbitCameraBehavior(view); } // todo gizmo update label // view.m_OrientationGizmo.UpdateGizmoLabel(view, view.rotation * Vector3.forward, view.m_Ortho.target); } } break; case ViewTool.Pan: { view.viewIsLockedToObject = false; view.FixNegativeSize(); Vector2 screenDelta = Event.current.delta; Vector3 worldDelta = ScreenToWorldDistance(view, new Vector2(-screenDelta.x, screenDelta.y)); if (evt.shift) worldDelta *= 4; view.pivot += worldDelta; } break; case ViewTool.Zoom: { float zoomDelta = HandleUtility.niceMouseDeltaZoom * (evt.shift ? 9 : 3); if (view.orthographic) { view.size = Mathf.Max(.0001f, view.size * (1 + zoomDelta * .001f)); } else { m_TotalMotion += zoomDelta; if (m_TotalMotion < 0) view.size = m_StartZoom * (1 + m_TotalMotion * .001f); else view.size = view.size + zoomDelta * m_ZoomSpeed * .003f; } } break; } evt.Use(); } public Vector3 ScreenToWorldDistance(SceneView view, Vector2 delta) { // Ensures that the camera matrix doesn't end up with gigantic or minuscule values in the clip to world matrix const float k_MaxCameraSizeForWorldToScreen = 2.5E+7f; // store original camera and view values var camera = view.camera; var near = camera.nearClipPlane; var far = camera.farClipPlane; var pos = camera.transform.position; var rotation = camera.transform.rotation; var size = view.size; // set camera transform and clip values to safe values view.size = Mathf.Min(view.size, k_MaxCameraSizeForWorldToScreen); // account for the distance clamping var scale = size / view.size; var clip = view.GetDynamicClipPlanes(); view.camera.nearClipPlane = clip.x; view.camera.farClipPlane = clip.y; view.camera.transform.position = Vector3.zero; view.camera.transform.rotation = Quaternion.identity; // do the distance calculation Vector3 pivotWorld = camera.transform.rotation * new Vector3(0f, 0f, view.cameraDistance); Vector3 pivotScreen = camera.WorldToScreenPoint(pivotWorld); pivotScreen += new Vector3(delta.x, delta.y, 0); Vector3 worldDelta = camera.ScreenToWorldPoint(pivotScreen) - pivotWorld; // We're clearing z here as ScreenToWorldPoint(WorldToScreenPoint(worldPoint)) does not always result in the exact same worldPoint that was inputed (for example, when camera is ortho). // https://jira.unity3d.com/browse/UUM-56425 worldDelta.z = 0f; worldDelta = rotation * worldDelta; worldDelta *= EditorGUIUtility.pixelsPerPoint * scale; // restore original cam and scene values view.size = size; view.camera.nearClipPlane = near; view.camera.farClipPlane = far; view.camera.transform.position = pos; view.camera.transform.rotation = rotation; return worldDelta; } // This can't be modified into a shortcut because Escape is an invalid key code binding. private void HandleKeyDown() { if (Event.current.keyCode == KeyCode.Escape && GUIUtility.hotControl == k_ViewToolID) CompleteSceneViewMotionTool(); } void HandleScrollWheel(SceneView view, bool zoomTowardsCenter) { var evt = Event. current; var scrollDelta = Event.current.delta.y; if (Tools.s_LockedViewTool == ViewTool.FPS) { // On MacOS, scrolling with Shift down is interpreted as a horizontal scroll at the 0S level. // On Window, due to UUM-43552 a change was done at the editor's win platform layer to mimic macOS behaviour and swap x/y deltas. if ((evt.modifiers & EventModifiers.Shift) != 0 && (Application.platform == RuntimePlatform.OSXEditor || Application.platform == RuntimePlatform.WindowsEditor)) scrollDelta = Event.current.delta.x; float scrollWheelDelta = scrollDelta * m_FPSScrollWheelMultiplier; view.cameraSettings.speedNormalized -= scrollWheelDelta; float cameraSettingsSpeed = view.cameraSettings.speed; string cameraSpeedDisplayValue = cameraSettingsSpeed.ToString( cameraSettingsSpeed < 0.0001f ? "F6" : cameraSettingsSpeed < 0.001f ? "F5" : cameraSettingsSpeed < 0.01f ? "F4" : cameraSettingsSpeed < 0.1f ? "F3" : cameraSettingsSpeed < 10f ? "F2" : "F0"); if (cameraSettingsSpeed < 0.1f) cameraSpeedDisplayValue = cameraSpeedDisplayValue.Trim(k_TrimChars); GUIContent cameraSpeedContent = EditorGUIUtility.TempContent(string.Format("{0}{1}", cameraSpeedDisplayValue, view.cameraSettings.accelerationEnabled ? "x" : "")); view.ShowNotification(cameraSpeedContent, .5f); } else { // When in camera view mode, change the FoV of the selected camera instead. if (view.viewpoint.hasActiveViewpoint) { view.viewpoint.HandleScrollWheel(view); return; } float targetSize; if (!view.orthographic) { float relativeDelta = Mathf.Abs(view.size) * scrollDelta * .015f; const float k_MinZoomDelta = .0001f; if (relativeDelta > 0 && relativeDelta < k_MinZoomDelta) relativeDelta = k_MinZoomDelta; else if (relativeDelta < 0 && relativeDelta > -k_MinZoomDelta) relativeDelta = -k_MinZoomDelta; targetSize = view.size + relativeDelta; } else { targetSize = Mathf.Abs(view.size) * (scrollDelta * .015f + 1.0f); } var initialDistance = view.cameraDistance; if (!(float.IsNaN(targetSize) || float.IsInfinity(targetSize))) { targetSize = Mathf.Min(SceneView.k_MaxSceneViewSize, targetSize); view.size = targetSize; } if (!zoomTowardsCenter && Mathf.Abs(view.cameraDistance) < 1.0e7f) { var percentage = 1f - (view.cameraDistance / initialDistance); var mouseRay = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); var mousePivot = mouseRay.origin + mouseRay.direction * initialDistance; var pivotVector = mousePivot - view.pivot; view.pivot += pivotVector * percentage; } } Event.current.Use(); } } } //namespace
UnityCsReference/Editor/Mono/SceneView/SceneViewMotion.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/SceneView/SceneViewMotion.cs", "repo_id": "UnityCsReference", "token_count": 15466 }
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.Runtime.InteropServices; using UnityEngine; using UnityEngine.Scripting; namespace UnityEditor { [RequiredByNativeCode] [StructLayout(LayoutKind.Sequential)] internal struct MonoReloadableIntPtr { internal IntPtr m_IntPtr; } [RequiredByNativeCode] [StructLayout(LayoutKind.Sequential)] internal struct MonoReloadableIntPtrClear { internal IntPtr m_IntPtr; } internal sealed class ScriptReloadProperties : ScriptableObject { public bool EditorGUI_IsActuallEditing; public int EditorGUI_TextEditor_cursorIndex; public int EditorGUI_TextEditor_selectIndex; public int EditorGUI_TextEditor_controlID; public bool EditorGUI_TextEditor_hasHorizontalCursorPos; public Vector2 EditorGUI_TextEditor_scrollOffset; public bool EditorGUI_TextEditor_hasFocus; public Vector2 EditorGUI_TextEditor_graphicalCursorPos; public string EditorGUI_TextEditor_content; public string EditorGUI_Current_Editing_String; public int EditorGUI_DelayedTextEditor_cursorIndex; public int EditorGUI_DelayedTextEditor_selectIndex; public int EditorGUI_DelayedTextEditor_controlID; public bool EditorGUI_DelayedTextEditor_hasHorizontalCursorPos; public Vector2 EditorGUI_DelayedTextEditor_scrollOffset; public bool EditorGUI_DelayedTextEditor_hasFocus; public Vector2 EditorGUI_DelayedTextEditor_graphicalCursorPos; public string EditorGUI_DelayedTextEditor_content; public string EditorGUI_DelayedControlThatHadFocusValue; [RequiredByNativeCode] static ScriptReloadProperties Store() { ScriptReloadProperties obj = CreateInstance<ScriptReloadProperties>(); obj.hideFlags = HideFlags.HideAndDontSave; obj.ManagedStore(); return obj; } [RequiredByNativeCode] static void Load(ScriptReloadProperties properties) { properties.ManagedLoad(); } private void ManagedStore() { EditorGUI_IsActuallEditing = EditorGUI.RecycledTextEditor.s_ActuallyEditing; EditorGUI_TextEditor_cursorIndex = EditorGUI.s_RecycledEditor.cursorIndex; EditorGUI_TextEditor_selectIndex = EditorGUI.s_RecycledEditor.selectIndex; EditorGUI_TextEditor_controlID = EditorGUI.s_RecycledEditor.controlID; EditorGUI_TextEditor_hasHorizontalCursorPos = EditorGUI.s_RecycledEditor.hasHorizontalCursor; EditorGUI_TextEditor_scrollOffset = EditorGUI.s_RecycledEditor.scrollOffset; EditorGUI_TextEditor_hasFocus = EditorGUI.s_RecycledEditor.m_HasFocus; EditorGUI_TextEditor_graphicalCursorPos = EditorGUI.s_RecycledEditor.graphicalCursorPos; EditorGUI_TextEditor_content = EditorGUI.s_RecycledEditor.text; EditorGUI_Current_Editing_String = EditorGUI.s_RecycledCurrentEditingString; EditorGUI_DelayedTextEditor_cursorIndex = EditorGUI.s_DelayedTextEditor.cursorIndex; EditorGUI_DelayedTextEditor_selectIndex = EditorGUI.s_DelayedTextEditor.selectIndex; EditorGUI_DelayedTextEditor_controlID = EditorGUI.s_DelayedTextEditor.controlID; EditorGUI_DelayedTextEditor_hasHorizontalCursorPos = EditorGUI.s_DelayedTextEditor.hasHorizontalCursor; EditorGUI_DelayedTextEditor_scrollOffset = EditorGUI.s_DelayedTextEditor.scrollOffset; EditorGUI_DelayedTextEditor_hasFocus = EditorGUI.s_DelayedTextEditor.m_HasFocus; EditorGUI_DelayedTextEditor_graphicalCursorPos = EditorGUI.s_DelayedTextEditor.graphicalCursorPos; EditorGUI_DelayedTextEditor_content = EditorGUI.s_DelayedTextEditor.text; EditorGUI_DelayedControlThatHadFocusValue = EditorGUI.s_DelayedTextEditor.controlThatHadFocusValue; } private void ManagedLoad() { EditorGUI.s_RecycledEditor.text = EditorGUI_TextEditor_content; EditorGUI.s_RecycledCurrentEditingString = EditorGUI_Current_Editing_String; EditorGUI.RecycledTextEditor.s_ActuallyEditing = EditorGUI_IsActuallEditing; EditorGUI.s_RecycledEditor.cursorIndex = EditorGUI_TextEditor_cursorIndex; EditorGUI.s_RecycledEditor.selectIndex = EditorGUI_TextEditor_selectIndex; EditorGUI.s_RecycledEditor.controlID = EditorGUI_TextEditor_controlID; EditorGUI.s_RecycledEditor.hasHorizontalCursor = EditorGUI_TextEditor_hasHorizontalCursorPos; EditorGUI.s_RecycledEditor.scrollOffset = EditorGUI_TextEditor_scrollOffset; EditorGUI.s_RecycledEditor.m_HasFocus = EditorGUI_TextEditor_hasFocus; EditorGUI.s_RecycledEditor.graphicalCursorPos = EditorGUI_TextEditor_graphicalCursorPos; EditorGUI.s_DelayedTextEditor.text = EditorGUI_DelayedTextEditor_content; EditorGUI.s_DelayedTextEditor.cursorIndex = EditorGUI_DelayedTextEditor_cursorIndex; EditorGUI.s_DelayedTextEditor.selectIndex = EditorGUI_DelayedTextEditor_selectIndex; EditorGUI.s_DelayedTextEditor.controlID = EditorGUI_DelayedTextEditor_controlID; EditorGUI.s_DelayedTextEditor.hasHorizontalCursor = EditorGUI_DelayedTextEditor_hasHorizontalCursorPos; EditorGUI.s_DelayedTextEditor.scrollOffset = EditorGUI_DelayedTextEditor_scrollOffset; EditorGUI.s_DelayedTextEditor.m_HasFocus = EditorGUI_DelayedTextEditor_hasFocus; EditorGUI.s_DelayedTextEditor.graphicalCursorPos = EditorGUI_DelayedTextEditor_graphicalCursorPos; EditorGUI.s_DelayedTextEditor.controlThatHadFocusValue = EditorGUI_DelayedControlThatHadFocusValue; } } }
UnityCsReference/Editor/Mono/ScriptReloadProperties.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/ScriptReloadProperties.cs", "repo_id": "UnityCsReference", "token_count": 2306 }
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; using System.Collections.Generic; using System.IO; using UnityEditor.Compilation; using UnityEditor.Utils; using UnityEngine; namespace UnityEditor.Scripting.Compilers { internal static class ScriptCompilerBase { public class CompilerOption { public string Arg; public string Value; } } internal static class MicrosoftResponseFileParser { static readonly char[] CompilerOptionArgumentSeperators = {';', ','}; public static List<ScriptCompilerBase.CompilerOption> GetCompilerOptions(string responseFileContent) { var compilerOptions = new List<ScriptCompilerBase.CompilerOption>(); var responseFileStrings = ResponseFileTextToStrings(responseFileContent); foreach (var line in responseFileStrings) { int idx = line.IndexOf(':'); string arg, value; if (idx == -1) { arg = line; value = ""; } else { arg = line.Substring(0, idx); value = line.Substring(idx + 1); } if (!string.IsNullOrEmpty(arg) && arg[0] == '-') arg = '/' + arg.Substring(1); compilerOptions.Add(new ScriptCompilerBase.CompilerOption {Arg = arg, Value = value}); } return compilerOptions; } public static List<string> GetDefines(List<ScriptCompilerBase.CompilerOption> compilerOptions) { List<string> defines = new List<string>(compilerOptions.Count); foreach (var compilerOption in compilerOptions) { if (IsDefine(compilerOption)) { defines.AddRange(GetOptionDefines(compilerOption)); } } return defines; } private static string[] GetOptionDefines(ScriptCompilerBase.CompilerOption compilerOption) { return compilerOption.Value.Split(CompilerOptionArgumentSeperators); } public static string GetResponseFileContent(string projectDirectory, string path) { var responseFilePath = Paths.ConvertSeparatorsToUnity(path); var projectDirectoryUnitySeperators = Paths.ConvertSeparatorsToUnity(projectDirectory); var relativeResponseFilePath = Paths.GetPathRelativeToProjectDirectory(responseFilePath); var responseFile = AssetDatabase.LoadAssetAtPath<TextAsset>(relativeResponseFilePath); if (responseFile) { return responseFile.text; } if (File.Exists(responseFilePath)) { return File.ReadAllText(responseFilePath); } return string.Empty; } public static ResponseFileData ParseResponseFileFromFile( string responseFilePath, string projectDirectory, string[] systemReferenceDirectories) { responseFilePath = Paths.ConvertSeparatorsToUnity(responseFilePath); projectDirectory = Paths.ConvertSeparatorsToUnity(projectDirectory); var relativeResponseFilePath = Paths.GetPathRelativeToProjectDirectory(responseFilePath); if (File.Exists(responseFilePath)) { var responseFileText = File.ReadAllText(responseFilePath); return ParseResponseFileText( responseFileText, responseFilePath, projectDirectory, systemReferenceDirectories); } else { var empty = new ResponseFileData { Defines = new string[0], FullPathReferences = new string[0], Unsafe = false, Errors = new string[0], OtherArguments = new string[0], }; return empty; } } static ResponseFileData ParseResponseFileText( string fileContent, string fileName, string projectDirectory, string[] systemReferenceDirectories) { List<ScriptCompilerBase.CompilerOption> compilerOptions = GetCompilerOptions(fileContent); var responseArguments = new List<string>(); var defines = new List<string>(); var references = new List<string>(); bool unsafeDefined = false; var errors = new List<string>(); foreach (var option in compilerOptions) { var arg = option.Arg; var value = option.Value; if (IsDefine(option)) { defines.AddRange(GetOptionDefines(option)); } else if (IsReference(option)) { if (TryGetReference(option, fileName, projectDirectory, systemReferenceDirectories, ref errors, out var result)) { references.Add(result); } } else if (IsSetUnsafe(option)) { unsafeDefined = true; } else if (IsUnsetUnsafe(option)) { unsafeDefined = false; } else { var valueWithColon = value.Length == 0 ? "" : ":" + SafeArgString(value); responseArguments.Add(arg + valueWithColon); } } var responseFileData = new ResponseFileData { Defines = defines.ToArray(), FullPathReferences = references.ToArray(), Unsafe = unsafeDefined, Errors = errors.ToArray(), OtherArguments = responseArguments.ToArray(), }; return responseFileData; } private static string SafeArgString(string text) { return ContainsWhiteSpace(text) ? $"\"{text}\"" : text; } private static bool ContainsWhiteSpace(string text) { for (int i = 0; i < text.Length; i++) { if (char.IsWhiteSpace(text[i])) return true; } return false; } private static bool IsDefine(ScriptCompilerBase.CompilerOption compilerOption) { if (string.IsNullOrEmpty(compilerOption?.Arg)) { return false; } return compilerOption.Arg.Equals("/d", StringComparison.Ordinal) || compilerOption.Arg.Equals("/define", StringComparison.Ordinal); } private static bool IsReference(ScriptCompilerBase.CompilerOption compilerOption) { if (string.IsNullOrEmpty(compilerOption?.Arg)) { return false; } return compilerOption.Arg.Equals("/r", StringComparison.Ordinal) || compilerOption.Arg.Equals("/reference", StringComparison.Ordinal); } private static bool IsSetUnsafe(ScriptCompilerBase.CompilerOption compilerOption) { if (string.IsNullOrEmpty(compilerOption?.Arg)) { return false; } return compilerOption.Arg.Equals("/unsafe", StringComparison.Ordinal) || compilerOption.Arg.Equals("/unsafe+", StringComparison.Ordinal); } private static bool IsUnsetUnsafe(ScriptCompilerBase.CompilerOption compilerOption) { if (string.IsNullOrEmpty(compilerOption?.Arg)) { return false; } return compilerOption.Arg.Equals("/unsafe", StringComparison.Ordinal) || compilerOption.Arg.Equals("/unsafe+", StringComparison.Ordinal); } private static bool TryGetReference(ScriptCompilerBase.CompilerOption option, string fileName, string projectDirectory, string[] systemReferenceDirectories, ref List<string> errors, out string result) { result = null; var value = option.Value; if (value.Length == 0) { errors.Add("No value set for reference"); return false; // break; } string[] refs = value.Split(CompilerOptionArgumentSeperators); if (refs.Length != 1) { errors.Add("Cannot specify multiple aliases using single /reference option"); return false; // break; } var reference = refs[0]; if (reference.Length == 0) { return false; // continue; } int index = reference.IndexOf('='); var responseReference = index > -1 ? reference.Substring(index + 1) : reference; var fullPathReference = responseReference; bool isRooted = Path.IsPathRooted(responseReference); if (!isRooted) { foreach (var directory in systemReferenceDirectories) { var systemReferencePath = Paths.Combine(directory, responseReference); if (File.Exists(systemReferencePath)) { fullPathReference = systemReferencePath; isRooted = true; break; } } var userPath = Paths.Combine(projectDirectory, responseReference); if (File.Exists(userPath)) { fullPathReference = userPath; isRooted = true; } } if (!isRooted) { errors.Add( $"{fileName}: not parsed correctly: {responseReference} could not be found as a system library.\n" + "If this was meant as a user reference please provide the relative path from project root (parent of the Assets folder) in the response file."); return false; // continue; } responseReference = fullPathReference.Replace('\\', '/'); result = responseReference; return true; } // From: // https://github.com/mono/mono/blob/c106cdc775792ceedda6da58de7471f9f5c0b86c/mcs/mcs/settings.cs // // settings.cs: All compiler settings // // Author: Miguel de Icaza ([email protected]) // Ravi Pratap ([email protected]) // Marek Safar ([email protected]) // // // Dual licensed under the terms of the MIT X11 or GNU GPL // // Copyright 2001 Ximian, Inc (http://www.ximian.com) // Copyright 2004-2008 Novell, Inc // Copyright 2011 Xamarin, Inc (http://www.xamarin.com) static string[] ResponseFileTextToStrings(string responseFileText) { var args = new List<string>(); var sb = new System.Text.StringBuilder(); var textLines = responseFileText.Split('\n', '\r'); foreach (var line in textLines) { int t = line.Length; for (int i = 0; i < t; i++) { char c = line[i]; if (c == '"' || c == '\'') { char end = c; for (i++; i < t; i++) { c = line[i]; if (c == end) break; sb.Append(c); } } else if (c == ' ') { if (sb.Length > 0) { args.Add(sb.ToString()); sb.Length = 0; } } else if (c == '#') { // skip the rest of the line if it is the start of a comment break; } else sb.Append(c); } if (sb.Length > 0) { args.Add(sb.ToString()); sb.Length = 0; } } return args.ToArray(); } } }
UnityCsReference/Editor/Mono/Scripting/Compilers/MicrosoftResponseFileParser.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Scripting/Compilers/MicrosoftResponseFileParser.cs", "repo_id": "UnityCsReference", "token_count": 6808 }
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.Linq; using System.Text.RegularExpressions; using Bee.BeeDriver; using Bee.BinLog; using Bee.Serialization; using NiceIO; using ScriptCompilationBuildProgram.Data; using UnityEditor.Scripting.Compilers; namespace UnityEditor.Scripting.ScriptCompilation { static class PotentiallyUpdatableErrorMessages { public static bool IsAnyPotentiallyUpdatable(CompilerMessage[] messages, NodeFinishedMessage nodeResult, ObjectsFromDisk dataFromBuildProgram) { var matches = messages.Select(m => MicrosoftCSharpCompilerOutputParser.sCompilerOutput.Match(m.message)).Where(m => m.Success).ToArray(); var typeNames = matches.Select(MissingTypeNameFor).Where(t => t != null).ToArray(); if (!typeNames.Any()) return false; var assemblyData = Helpers.FindOutputDataAssemblyInfoFor(nodeResult, dataFromBuildProgram); var lines = new NPath(assemblyData.MovedFromExtractorFile).ReadAllLines(); return typeNames.Any(t => lines.Contains(t)); } private static readonly Regex sMissingMember = new Regex(@"[^'`]*['`](?<type_name>[^']+)'[^'`]+['`](?<member_name>[^']+)'", RegexOptions.ExplicitCapture | RegexOptions.Compiled); private static readonly Regex sMissingType = new Regex(@"[^'`]*['`](?<type_name>[^']+)'[^'`]+['`](?<namespace>[^']+)'", RegexOptions.ExplicitCapture | RegexOptions.Compiled); private static readonly Regex sUnknownTypeOrNamespace = new Regex(@"[^'`]*['`](?<type_name>[^']+)'.*", RegexOptions.ExplicitCapture | RegexOptions.Compiled); private static string MissingTypeNameFor(Match match) { Regex TypeNameParserFor(string compilerErrorCode) { switch (compilerErrorCode) { case "CS0117": return sMissingMember; case "CS0246": case "CS0103": return sUnknownTypeOrNamespace; case "CS0234": return sMissingType; default: return null; } } var id = match.Groups["id"].Value; var typeNameParser = TypeNameParserFor(id); if (typeNameParser == null) return null; var matchedMessage = typeNameParser.Match(match.Groups["message"].Value); return !matchedMessage.Success ? null : matchedMessage.Groups["type_name"].Value; } } }
UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/BeeDriver/PotentiallyUpdatableErrorMessages.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/BeeDriver/PotentiallyUpdatableErrorMessages.cs", "repo_id": "UnityCsReference", "token_count": 1183 }
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; namespace UnityEditor.Scripting.ScriptCompilation { // Keep in sync with EditorScriptCompilationOptions in native [Flags] enum EditorScriptCompilationOptions { BuildingEmpty = 0, BuildingDevelopmentBuild = 1 << 0, BuildingForEditor = 1 << 1, BuildingEditorOnlyAssembly = 1 << 2, BuildingForIl2Cpp = 1 << 3, BuildingWithAsserts = 1 << 4, BuildingIncludingTestAssemblies = 1 << 5, BuildingPredefinedAssembliesAllowUnsafeCode = 1 << 6, BuildingForHeadlessPlayer = 1 << 7, BuildingUseDeterministicCompilation = 1 << 9, BuildingWithoutScriptUpdater = 1 << 11, BuildingExtractTypeDB = 1 << 12, BuildingSkipCompile = 1 << 13, BuildingCleanCompilation = 1 << 14, } }
UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/EditorScriptCompilationOptions.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/EditorScriptCompilationOptions.cs", "repo_id": "UnityCsReference", "token_count": 360 }
343
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Collections.Generic; using System.Diagnostics; using System.Linq; using UnityEditor.Scripting.Compilers; using UnityEditor.Compilation; using UnityEditor.Modules; namespace UnityEditor.Scripting.ScriptCompilation { // Settings that would be common for a group of ScriptAssembly's created for the same build target. class ScriptAssemblySettings { public BuildTarget BuildTarget { get; set; } public int Subtarget { get; set; } public string OutputDirectory { get; set; } public EditorScriptCompilationOptions CompilationOptions { get; set; } public ScriptCompilerOptions PredefinedAssembliesCompilerOptions { get; set; } public string[] ExtraGeneralDefines { get; set; } public string[] AdditionalCompilerArguments { get; set; } public ICompilationExtension CompilationExtension { get; set; } public string ProjectRootNamespace { get; set; } public string ProjectDirectory { get; set; } = "."; public CodeOptimization EditorCodeOptimization { get; set; } public ScriptAssemblySettings() { BuildTarget = BuildTarget.NoTarget; Subtarget = 0; PredefinedAssembliesCompilerOptions = new ScriptCompilerOptions(); ExtraGeneralDefines = new string[0]; AdditionalCompilerArguments = new string[0]; } public bool BuildingForEditor { get { return (CompilationOptions & EditorScriptCompilationOptions.BuildingForEditor) == EditorScriptCompilationOptions.BuildingForEditor; } } public bool BuildingDevelopmentBuild { get { return (CompilationOptions & EditorScriptCompilationOptions.BuildingDevelopmentBuild) == EditorScriptCompilationOptions.BuildingDevelopmentBuild; } } public CodeOptimization CodeOptimization { get { return BuildingForEditor ? EditorCodeOptimization : BuildingDevelopmentBuild? CodeOptimization.Debug : CodeOptimization.Release; } } public bool BuildingWithoutScriptUpdater { get { return (CompilationOptions & EditorScriptCompilationOptions.BuildingWithoutScriptUpdater) == EditorScriptCompilationOptions.BuildingWithoutScriptUpdater; } } } [DebuggerDisplay("{Filename}")] class ScriptAssembly { public string OriginPath { get; set; } public AssemblyFlags Flags { get; set; } public BuildTarget BuildTarget { get; set; } public string Filename { get; set; } public string OutputDirectory { get; set; } /// <summary> /// References to dependencies that will be built. /// </summary> public ScriptAssembly[] ScriptAssemblyReferences { get; set; } /// <summary> ///References to dependencies that that will *not* be built. /// </summary> public string[] References { get; set; } public string[] Defines { get; set; } public string[] Files { get; set; } public string RootNamespace { get; set; } public ScriptCompilerOptions CompilerOptions { get; set; } public string GeneratedResponseFile { get; set; } // Indicates whether the assembly had compile errors on last compilation public bool HasCompileErrors { get; set; } internal TargetAssemblyType TargetAssemblyType { get; set; } public string AsmDefPath { get; set; } public ScriptAssembly() { CompilerOptions = new ScriptCompilerOptions(); } public string FullPath { get { return AssetPath.Combine(OutputDirectory, Filename); } } public string[] GetAllReferences() { return References.Concat(ScriptAssemblyReferences.Select(a => a.FullPath)).ToArray(); } public IEnumerable<ScriptAssembly> AllRecursiveScripAssemblyReferencesIncludingSelf() => ScriptAssemblyReferences .SelectMany(a => a.AllRecursiveScripAssemblyReferencesIncludingSelf()) .Concat(new[] {this}); public string[] GetResponseFiles() { return new MicrosoftCSharpResponseFileProvider().Get(OriginPath).ToArray(); } public bool SkipCodeGen { get; set; } } }
UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/ScriptAssembly.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/ScriptAssembly.cs", "repo_id": "UnityCsReference", "token_count": 1601 }
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.Collections.Generic; using UnityEngine.UIElements; using Object = UnityEngine.Object; namespace UnityEditor.SearchService { // Default implementations for built-in search engines. abstract class LegacySearchEngineBase : ISearchEngineBase { internal const string k_Name = "Classic"; public string name => k_Name; public virtual void BeginSession(ISearchContext context) {} public virtual void EndSession(ISearchContext context) {} public virtual void BeginSearch(ISearchContext context, string query) {} public virtual void EndSearch(ISearchContext context) {} } abstract class DefaultSearchEngine<T> : LegacySearchEngineBase, ISearchEngine<T> { public virtual IEnumerable<T> Search(ISearchContext context, string query, Action<IEnumerable<T>> asyncItemsReceived) { return null; } } abstract class DefaultFilterEngine<T> : LegacySearchEngineBase, IFilterEngine<T> { public virtual bool Filter(ISearchContext context, string query, T objectToFilter) { return false; } } abstract class DefaultObjectSelectorEngine : LegacySearchEngineBase, ISelectorEngine { public virtual bool SelectObject(ISearchContext context, Action<Object, bool> onObjectSelectorClosed, Action<Object> onObjectSelectedUpdated) { return false; } public virtual void SetSearchFilter(ISearchContext context, string searchFilter) {} } // Default project search engine. Nothing is overriden. We keep returning null because // of how the search is implemented in the project browser. The null value is handled there, // and the default behavior is used when null is returned. [ProjectSearchEngine] class ProjectSearchEngine : DefaultSearchEngine<string>, IProjectSearchEngine {} // Default scene search engine. [SceneSearchEngine] class HierarchySearchEngine : DefaultFilterEngine<HierarchyProperty>, ISceneSearchEngine { public override bool Filter(ISearchContext context, string query, HierarchyProperty objectToFilter) { // Returning true here, since the properties have already been filtered. See BeginSearch(). return true; } public override void BeginSearch(ISearchContext context, string query) { // To get the original behavior and performance, we set the filter on the root property // at the beginning of a search. This will have the effect of filtering the properties // during a call to Next() or NextWithDepthCheck(), so Filter() should always return true. var hierarchySearchContext = context as SceneSearchContext; hierarchySearchContext?.rootProperty.SetSearchFilter(hierarchySearchContext.searchFilter); } } // Default object selector engine. Nothing is overriden. We keep returning false because // of how the selector is implemented in the object selector. The bool value is handled there, // and the default behavior is used when false is returned. [ObjectSelectorEngine] class ObjectPickerEngine : DefaultObjectSelectorEngine, IObjectSelectorEngine {} }
UnityCsReference/Editor/Mono/Search/LegacyImplementations.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Search/LegacyImplementations.cs", "repo_id": "UnityCsReference", "token_count": 1134 }
345
// 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.Runtime.CompilerServices; using System.Runtime.InteropServices; using UnityEngine.Bindings; using UnityEngine.Serialization; using UnityObject = UnityEngine.Object; using System.Reflection; using System.Text.RegularExpressions; using RefId = System.Int64; namespace UnityEditor { // This MUST be kept synchronized with the enum in SerializedProperty.h // Type of a [[SerializedProperty]]. public enum SerializedPropertyType { // Struct, array or class that is serialized by value. Generic = -1, // Integer property. Integer = 0, // Boolean property. Boolean = 1, // Float property. Float = 2, // String property. String = 3, // Color property. Color = 4, // Reference to another object. ObjectReference = 5, // [[LayerMask]] property. LayerMask = 6, // Enumeration property. Enum = 7, // 2D vector property. Vector2 = 8, // 3D vector property. Vector3 = 9, // 4D vector property. Vector4 = 10, // Rectangle property. Rect = 11, // Array size property. ArraySize = 12, // Character property. Character = 13, // AnimationCurve property. AnimationCurve = 14, // Bounds property. Bounds = 15, // Gradient property. Gradient = 16, // Quaternion property. Quaternion = 17, ExposedReference = 18, // Fixed Buffer size property FixedBufferSize = 19, // 2D int vector property. Vector2Int = 20, // 3D int vector property. Vector3Int = 21, // Rectangle with int property. RectInt = 22, // Bounds with int property. BoundsInt = 23, // Managed reference property. ManagedReference = 24, // Hash128 value Hash128 = 25, // Rendering Layer Mask property RenderingLayerMask = 26 } // This enum exposes extra detail, because SerializedPropertyType classifies all numeric types as Integer or Float public enum SerializedPropertyNumericType { Unknown = 0, // SerializedPropertyType.Integer covers all these types Int8 = 1, // sbyte UInt8 = 2, // byte Int16 = 3, // short UInt16 = 4, // ushort Int32 = 5, // int UInt32 = 6, // uint Int64 = 7, // long UInt64 = 8, // ulong // SerializedPropertyType.Float includes both Float and Double Float = 100, Double = 101, } [NativeHeader("Editor/Src/Utility/SerializedProperty.h")] [NativeHeader("Editor/Src/Utility/SerializedProperty.bindings.h")] [StructLayout(LayoutKind.Sequential)] public class SerializedProperty : IDisposable { IntPtr m_NativePropertyPtr; private SerializedProperty(IntPtr nativePropertyPtr) { m_NativePropertyPtr = nativePropertyPtr; } // This is so the garbage collector won't clean up SerializedObject behind the scenes. [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal SerializedObject m_SerializedObject; internal string m_CachedLocalizedDisplayName = ""; string m_CachedTooltip; internal SerializedProperty() {} ~SerializedProperty() { Dispose(); } // [[SerializedObject]] this property belongs to (RO). public SerializedObject serializedObject { get { return m_SerializedObject; } } public UnityObject exposedReferenceValue { get { if (propertyType != SerializedPropertyType.ExposedReference) return null; var defaultValue = FindPropertyRelative("defaultValue"); if (defaultValue == null) return null; var returnedValue = defaultValue.objectReferenceValue; var exposedPropertyTable = serializedObject.context as IExposedPropertyTable; if (exposedPropertyTable != null) { SerializedProperty exposedName = FindPropertyRelative("exposedName"); var propertyName = new PropertyName(exposedName.stringValue); bool propertyFoundInTable = false; var objReference = exposedPropertyTable.GetReferenceValue(propertyName, out propertyFoundInTable); if (propertyFoundInTable == true) returnedValue = objReference; } return returnedValue; } set { if (propertyType != SerializedPropertyType.ExposedReference) { throw new System.InvalidOperationException("Attempting to set the reference value on a SerializedProperty that is not an ExposedReference"); } var defaultValue = FindPropertyRelative("defaultValue"); var exposedPropertyTable = serializedObject.context as IExposedPropertyTable; if (exposedPropertyTable == null) { defaultValue.objectReferenceValue = value; defaultValue.serializedObject.ApplyModifiedProperties(); return; } SerializedProperty exposedName = FindPropertyRelative("exposedName"); var exposedId = exposedName.stringValue; if (String.IsNullOrEmpty(exposedId)) { exposedId = UnityEditor.GUID.Generate().ToString(); exposedName.stringValue = exposedId; } var propertyName = new PropertyName(exposedId); exposedPropertyTable.SetReferenceValue(propertyName, value); } } internal bool isScript { get { return type == "PPtr<MonoScript>"; } } internal string localizedDisplayName { [VisibleToOtherModules("UnityEditor.UIBuilderModule")] get { if (!this.isValidDisplayNameCache) { this.isValidDisplayNameCache = true; m_CachedLocalizedDisplayName = L10n.Tr(displayName, m_SerializedObject.targetObject); } return m_CachedLocalizedDisplayName; } } internal string[] enumLocalizedDisplayNames { get { string[] names = enumDisplayNames; var res = new string[names.Length]; for (var i = 0; i < res.Length; ++i) { res[i] = L10n.Tr(names[i], m_SerializedObject.targetObject); } return res; } } // Returns a copy of the SerializedProperty iterator in its current state. This is useful if you want to keep a reference to the current property but continue with the iteration. public SerializedProperty Copy() { SerializedProperty property = CopyInternal(); property.m_SerializedObject = m_SerializedObject; property.m_CachedLocalizedDisplayName = m_CachedLocalizedDisplayName; property.m_CachedTooltip = m_CachedTooltip; return property; } // Retrieves the SerializedProperty at a relative path to the current property. public SerializedProperty FindPropertyRelative(string relativePropertyPath) { SerializedProperty prop = Copy(); if (prop.FindPropertyRelativeInternal(relativePropertyPath)) return prop; else return null; } // Retrieves an iterator that allows you to iterator over the current nexting of a serialized property. public System.Collections.IEnumerator GetEnumerator() { if (isArray) { for (int i = 0; i < arraySize; i++) { yield return GetArrayElementAtIndex(i); } } else { var end = GetEndProperty(); while (NextVisible(true) && !SerializedProperty.EqualContents(this, end)) { yield return this; } } } // Returns the element at the specified index in the array. public SerializedProperty GetArrayElementAtIndex(int index) { SerializedProperty prop = Copy(); if (prop.GetArrayElementAtIndexInternal(index)) return prop; else return null; } internal void SetToValueOfTarget(UnityObject target) { using (SerializedObject targetObject = new SerializedObject(target)) { using (SerializedProperty targetProperty = targetObject.FindProperty(propertyPath)) { if (targetProperty == null) { Debug.LogError(target.name + " does not have the property " + propertyPath); return; } try { boxedValue = targetProperty.boxedValue; } catch (NotSupportedException ex) { // Previous implementation silently did nothing for unsupported types, now moving towards more strict error handling with this warning Debug.LogWarning(ex.Message); } } } } public System.Object boxedValue { get { switch (propertyType) { case SerializedPropertyType.Generic: return structValue; case SerializedPropertyType.Enum: goto case SerializedPropertyType.Integer; case SerializedPropertyType.Integer: { switch (numericType) { case SerializedPropertyNumericType.UInt64: return ulongValue; case SerializedPropertyNumericType.Int64: return longValue; case SerializedPropertyNumericType.UInt32: return uintValue; case SerializedPropertyNumericType.UInt16: return (System.UInt16)uintValue; case SerializedPropertyNumericType.Int16: return (System.Int16)intValue; case SerializedPropertyNumericType.UInt8: return (System.Byte)uintValue; case SerializedPropertyNumericType.Int8: return (System.SByte)intValue; default: return intValue; } } case SerializedPropertyType.Boolean: return boolValue; case SerializedPropertyType.Float: { if (numericType == SerializedPropertyNumericType.Double) return doubleValue; else return floatValue; } case SerializedPropertyType.String: return stringValue; case SerializedPropertyType.Color: return colorValue; case SerializedPropertyType.ObjectReference: return objectReferenceValue; case SerializedPropertyType.LayerMask: return (LayerMask)intValue; case SerializedPropertyType.RenderingLayerMask: return (RenderingLayerMask)uintValue; case SerializedPropertyType.Vector2: return vector2Value; case SerializedPropertyType.Vector3: return vector3Value; case SerializedPropertyType.Vector4: return vector4Value; case SerializedPropertyType.Rect: return rectValue; case SerializedPropertyType.ArraySize: return intValue; case SerializedPropertyType.Character: return (System.UInt16)uintValue; case SerializedPropertyType.AnimationCurve: return animationCurveValue; case SerializedPropertyType.Bounds: return boundsValue; case SerializedPropertyType.Gradient: return gradientValue; case SerializedPropertyType.Quaternion: return quaternionValue; case SerializedPropertyType.ExposedReference: return exposedReferenceValue; case SerializedPropertyType.FixedBufferSize: return intValue; case SerializedPropertyType.Vector2Int: return vector2IntValue; case SerializedPropertyType.Vector3Int: return vector3IntValue; case SerializedPropertyType.RectInt: return rectIntValue; case SerializedPropertyType.BoundsInt: return boundsIntValue; case SerializedPropertyType.ManagedReference: return managedReferenceValue; case SerializedPropertyType.Hash128: return hash128Value; default: throw new NotSupportedException(string.Format("The boxedValue property is not supported on \"{0}\" because it has an unsupported propertyType {1}.", propertyPath, propertyType)); } } set { if (value == null && !IsBoxedValueNullable()) throw new ArgumentException("Argument to boxedValue cannot be null"); try { // Note: typecast from System.Object enforces strict match between the boxed type and cast type. // The Convert API is used for cases where multiple types can safely and commonly be converted to the underlying SerializedProperty type. switch (propertyType) { case SerializedPropertyType.Generic: structValue = value; break; case SerializedPropertyType.Enum: goto case SerializedPropertyType.Integer; case SerializedPropertyType.ArraySize: goto case SerializedPropertyType.Integer; case SerializedPropertyType.Integer: { //Convert so that simple mismatches like sbyte to int are accepted if (numericType == SerializedPropertyNumericType.UInt64) { ulongValue = Convert.ToUInt64(value); } else { // all smaller numeric datatypes fit into the range of long and are cast back to the correct type internally longValue = Convert.ToInt64(value); } break; } case SerializedPropertyType.Boolean: boolValue = (bool)value; break; case SerializedPropertyType.Float: { if (numericType == SerializedPropertyNumericType.Double) doubleValue = Convert.ToDouble(value); else floatValue = Convert.ToSingle(value); break; } case SerializedPropertyType.String: stringValue = (string)value; break; case SerializedPropertyType.Color: colorValue = (Color)value; break; case SerializedPropertyType.ObjectReference: objectReferenceValue = (UnityEngine.Object)value; break; case SerializedPropertyType.LayerMask: { try { intValue = ((LayerMask)value).value; } catch (InvalidCastException) { intValue = Convert.ToInt32(value); } break; } case SerializedPropertyType.RenderingLayerMask: { try { uintValue = ((RenderingLayerMask)value).value; } catch (InvalidCastException) { uintValue = Convert.ToUInt32(value); } break; } case SerializedPropertyType.Vector2: vector2Value = (Vector2)value; break; case SerializedPropertyType.Vector3: vector3Value = (Vector3)value; break; case SerializedPropertyType.Vector4: vector4Value = (Vector4)value; break; case SerializedPropertyType.Rect: rectValue = (Rect)value; break; case SerializedPropertyType.Character: uintValue = Convert.ToUInt16(value); break; case SerializedPropertyType.AnimationCurve: animationCurveValue = (AnimationCurve)value; break; case SerializedPropertyType.Bounds: boundsValue = (Bounds)value; break; case SerializedPropertyType.Gradient: gradientValue = (Gradient)value; break; case SerializedPropertyType.Quaternion: quaternionValue = (Quaternion)value; break; case SerializedPropertyType.ExposedReference: exposedReferenceValue = (UnityEngine.Object)value; break; case SerializedPropertyType.Vector2Int: vector2IntValue = (Vector2Int)value; break; case SerializedPropertyType.Vector3Int: vector3IntValue = (Vector3Int)value; break; case SerializedPropertyType.RectInt: rectIntValue = (RectInt)value; break; case SerializedPropertyType.BoundsInt: boundsIntValue = (BoundsInt)value; break; case SerializedPropertyType.ManagedReference: managedReferenceValue = value; break; case SerializedPropertyType.Hash128: hash128Value = (Hash128)value; break; default: // FixedBufferSize is read-only throw new NotSupportedException(string.Format("Set on boxedValue property is not supported on \"{0}\" because it has an unsupported propertyType {1}.", propertyPath, propertyType)); } } catch (InvalidCastException) { throw new InvalidCastException(string.Format("The value passed to boxedValue on \"{0}\" cannot be cast to expected propertyType {1}.", propertyPath, propertyType)); } } } private bool IsBoxedValueNullable() { return propertyType == SerializedPropertyType.ManagedReference || propertyType == SerializedPropertyType.ObjectReference || propertyType == SerializedPropertyType.ExposedReference || propertyType == SerializedPropertyType.String; } extern private bool EndOfData(); extern private void SyncSerializedObjectVersion(); [Flags] internal enum VerifyFlags { None = 0, IteratorNotAtEnd = 1 << 1, } [MethodImpl(256)] internal void Verify(VerifyFlags verifyFlags = VerifyFlags.None) { if (unsafeMode) return; if (m_NativePropertyPtr == IntPtr.Zero || m_SerializedObject == null || m_SerializedObject.m_NativeObjectPtr == IntPtr.Zero) throw new NullReferenceException("SerializedObject of SerializedProperty has been Disposed."); SyncSerializedObjectVersion(); if ((verifyFlags & VerifyFlags.IteratorNotAtEnd) == VerifyFlags.IteratorNotAtEnd && EndOfData()) throw new InvalidOperationException("The operation is not possible when moved past all properties (Next returned false)"); } // Move to next visible property. public bool NextVisible(bool enterChildren) { Verify(VerifyFlags.IteratorNotAtEnd); return NextVisibleInternal(enterChildren); } [NativeName("NextVisible")] extern private bool NextVisibleInternal(bool enterChildren); // Remove all elements from the array. public void ClearArray() { Verify(VerifyFlags.IteratorNotAtEnd); ClearArrayInternal(); } [FreeFunction(Name = "SerializedPropertyBindings::ClearArray", HasExplicitThis = true)] extern private void ClearArrayInternal(); [NativeName("FindProperty")] extern internal bool FindPropertyInternal(string propertyPath); [NativeName("FindFirstPropertyFromManagedReferencePath")] extern internal bool FindFirstPropertyFromManagedReferencePathInternal(string managedReferencePath); [ThreadAndSerializationSafe()] public void Dispose() { if (m_NativePropertyPtr != IntPtr.Zero) { Internal_Destroy(m_NativePropertyPtr); m_NativePropertyPtr = IntPtr.Zero; } } [FreeFunction("SerializedPropertyBindings::Internal_Destroy", IsThreadSafe = true)] private extern static void Internal_Destroy(IntPtr ptr); // See if contained serialized properties are equal. public static bool EqualContents(SerializedProperty x, SerializedProperty y) { if (x == null) return (y == null || y.m_NativePropertyPtr == IntPtr.Zero); if (y == null) return (x == null || x.m_NativePropertyPtr == IntPtr.Zero); x.Verify(); y.Verify(); return EqualContentsInternal(x, y); } [FreeFunction("SerializedPropertyBindings::EqualContentsInternal")] private extern static bool EqualContentsInternal(SerializedProperty x, SerializedProperty y); // See if raw data inside both serialized property is equal. public static bool DataEquals(SerializedProperty x, SerializedProperty y) { if (x == null) return (y == null || y.m_NativePropertyPtr == IntPtr.Zero); if (y == null) return (x == null || x.m_NativePropertyPtr == IntPtr.Zero); x.Verify(); y.Verify(); return DataEqualsInternal(x, y); } // See if versions inside both property serialized objects are equal. internal static bool VersionEquals(SerializedProperty x, SerializedProperty y) { if (x == null) return (y == null || y.m_NativePropertyPtr == IntPtr.Zero); if (y == null) return (x == null || x.m_NativePropertyPtr == IntPtr.Zero); return SerializedObject.VersionEquals(x.serializedObject, y.serializedObject); } [FreeFunction("SerializedPropertyBindings::DataEqualsInternal")] private extern static bool DataEqualsInternal(SerializedProperty x, SerializedProperty y); // Does this property represent multiple different values due to multi-object editing? (RO) public bool hasMultipleDifferentValues { get { Verify(VerifyFlags.IteratorNotAtEnd); return HasMultipleDifferentValuesInternal() != 0; } } internal int hasMultipleDifferentValuesBitwise { get { Verify(VerifyFlags.IteratorNotAtEnd); return HasMultipleDifferentValuesInternal(); } } [NativeName("HasMultipleDifferentValues")] private extern int HasMultipleDifferentValuesInternal(); internal void SetBitAtIndexForAllTargetsImmediate(int index, bool value) { Verify(VerifyFlags.IteratorNotAtEnd); SetBitAtIndexForAllTargetsImmediateInternal(index, value); } [NativeName("SetBitAtIndexForAllTargetsImmediate")] private extern void SetBitAtIndexForAllTargetsImmediateInternal(int index, bool value); // Nice display name of the property (RO) public string displayName { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetMangledNameInternal(); } } [NativeName("GetMangledName")] private extern string GetMangledNameInternal(); // Name of the property (RO) public string name { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetNameInternal(); } } [FreeFunction("SerializedPropertyBindings::GetNameInternal", HasExplicitThis = true)] private extern string GetNameInternal(); // Type name of the property (RO) public string type { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetSerializedPropertyTypeNameInternal(); } } [NativeName("GetSerializedPropertyTypeName")] private extern string GetSerializedPropertyTypeNameInternal(); // Type name of the element of an Array property (RO) public string arrayElementType { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetSerializedPropertyArrayElementTypeNameInternal(); } } [NativeName("GetSerializedPropertyArrayElementTypeName")] private extern string GetSerializedPropertyArrayElementTypeNameInternal(); // Tooltip of the property (RO) public string tooltip { get { Verify(VerifyFlags.IteratorNotAtEnd); if (!isValidTooltipCache) { isValidTooltipCache = true; m_CachedTooltip = GetTooltipInternal(); if (string.IsNullOrEmpty(m_CachedTooltip)) m_CachedTooltip = ScriptAttributeUtility.GetHandler(this).tooltip ?? string.Empty; } return m_CachedTooltip; } } [NativeName("GetTooltip")] private extern string GetTooltipInternal(); // Nesting depth of the property (RO) public int depth { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetDepthInternal(); } } [NativeName("GetDepth")] private extern int GetDepthInternal(); // Full path of the property (RO) private string m_PropertyPath = ""; private int m_PropertyPathHash = 0; public string propertyPath { get { Verify(); int hash = GetHashCodeForPropertyPathInternal(); if (m_PropertyPathHash != hash) { m_PropertyPathHash = hash; m_PropertyPath = GetPropertyPathInternal(); } return m_PropertyPath; } } [NativeName("GetPropertyPath")] private extern string GetPropertyPathInternal(); [NativeName("GetHashCodeForPropertyPath")] private extern int GetHashCodeForPropertyPathInternal(); internal int hashCodeForPropertyPathWithoutArrayIndex { get { Verify(); return GetHashCodeForPropertyPathWithoutArrayIndexInternal(); } } internal int hashCodeForPropertyPath { get { Verify(); return GetHashCodeForPropertyPathInternal(); } } [NativeName("GetHashCodeForPropertyPathWithoutArrayIndex")] private extern int GetHashCodeForPropertyPathWithoutArrayIndexInternal(); // Is this property editable? (RO) public bool editable { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetEditableInternal(); } } [NativeName("GetEditable")] private extern bool GetEditableInternal(); [NativeName("IsReorderable")] internal extern bool IsReorderable(); // Is this property animated? (RO) public bool isAnimated { get { Verify(VerifyFlags.IteratorNotAtEnd); return IsAnimatedInternal(); } } [NativeName("IsAnimated")] private extern bool IsAnimatedInternal(); // Is this property candidate? (RO) internal bool isCandidate { get { Verify(VerifyFlags.IteratorNotAtEnd); return IsCandidateInternal(); } } [NativeName("IsCandidate")] private extern bool IsCandidateInternal(); // Is this property keyed? (RO) internal bool isKey { get { Verify(VerifyFlags.IteratorNotAtEnd); return IsKeyInternal(); } } [NativeName("IsKey")] private extern bool IsKeyInternal(); [NativeName("IsLiveModified")] private extern bool IsLiveModified(); // Is this property live modified? internal bool isLiveModified { get { Verify(VerifyFlags.IteratorNotAtEnd); return IsLiveModified(); } } // Is this property expanded in the inspector? public bool isExpanded { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetIsExpandedInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetIsExpandedInternal(value); } } [NativeName("GetIsExpanded")] private extern bool GetIsExpandedInternal(); [NativeName("SetIsExpanded")] private extern void SetIsExpandedInternal(bool value); // Does it have child properties? (RO) public bool hasChildren { get { Verify(VerifyFlags.IteratorNotAtEnd); return HasChildrenInternal(); } } [NativeName("HasChildren")] private extern bool HasChildrenInternal(); // Does it have visible child properties? (RO) public bool hasVisibleChildren { get { Verify(VerifyFlags.IteratorNotAtEnd); return HasVisibleChildrenInternal(); } } [NativeName("HasVisibleChildren")] private extern bool HasVisibleChildrenInternal(); // Is property part of a prefab instance? (RO) public bool isInstantiatedPrefab { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetIsInstantiatedPrefabInternal(); } } [NativeName("GetIsInstantiatedPrefab")] private extern bool GetIsInstantiatedPrefabInternal(); /// <summary> /// A property can reference any element in the parent SerializedObject. /// In the context of polymorphic serialization, those elements might be dynamic instances /// not statically discoverable from the class type. /// We need to take a very specific code path when we try to get the type of a field /// inside such a dynamic instance through a SerializedProperty. /// /// @see UnityEditor.ScriptAttributeUtility.GetFieldInfoAndStaticTypeFromProperty /// </summary> internal bool isReferencingAManagedReferenceField { get { Verify(VerifyFlags.IteratorNotAtEnd); return IsReferencingAManagedReferenceFieldInternal(); } } // Useful in the same context as 'isReferencingAManagedReferenceField'. [NativeName("IsReferencingAManagedReferenceField")] private extern bool IsReferencingAManagedReferenceFieldInternal(); /// <summary> /// Returns the FQN in the format "<assembly name> <full class name>" for the current dynamic managed reference. /// </summary> /// <returns></returns> // Useful in the same context as 'isReferencingAManagedReferenceField'. [NativeName("GetFullyQualifiedTypenameForCurrentTypeTree")] internal extern string GetFullyQualifiedTypenameForCurrentTypeTreeInternal(); /// <summary> /// Returns the path of the current field on the dynamic reference class. /// </summary> // Useful in the same context as 'isReferencingAManagedReferenceField'. [NativeName("GetPropertyPathInCurrentManagedTypeTree")] internal extern string GetPropertyPathInCurrentManagedTypeTreeInternal(); /// <summary> /// If the current field is on a SerializeReference instance this returns the path /// of the field relative the ManagedReferenceRegistry. managedReferences[refId].field /// </summary> internal string managedReferencePropertyPath { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetManagedReferencePropertyPathInternal(); } } /// <summary> /// Returns the path of the current field relative to the managed reference registry managedReferences[refId]. /// </summary> // Useful in the same context as 'isReferencingAManagedReferenceField'. [NativeName("GetManagedReferencePropertyPath")] internal extern string GetManagedReferencePropertyPathInternal(); // Is property's value different from the prefab it belongs to? public bool prefabOverride { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetPrefabOverrideInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetPrefabOverrideInternal(value); } } [NativeName("GetPrefabOverride")] private extern bool GetPrefabOverrideInternal(); [NativeName("SetPrefabOverride")] private extern void SetPrefabOverrideInternal(bool value); // Is property a default override property which is enforced to always be overridden? (RO) public bool isDefaultOverride { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetIsDefaultOverrideInternal(); } } [NativeName("IsDefaultOverride")] private extern bool GetIsDefaultOverrideInternal(); // Is property a driven property (using RectTransform driven properties)? (RO) internal bool isDrivenRectTransformProperty { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetIsDrivenRectTransformPropertyInternal(); } } [NativeName("IsDrivenRectTransformProperty")] private extern bool GetIsDrivenRectTransformPropertyInternal(); // Type of this property (RO). public SerializedPropertyType propertyType { get { Verify(VerifyFlags.IteratorNotAtEnd); return (SerializedPropertyType)GetSerializedPropertyTypeInternal(); } } [NativeName("GetSerializedPropertyType")] private extern int GetSerializedPropertyTypeInternal(); public SerializedPropertyNumericType numericType { get { Verify(VerifyFlags.IteratorNotAtEnd); return (SerializedPropertyNumericType)GetNumericTypeInternal(); } } [NativeName("GetNumericType")] private extern int GetNumericTypeInternal(); // Value of an integer property. public int intValue { get { Verify(VerifyFlags.IteratorNotAtEnd); return (int)GetIntValueInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetIntValueInternal(value); } } [NativeName("GetIntValue")] private extern long GetIntValueInternal(); [NativeName("SetIntValue")] private extern void SetIntValueInternal(long value); // Value of an long property. public long longValue { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetIntValueInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetIntValueInternal(value); } } public ulong ulongValue { get { Verify(VerifyFlags.IteratorNotAtEnd); return (ulong)GetIntValueInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetIntValueInternal((long)value); } } public uint uintValue { get { Verify(VerifyFlags.IteratorNotAtEnd); return (uint)GetIntValueInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetIntValueInternal(value); } } // Value of a boolean property. public bool boolValue { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetBoolValueInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetBoolValueInternal(value); } } [NativeName("GetBoolValue")] private extern bool GetBoolValueInternal(); [NativeName("SetBoolValue")] private extern void SetBoolValueInternal(bool value); // Value of a float property. public float floatValue { get { Verify(VerifyFlags.IteratorNotAtEnd); return (float)GetFloatValueInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetFloatValueInternal(value); } } [NativeName("GetFloatValue")] private extern double GetFloatValueInternal(); [NativeName("SetFloatValue")] private extern void SetFloatValueInternal(double value); internal double[] allDoubleValues { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetAllFloatValues(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetAllFloatValuesImmediate(value); } } internal long[] allLongValues { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetAllIntValues(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetAllIntValuesImmediate(value); } } extern double[] GetAllFloatValues(); extern void SetAllFloatValuesImmediate(double[] value); extern long[] GetAllIntValues(); extern void SetAllIntValuesImmediate(long[] value); // Value of a double property. public double doubleValue { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetFloatValueInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetFloatValueInternal(value); } } // Value of a string property. public string stringValue { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetStringValueInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetStringValueInternal(value); } } [NativeName("GetStringValue")] private extern string GetStringValueInternal(); [NativeName("SetStringValue")] private extern void SetStringValueInternal(string value); // Value of a color property. public Color colorValue { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetColorValueInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetColorValueInternal(value); } } [NativeName("GetColorValue")] private extern Color GetColorValueInternal(); [NativeName("SetColorValue")] private extern void SetColorValueInternal(Color value); // Value of a animation curve property. public AnimationCurve animationCurveValue { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetAnimationCurveValueCopyInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetAnimationCurveValueInternal(value); } } [NativeName("GetAnimationCurveValueCopy")] private extern AnimationCurve GetAnimationCurveValueCopyInternal(); [NativeName("SetAnimationCurveValue")] private extern void SetAnimationCurveValueInternal(AnimationCurve value); // Value of a gradient property. public Gradient gradientValue { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetGradientValueCopyInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetGradientValueInternal(value); } } [NativeName("GetGradientValueCopy")] private extern Gradient GetGradientValueCopyInternal(); [NativeName("SetGradientValue")] private extern void SetGradientValueInternal(Gradient value); // Value of an object reference property. public UnityObject objectReferenceValue { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetPPtrValueInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetPPtrValueInternal(value); } } // Value of an object reference property. public object managedReferenceValue { get { Verify(VerifyFlags.IteratorNotAtEnd); if (propertyType != SerializedPropertyType.ManagedReference) { throw new System.InvalidOperationException( $"managedReferenceValue is only available on fields with the [SerializeReference] attribute"); } return LookupInstanceByIdInternal(GetManagedReferenceIdInternal()); } set { if (propertyType != SerializedPropertyType.ManagedReference) { throw new System.InvalidOperationException( $"Attempting to set the managed reference value on a SerializedProperty that is set to a '{this.type}'"); } // Make sure that the underlying base type is compatible with the current object Type type; var fieldInfo = UnityEditor.ScriptAttributeUtility.GetFieldInfoAndStaticTypeFromProperty(this, out type); var propertyBaseType = type; if (value != null) { var valueType = value.GetType(); if (valueType == typeof(UnityObject) || valueType.IsSubclassOf(typeof(UnityObject))) { throw new System.InvalidOperationException( $"Cannot assign an object deriving from UnityEngine.Object to a managed reference. This is not supported."); } else if (!propertyBaseType.IsAssignableFrom(valueType)) { throw new System.InvalidOperationException( $"Cannot assign an object of type '{valueType.Name}' to a managed reference with a base type of '{propertyBaseType.Name}': types are not compatible"); } } Verify(VerifyFlags.IteratorNotAtEnd); SetManagedReferenceValueInternal(value); } } public RefId managedReferenceId { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetManagedReferenceIdInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); var referencedObj = LookupInstanceByIdInternal(value); if (value != ManagedReferenceUtility.RefIdNull && referencedObj == null) { throw new System.InvalidOperationException( $"The specified managed reference id cannot be set because it is not currently assigned to an object."); } managedReferenceValue = referencedObj; } } [NativeName("GetManagedReferenceId")] private extern long GetManagedReferenceIdInternal(); // Dynamic type for the current managed reference. public string managedReferenceFullTypename { get { if (propertyType != SerializedPropertyType.ManagedReference) { throw new System.InvalidOperationException( $"Attempting to get the managed reference full typename on a SerializedProperty that is set to a '{this.type}'"); } if (serializedObject.targetObject == null) { return null; } return GetManagedReferenceFullTypeNameInternal(); } } // Static type for the current managed reference. public string managedReferenceFieldTypename { get { if (propertyType != SerializedPropertyType.ManagedReference) { throw new System.InvalidOperationException( $"Attempting to get the managed reference full typename on a SerializedProperty that is set to a '{this.type}'"); } Type type; var fieldInfo = UnityEditor.ScriptAttributeUtility.GetFieldInfoAndStaticTypeFromProperty(this, out type); return $"{type.Assembly.GetName().Name} {type.FullName.Replace("+", "/")}"; } } [NativeName("GetManagedReferenceFullTypeName")] private extern string GetManagedReferenceFullTypeNameInternal(); [NativeName("SetManagedReferenceValue")] private extern void SetManagedReferenceValueInternal(object value); [NativeName("SetStructValue")] [NativeThrows] internal extern void SetStructValueInternal(object value); [NativeName("GetStructValue")] [NativeThrows] internal extern object GetStructValueInternal(string assemblyName, string nameSpace, string className); // exposed for public access via boxedValue [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal object structValue { get { if (isArray) throw new System.InvalidOperationException($"'{propertyPath}' is an array so it cannot be read with boxedValue."); // Unlike managed references, the precise type for a struct or by-value class field is easier to determine in C# // rather than at the native level, so we pass that info in. UnityEditor.ScriptAttributeUtility.GetFieldInfoAndStaticTypeFromProperty(this, out Type type); var nameSpace = type.Namespace; string typeName = type.FullName.Replace("+", "/"); if (!string.IsNullOrEmpty(nameSpace)) typeName = typeName.Substring(nameSpace.Length + 1); return GetStructValueInternal(type.Assembly.GetName().Name, nameSpace, typeName); } set { if (isArray) throw new System.InvalidOperationException($"'{propertyPath}' is an array so it cannot be set with boxedValue."); // Retrieve the C# type info this property UnityEditor.ScriptAttributeUtility.GetFieldInfoAndStaticTypeFromProperty(this, out Type propertyType); if (propertyType.FullName != value.GetType().FullName) throw new System.InvalidOperationException( $"The input to boxedValue has type '{value.GetType().FullName.Replace("+","/")}', which does not match the expected type '{propertyType.FullName.Replace("+","/")}'."); SetStructValueInternal(value); } } [NativeName("LookupInstanceById")] private extern object LookupInstanceByIdInternal(RefId refId); [NativeName("GetPPtrValue")] private extern UnityObject GetPPtrValueInternal(); [NativeName("SetPPtrValue")] private extern void SetPPtrValueInternal(UnityObject value); public int objectReferenceInstanceIDValue { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetPPtrValueFromInstanceIDInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetPPtrValueFromInstanceIDInternal(value); } } [NativeName("GetPPtrInstanceID")] private extern int GetPPtrValueFromInstanceIDInternal(); [FreeFunction(Name = "SerializedPropertyBindings::SetPPtrValueFromInstanceIDInternal", HasExplicitThis = true)] private extern void SetPPtrValueFromInstanceIDInternal(int instanceID); internal string objectReferenceStringValue { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetPPtrStringValueInternal(); } } [NativeName("GetPPtrStringValue")] private extern string GetPPtrStringValueInternal(); internal bool ValidateObjectReferenceValue(UnityObject obj) { Verify(VerifyFlags.IteratorNotAtEnd); return ValidatePPtrValueInternal(obj); } [NativeName("ValidatePPtrValue")] private extern bool ValidatePPtrValueInternal(UnityObject obj); internal bool ValidateObjectReferenceValueExact(UnityObject obj) { Verify(VerifyFlags.IteratorNotAtEnd); return ValidatePPtrValueExact(obj); } [NativeName("ValidatePPtrValueExact")] private extern bool ValidatePPtrValueExact(UnityObject obj); internal string objectReferenceTypeString { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetPPtrClassNameInternal(); } } [NativeName("GetPPtrClassName")] private extern string GetPPtrClassNameInternal(); internal void AppendFoldoutPPtrValue(UnityObject obj) { Verify(VerifyFlags.IteratorNotAtEnd); AppendFoldoutPPtrValueInternal(obj); } [NativeName("AppendFoldoutPPtrValue")] private extern void AppendFoldoutPPtrValueInternal(UnityObject obj); internal extern static string GetLayerMaskStringValue(UInt32 layers); internal UInt32 layerMaskBits { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetLayerMaskBitsInternal(); } } [NativeName("GetLayerMaskBits")] private extern UInt32 GetLayerMaskBitsInternal(); // Enum index of an enum property. public int enumValueIndex { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetEnumValueIndexInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetEnumValueIndexInternal(value); } } // Enum flag value public int enumValueFlag { get { return intValue; } set { intValue = value; } } [NativeName("GetEnumValueIndex")] private extern int GetEnumValueIndexInternal(); [NativeName("SetEnumValueIndex")] private extern void SetEnumValueIndexInternal(int value); // Names of enumeration of an enum property. public string[] enumNames { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetEnumNamesInternal(false); } } // Names of enumeration of an enum property, nicified. public string[] enumDisplayNames { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetEnumNamesInternal(true); } } [NativeName("GetEnumNames")] private extern string[] GetEnumNamesInternal(bool nicify); // Value of a 2D vector property. public Vector2 vector2Value { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetValueVector2Internal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetValueVector2Internal(value); } } [FreeFunction(Name = "SerializedPropertyBindings::GetValueVector2Internal", HasExplicitThis = true)] extern private Vector2 GetValueVector2Internal(); [FreeFunction(Name = "SerializedPropertyBindings::SetValueVector2Internal", HasExplicitThis = true)] extern private void SetValueVector2Internal(Vector2 value); // Value of a 3D vector property. public Vector3 vector3Value { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetValueVector3Internal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetValueVector3Internal(value); } } [FreeFunction(Name = "SerializedPropertyBindings::GetValueVector3Internal", HasExplicitThis = true)] extern private Vector3 GetValueVector3Internal(); [FreeFunction(Name = "SerializedPropertyBindings::SetValueVector3Internal", HasExplicitThis = true)] extern private void SetValueVector3Internal(Vector3 value); // Value of a 4D vector property. public Vector4 vector4Value { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetValueVector4Internal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetValueVector4Internal(value); } } [FreeFunction(Name = "SerializedPropertyBindings::GetValueVector4Internal", HasExplicitThis = true)] extern private Vector4 GetValueVector4Internal(); [FreeFunction(Name = "SerializedPropertyBindings::SetValueVector4Internal", HasExplicitThis = true)] extern private void SetValueVector4Internal(Vector4 value); // Value of a 2D int vector property. public Vector2Int vector2IntValue { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetValueVector2IntInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetValueVector2IntInternal(value); } } [FreeFunction(Name = "SerializedPropertyBindings::GetValueVector2IntInternal", HasExplicitThis = true)] extern private Vector2Int GetValueVector2IntInternal(); [FreeFunction(Name = "SerializedPropertyBindings::SetValueVector2IntInternal", HasExplicitThis = true)] extern private void SetValueVector2IntInternal(Vector2Int value); // Value of a 3D int vector property. public Vector3Int vector3IntValue { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetValueVector3IntInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetValueVector3IntInternal(value); } } [FreeFunction(Name = "SerializedPropertyBindings::GetValueVector3IntInternal", HasExplicitThis = true)] extern private Vector3Int GetValueVector3IntInternal(); [FreeFunction(Name = "SerializedPropertyBindings::SetValueVector3IntInternal", HasExplicitThis = true)] extern private void SetValueVector3IntInternal(Vector3Int value); // Value of a quaternion property. public Quaternion quaternionValue { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetValueQuaternionInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetValueQuaternionInternal(value); } } [FreeFunction(Name = "SerializedPropertyBindings::GetValueQuaternionInternal", HasExplicitThis = true)] extern private Quaternion GetValueQuaternionInternal(); [FreeFunction(Name = "SerializedPropertyBindings::SetValueQuaternionInternal", HasExplicitThis = true)] extern private void SetValueQuaternionInternal(Quaternion value); // Value of a rectangle property. public Rect rectValue { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetValueRectInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetValueRectInternal(value); } } [FreeFunction(Name = "SerializedPropertyBindings::GetValueRectInternal", HasExplicitThis = true)] extern private Rect GetValueRectInternal(); [FreeFunction(Name = "SerializedPropertyBindings::SetValueRectInternal", HasExplicitThis = true)] extern private void SetValueRectInternal(Rect value); // Value of a rectangle int property. public RectInt rectIntValue { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetValueRectIntInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetValueRectIntInternal(value); } } [FreeFunction(Name = "SerializedPropertyBindings::GetValueRectIntInternal", HasExplicitThis = true)] extern private RectInt GetValueRectIntInternal(); [FreeFunction(Name = "SerializedPropertyBindings::SetValueRectIntInternal", HasExplicitThis = true)] extern private void SetValueRectIntInternal(RectInt value); // Value of bounds property. public Bounds boundsValue { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetValueBoundsInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetValueBoundsInternal(value); } } [FreeFunction(Name = "SerializedPropertyBindings::GetValueBoundsInternal", HasExplicitThis = true)] extern private Bounds GetValueBoundsInternal(); [FreeFunction(Name = "SerializedPropertyBindings::SetValueBoundsInternal", HasExplicitThis = true)] extern private void SetValueBoundsInternal(Bounds value); // Value of bounds int property. public BoundsInt boundsIntValue { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetValueBoundsIntInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetValueBoundsIntInternal(value); } } [FreeFunction(Name = "SerializedPropertyBindings::GetValueBoundsIntInternal", HasExplicitThis = true)] extern private BoundsInt GetValueBoundsIntInternal(); [FreeFunction(Name = "SerializedPropertyBindings::SetValueBoundsIntInternal", HasExplicitThis = true)] extern private void SetValueBoundsIntInternal(BoundsInt value); // Value of a Hash128 property. public Hash128 hash128Value { get { Verify(VerifyFlags.IteratorNotAtEnd); return (Hash128)GetHash128ValueInternal(); } set { Verify(VerifyFlags.IteratorNotAtEnd); SetHash128ValueInternal(value); } } [FreeFunction(Name = "SerializedPropertyBindings::GetHash128ValueInternal", HasExplicitThis = true)] private extern Hash128 GetHash128ValueInternal(); [FreeFunction(Name = "SerializedPropertyBindings::SetHash128ValueInternal", HasExplicitThis = true)] private extern void SetHash128ValueInternal(Hash128 value); // Move to next property. public bool Next(bool enterChildren) { Verify(VerifyFlags.IteratorNotAtEnd); return NextInternal(enterChildren); } [FreeFunction(Name = "SerializedPropertyBindings::NextInternal", HasExplicitThis = true)] extern private bool NextInternal(bool enterChildren); // Move to first property of the object. public void Reset() { Verify(); ResetInternal(); } [FreeFunction(Name = "SerializedPropertyBindings::ResetInternal", HasExplicitThis = true)] extern private void ResetInternal(); // Count remaining visible properties. public int CountRemaining() { Verify(VerifyFlags.IteratorNotAtEnd); return CountRemainingInternal(); } [NativeName("CountRemaining")] extern private int CountRemainingInternal(); // Count visible children of this property, including this property itself. public int CountInProperty() { Verify(VerifyFlags.IteratorNotAtEnd); return CountInPropertyInternal(); } [NativeName("CountInProperty")] extern private int CountInPropertyInternal(); private SerializedProperty CopyInternal() { Verify(); return CopyInternalImpl(); } [FreeFunction(Name = "SerializedPropertyBindings::CopyInternal", HasExplicitThis = true)] extern private SerializedProperty CopyInternalImpl(); // Duplicates the serialized property. public bool DuplicateCommand() { Verify(VerifyFlags.IteratorNotAtEnd); return DuplicateCommandInternal(); } [NativeName("DuplicateCommand")] extern private bool DuplicateCommandInternal(); // Deletes the serialized property. public bool DeleteCommand() { Verify(VerifyFlags.IteratorNotAtEnd); return DeleteCommandInternal(); } [NativeName("DeleteCommand")] extern private bool DeleteCommandInternal(); // Retrieves the SerializedProperty that defines the end range of this property. public SerializedProperty GetEndProperty() { return GetEndProperty(false); } // Retrieves the SerializedProperty that defines the end range of this property. public SerializedProperty GetEndProperty(bool includeInvisible) { SerializedProperty prop = Copy(); if (includeInvisible) prop.Next(false); else prop.NextVisible(false); return prop; } internal bool FindPropertyRelativeInternal(string propertyPath) { Verify(VerifyFlags.IteratorNotAtEnd); return FindRelativeProperty(propertyPath); } extern private bool FindRelativeProperty(string propertyPath); // Is this property an array? (RO) public bool isArray { get { Verify(VerifyFlags.IteratorNotAtEnd); return IsArray(); } } extern private bool IsArray(); // The number of elements in the array. public int arraySize { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetInspectableArraySize(); } set { Verify(); ResizeArray(value); } } public int minArraySize { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetMinArraySize(); } } extern private int GetMinArraySize(); extern private int GetInspectableArraySize(); extern private void ResizeArray(int value); private bool GetArrayElementAtIndexInternal(int index) { Verify(VerifyFlags.IteratorNotAtEnd); return GetArrayElementAtIndexImpl(index); } [NativeName("GetArrayElementAtIndex")] extern private bool GetArrayElementAtIndexImpl(int index); // Insert an empty element at the specified index in the array. // @TODO: What is the value of the element when it hasn't been set yet? // SA: ::ref::isArray public void InsertArrayElementAtIndex(int index) { Verify(VerifyFlags.IteratorNotAtEnd); InsertArrayElementAtIndexInternal(index); } [NativeName("InsertArrayElementAtIndex")] extern private void InsertArrayElementAtIndexInternal(int index); // Delete the element at the specified index in the array. public void DeleteArrayElementAtIndex(int index) { Verify(VerifyFlags.IteratorNotAtEnd); DeleteArrayElementAtIndexInternal(index); } [NativeName("DeleteArrayElementAtIndex")] extern private void DeleteArrayElementAtIndexInternal(int index); // Move an array element from srcIndex to dstIndex. public bool MoveArrayElement(int srcIndex, int dstIndex) { Verify(VerifyFlags.IteratorNotAtEnd); return MoveArrayElementInternal(srcIndex, dstIndex); } [NativeName("MoveArrayElement")] extern private bool MoveArrayElementInternal(int srcIndex, int dstIndex); // Is this property a fixed buffer? (RO) public bool isFixedBuffer { get { return IsFixedBuffer(); } } extern private bool IsFixedBuffer(); // The number of elements in the fixed buffer (RO). public int fixedBufferSize { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetFixedBufferSize(); } } extern private int GetFixedBufferSize(); // Is the cache for a display name string valid? internal bool isValidDisplayNameCache { get => GetIsValidDisplayNameCache(); set => SetIsValidDisplayNameCache(value); } extern private bool GetIsValidDisplayNameCache(); extern private void SetIsValidDisplayNameCache(bool value); // Is the cache for a tooltip string valid? internal bool isValidTooltipCache { get => GetIsValidTooltipCache(); set => SetIsValidTooltipCache(value); } extern private bool GetIsValidTooltipCache(); extern private void SetIsValidTooltipCache(bool value); public SerializedProperty GetFixedBufferElementAtIndex(int index) { Verify(VerifyFlags.IteratorNotAtEnd); SerializedProperty prop = Copy(); if (prop.GetFixedBufferAtIndexInternal(index)) return prop; else return null; } [NativeName("GetFixedBufferElementAtIndex")] extern private bool GetFixedBufferAtIndexInternal(int index); [NativeName("AnimationCurveValueEquals")] extern private bool AnimationCurveValueEquals(AnimationCurve curve); internal bool ValueEquals(AnimationCurve curve) { Verify(VerifyFlags.IteratorNotAtEnd); return AnimationCurveValueEquals(curve); } [NativeName("GradientValueEquals")] extern private bool GradientValueEquals(Gradient gradient); internal bool ValueEquals(Gradient gradient) { Verify(VerifyFlags.IteratorNotAtEnd); return GradientValueEquals(gradient); } [NativeName("StringValueEquals")] extern private bool StringValueEquals(string value); internal bool ValueEquals(string value) { Verify(VerifyFlags.IteratorNotAtEnd); return StringValueEquals(value); } internal bool unsafeMode {get; set; } internal bool isValid { get { // SerializedProperty should only be accessed while the SerializedObject that created them is still alive // Without this check IsValidInternal will crash in that case if (m_NativePropertyPtr == IntPtr.Zero || m_SerializedObject == null || m_SerializedObject.m_NativeObjectPtr == IntPtr.Zero) return false; return IsValidInternal(); } } [NativeName("IsValid")] extern private bool IsValidInternal(); public uint contentHash { get { Verify(VerifyFlags.IteratorNotAtEnd); return GetContentHashInternal(); } } [NativeMethod("GetContentHash")] extern private uint GetContentHashInternal(); internal static class BindingsMarshaller { public static IntPtr ConvertToNative(SerializedProperty prop) => prop.m_NativePropertyPtr; public static SerializedProperty ConvertToManaged(IntPtr ptr) => new SerializedProperty(ptr); } } }
UnityCsReference/Editor/Mono/SerializedProperty.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/SerializedProperty.bindings.cs", "repo_id": "UnityCsReference", "token_count": 34292 }
346
// Unity 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 UnityEditor.Rendering; using UnityEngine; using UnityEngine.Bindings; using UnityEngine.Rendering; using UnityEngine.Scripting; using ShaderPlatform = UnityEngine.Rendering.GraphicsDeviceType; using UnityEditor.AssetImporters; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("UniversalEditorTests")] namespace UnityEditor { public enum PreprocessorOverride { UseProjectSettings = 0, ForcePlatformPreprocessor = 1, ForceCachingPreprocessor = 2 } [Serializable] [RequiredByNativeCode] [NativeHeader("Editor/Src/ShaderMenu.h")] public struct ShaderInfo { [SerializeField][NativeName("name")] internal string m_Name; [SerializeField][NativeName("supported")] internal bool m_Supported; [SerializeField][NativeName("hasErrors")] internal bool m_HasErrors; [SerializeField][NativeName("hasWarnings")] internal bool m_HasWarnings; public string name { get { return m_Name; } } public bool supported { get { return m_Supported; } } public bool hasErrors { get { return m_HasErrors; } } public bool hasWarnings { get { return m_HasWarnings; } } } [StructLayout(LayoutKind.Sequential)] public struct ShaderMessage : IEquatable<ShaderMessage> { public ShaderMessage(string msg, ShaderCompilerMessageSeverity sev = ShaderCompilerMessageSeverity.Error) { message = msg; messageDetails = string.Empty; file = string.Empty; line = 0; platform = ShaderCompilerPlatform.None; severity = sev; } public string message { get; } public string messageDetails { get; } public string file { get; } public int line { get; } public ShaderCompilerPlatform platform { get; } public ShaderCompilerMessageSeverity severity { get; } public bool Equals(ShaderMessage other) { return string.Equals(message, other.message) && string.Equals(messageDetails, other.messageDetails) && string.Equals(file, other.file) && line == other.line && platform == other.platform && severity == other.severity; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is ShaderMessage && Equals((ShaderMessage)obj); } public override int GetHashCode() { unchecked { var hashCode = (message != null ? message.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (messageDetails != null ? messageDetails.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (file != null ? file.GetHashCode() : 0); hashCode = (hashCode * 397) ^ line; hashCode = (hashCode * 397) ^ (int)platform; hashCode = (hashCode * 397) ^ (int)severity; return hashCode; } } public static bool operator==(ShaderMessage left, ShaderMessage right) { return left.Equals(right); } public static bool operator!=(ShaderMessage left, ShaderMessage right) { return !left.Equals(right); } } internal struct ShaderVariantEntriesData { public int[] passTypes; public string[] keywordLists; public string[] remainingKeywords; } [NativeHeader("Editor/Mono/ShaderUtil.bindings.h")] [NativeHeader("Editor/Src/ShaderData.h")] [NativeHeader("Editor/Src/ShaderMenu.h")] [NativeHeader("Runtime/Shaders/GpuPrograms/GpuProgramManager.h")] public sealed partial class ShaderUtil { extern internal static int GetAvailableShaderCompilerPlatforms(); extern internal static bool HasSurfaceShaders([NotNull] Shader s); extern internal static bool HasFixedFunctionShaders([NotNull] Shader s); extern internal static bool HasShaderSnippets([NotNull] Shader s); extern internal static bool HasInstancing([NotNull] Shader s); extern public static bool HasProceduralInstancing([NotNull] Shader s); extern internal static bool HasShadowCasterPass([NotNull] Shader s); extern internal static bool DoesIgnoreProjector([NotNull] Shader s); extern internal static int GetRenderQueue([NotNull] Shader s); extern internal static bool HasTangentChannel([NotNull] Shader s); extern internal static void FetchCachedMessages([NotNull] Shader s); extern public static int GetShaderMessageCount([NotNull] Shader s); public static ShaderMessage[] GetShaderMessages(Shader s) { return GetShaderMessages(s, (ShaderCompilerPlatform)0); } extern public static ShaderMessage[] GetShaderMessages([NotNull] Shader s, ShaderCompilerPlatform platform); extern public static void ClearShaderMessages([NotNull] Shader s); extern public static int GetComputeShaderMessageCount([NotNull] ComputeShader s); extern public static ShaderMessage[] GetComputeShaderMessages([NotNull] ComputeShader s); extern public static int GetRayTracingShaderMessageCount([NotNull] RayTracingShader s); extern public static ShaderMessage[] GetRayTracingShaderMessages([NotNull] RayTracingShader s); extern public static int GetRayGenerationShaderCount([NotNull] RayTracingShader s); extern public static string GetRayGenerationShaderName([NotNull] RayTracingShader s, int shaderIndex); extern public static int GetMissShaderCount([NotNull] RayTracingShader s); extern public static string GetMissShaderName([NotNull] RayTracingShader s, int shaderIndex); extern public static int GetMissShaderRayPayloadSize([NotNull] RayTracingShader s, int shaderIndex); extern public static int GetCallableShaderCount([NotNull] RayTracingShader s); extern public static string GetCallableShaderName([NotNull] RayTracingShader s, int shaderIndex); extern public static int GetCallableShaderParamSize([NotNull] RayTracingShader s, int shaderIndex); extern static public void ClearCachedData([NotNull] Shader s); extern internal static int GetTextureBindingIndex(Shader s, int texturePropertyID); extern internal static int GetTextureSamplerBindingIndex(Shader s, int texturePropertyID); extern internal static int GetLOD(Shader s); extern internal static int GetSRPBatcherCompatibilityCode(Shader s, int subShaderIdx); extern internal static string GetSRPBatcherCompatibilityIssueReason(Shader s, int subShaderIdx, int err); extern internal static ulong GetVariantCount(Shader s, bool usedBySceneOnly); extern internal static int GetComputeShaderPlatformCount(ComputeShader s); extern internal static ShaderPlatform GetComputeShaderPlatformType(ComputeShader s, int platformIndex); extern internal static int GetComputeShaderPlatformKernelCount(ComputeShader s, int platformIndex); extern internal static string GetComputeShaderPlatformKernelName(ComputeShader s, int platformIndex, int kernelIndex); extern internal static int GetRayTracingShaderPlatformCount(RayTracingShader s); extern internal static ShaderPlatform GetRayTracingShaderPlatformType(RayTracingShader s, int platformIndex); extern internal static bool IsRayTracingShaderValidForPlatform(RayTracingShader s, ShaderPlatform renderer); extern internal static void CalculateLightmapStrippingFromCurrentScene(); extern internal static void CalculateFogStrippingFromCurrentScene(); extern internal static Rect rawViewportRect { get; set; } extern internal static Rect rawScissorRect { get; set; } extern public static bool hardwareSupportsRectRenderTexture { get; } extern internal static bool hardwareSupportsFullNPOT { get; } public static extern bool disableShaderOptimization { get; set; } extern internal static void RequestLoadRenderDoc(); extern internal static void RecreateGfxDevice(); extern internal static void RecreateSkinnedMeshResources(); extern internal static void ReloadAllShaders(); extern public static Shader CreateShaderAsset(AssetImportContext context, string source, bool compileInitialShaderVariants); public static Shader CreateShaderAsset(string source) { return CreateShaderAsset(null, source, true); } public static Shader CreateShaderAsset(string source, bool compileInitialShaderVariants) { return CreateShaderAsset(null, source, compileInitialShaderVariants); } extern public static void UpdateShaderAsset(AssetImportContext context, [NotNull] Shader shader, [NotNull] string source, bool compileInitialShaderVariants); public static void UpdateShaderAsset(Shader shader, string source) { UpdateShaderAsset(null, shader, source, true); } public static void UpdateShaderAsset(Shader shader, string source, bool compileInitialShaderVariants) { UpdateShaderAsset(null, shader, source, compileInitialShaderVariants); } extern public static ComputeShader CreateComputeShaderAsset(AssetImportContext context, string source); [FreeFunction("GetShaderNameRegistry().AddShader")] extern public static void RegisterShader([NotNull] Shader shader); extern internal static void OpenCompiledShader(Shader shader, int mode, int externPlatformsMask, bool includeAllVariants, bool preprocessOnly, bool stripLineDirectives); extern internal static void OpenCompiledComputeShader(ComputeShader shader, bool allVariantsAndPlatforms, bool showPreprocessed, bool stripLineDirectives); extern internal static void OpenParsedSurfaceShader(Shader shader); extern internal static void OpenGeneratedFixedFunctionShader(Shader shader); extern internal static void OpenShaderCombinations(Shader shader, bool usedBySceneOnly); extern internal static void OpenSystemShaderIncludeError(string includeName, int line); extern internal static void SaveCurrentShaderVariantCollection(string path); extern internal static void ClearCurrentShaderVariantCollection(); extern internal static int GetCurrentShaderVariantCollectionShaderCount(); extern internal static int GetCurrentShaderVariantCollectionVariantCount(); extern internal static bool AddNewShaderToCollection(Shader shader, ShaderVariantCollection collection); private static extern ShaderVariantEntriesData GetShaderVariantEntriesFilteredInternal([NotNull] Shader shader, int maxEntries, string[] filterKeywords, ShaderVariantCollection excludeCollection); internal static void GetShaderVariantEntriesFiltered(Shader shader, int maxEntries, string[] filterKeywords, ShaderVariantCollection excludeCollection, out int[] passTypes, out string[] keywordLists, out string[] remainingKeywords) { ShaderVariantEntriesData data = GetShaderVariantEntriesFilteredInternal(shader, maxEntries, filterKeywords, excludeCollection); passTypes = data.passTypes; keywordLists = data.keywordLists; remainingKeywords = data.remainingKeywords; } extern internal static string[] GetAllGlobalKeywords(); extern internal static string[] GetShaderGlobalKeywords([NotNull] Shader shader); extern internal static string[] GetShaderLocalKeywords([NotNull] Shader shader); [FreeFunction] public static extern ShaderInfo[] GetAllShaderInfo(); [FreeFunction] public static extern ShaderInfo GetShaderInfo([NotNull] Shader shader); [FreeFunction] extern internal static string GetShaderPassSourceCode([NotNull] Shader shader, int subShaderIndex, int passId); [FreeFunction] extern internal static string GetShaderPassName([NotNull] Shader shader, int subShaderIndex, int passId); [FreeFunction] extern internal static int GetShaderActiveSubshaderIndex([NotNull] Shader shader); [FreeFunction] extern internal static int GetShaderSubshaderCount([NotNull] Shader shader); [FreeFunction] extern internal static int GetShaderTotalPassCount([NotNull] Shader shader, int subShaderIndex); [FreeFunction] extern internal static int GetSubshaderLOD([NotNull] Shader shader, int subShaderIndex); [FreeFunction] extern internal static bool IsGrabPass([NotNull] Shader shader, int subShaderIndex, int passId); [FreeFunction("ShaderUtil::GetShaderSerializedSubshaderCount")] extern internal static int GetShaderSerializedSubshaderCount([NotNull] Shader shader); [FreeFunction("ShaderUtil::FindSerializedSubShaderTagValue")] extern internal static int FindSerializedSubShaderTagValue([NotNull] Shader shader, int subShaderIndex, int tagName); [FreeFunction("ShaderUtil::FindPassTagValue")] extern internal static int FindPassTagValue([NotNull] Shader shader, int subShaderIndex, int passIndex, int tagName); extern public static bool anythingCompiling { get; } extern public static bool allowAsyncCompilation { get; set; } extern public static void SetAsyncCompilation([NotNull] CommandBuffer cmd, bool allow); extern public static void RestoreAsyncCompilation([NotNull] CommandBuffer cmd); extern public static bool IsPassCompiled([NotNull] Material material, int pass); extern public static void CompilePass([NotNull] Material material, int pass, bool forceSync = false); internal static MaterialProperty[] GetMaterialProperties(UnityEngine.Object[] mats) { return (MaterialProperty[])GetMaterialPropertiesImpl(mats); } extern private static System.Object GetMaterialPropertiesImpl(System.Object mats); internal static string[] GetMaterialPropertyNames(UnityEngine.Object[] mats) { return GetMaterialPropertyNamesImpl(mats); } extern private static string[] GetMaterialPropertyNamesImpl(System.Object mats); internal static MaterialProperty GetMaterialProperty(UnityEngine.Object[] mats, string name) { return (MaterialProperty)GetMaterialPropertyImpl(mats, name); } extern private static System.Object GetMaterialPropertyImpl(System.Object mats, string name); internal static MaterialProperty GetMaterialProperty(UnityEngine.Object[] mats, int propertyIndex) { return (MaterialProperty)GetMaterialPropertyByIndex(mats, propertyIndex); } extern private static System.Object GetMaterialPropertyByIndex(System.Object mats, int propertyIndex); internal static void ApplyProperty(MaterialProperty prop, int propertyMask, string undoName) { ApplyPropertyImpl(prop, propertyMask, undoName); } [NativeThrows] extern private static void ApplyPropertyImpl(System.Object prop, int propertyMask, string undoName); internal static void ApplyMaterialPropertyBlockToMaterialProperty(MaterialPropertyBlock propertyBlock, MaterialProperty materialProperty) { ApplyMaterialPropertyBlockToMaterialPropertyImpl(propertyBlock, materialProperty); } extern private static void ApplyMaterialPropertyBlockToMaterialPropertyImpl(System.Object propertyBlock, System.Object materialProperty); internal static void ApplyMaterialPropertyToMaterialPropertyBlock(MaterialProperty materialProperty, int propertyMask, MaterialPropertyBlock propertyBlock) { ApplyMaterialPropertyToMaterialPropertyBlockImpl(materialProperty, propertyMask, propertyBlock); } extern private static void ApplyMaterialPropertyToMaterialPropertyBlockImpl(System.Object materialProperty, int propertyMask, System.Object propertyBlock); public static string GetCustomEditorForRenderPipeline(Shader shader, string renderPipelineType) { if (shader == null) return null; shader.Internal_GetCustomEditorForRenderPipeline(renderPipelineType, out var rpEditor); return String.IsNullOrEmpty(rpEditor) ? null : rpEditor; } public static string GetCustomEditorForRenderPipeline(Shader shader, Type renderPipelineType) => GetCustomEditorForRenderPipeline(shader, renderPipelineType?.FullName); public static string GetCurrentCustomEditor(Shader shader) { if (shader == null) return null; var rpEditor = GetCustomEditorForRenderPipeline(shader, GraphicsSettings.currentRenderPipeline?.GetType()); return String.IsNullOrEmpty(rpEditor) ? shader.customEditor : rpEditor; } extern public static BuiltinShaderDefine[] GetShaderPlatformKeywordsForBuildTarget(ShaderCompilerPlatform shaderCompilerPlatform, BuildTarget buildTarget, GraphicsTier tier); public static BuiltinShaderDefine[] GetShaderPlatformKeywordsForBuildTarget(ShaderCompilerPlatform shaderCompilerPlatform, BuildTarget buildTarget) { return GetShaderPlatformKeywordsForBuildTarget(shaderCompilerPlatform, buildTarget, GraphicsTier.Tier1); } extern internal static ShaderData.VariantCompileInfo CompileShaderVariant([NotNull] Shader shader, int subShaderIndex, int passId, ShaderType shaderType, BuiltinShaderDefine[] platformKeywords, string[] keywords, ShaderCompilerPlatform shaderCompilerPlatform, BuildTarget buildTarget, GraphicsTier tier, bool outputForExternalTool); extern internal static ShaderData.PreprocessedVariant PreprocessShaderVariant([NotNull] Shader shader, int subShaderIndex, int passId, ShaderType shaderType, BuiltinShaderDefine[] platformKeywords, string[] keywords, ShaderCompilerPlatform shaderCompilerPlatform, BuildTarget buildTarget, GraphicsTier tier, bool stripLineDirectives); [FreeFunction("ShaderUtil::GetPassKeywords")] extern private static LocalKeyword[] GetPassAllStageKeywords(Shader s, in PassIdentifier passIdentifier); [FreeFunction("ShaderUtil::GetPassKeywords")] extern private static LocalKeyword[] GetPassStageKeywords(Shader s, in PassIdentifier passIdentifier, ShaderType shaderType); [FreeFunction("ShaderUtil::GetPassKeywords")] extern private static LocalKeyword[] GetPassStageKeywordsForAPI(Shader s, in PassIdentifier passIdentifier, ShaderType shaderType, ShaderCompilerPlatform shaderCompilerPlatform); [FreeFunction("ShaderUtil::PassHasKeyword")] extern private static bool PassAnyStageHasKeyword(Shader s, in PassIdentifier passIdentifier, uint keywordIndex); [FreeFunction("ShaderUtil::PassHasKeyword")] extern private static bool PassStageHasKeyword(Shader s, in PassIdentifier passIdentifier, uint keywordIndex, ShaderType shaderType); [FreeFunction("ShaderUtil::PassHasKeyword")] extern private static bool PassStageHasKeywordForAPI(Shader s, in PassIdentifier passIdentifier, uint keywordIndex, ShaderType shaderType, ShaderCompilerPlatform shaderCompilerPlatform); public static LocalKeyword[] GetPassKeywords(Shader s, in PassIdentifier passIdentifier) { return GetPassAllStageKeywords(s, passIdentifier); } public static LocalKeyword[] GetPassKeywords(Shader s, in PassIdentifier passIdentifier, ShaderType shaderType) { return GetPassStageKeywords(s, passIdentifier, shaderType); } public static LocalKeyword[] GetPassKeywords(Shader s, in PassIdentifier passIdentifier, ShaderType shaderType, ShaderCompilerPlatform shaderCompilerPlatform) { return GetPassStageKeywordsForAPI(s, passIdentifier, shaderType, shaderCompilerPlatform); } public static bool PassHasKeyword(Shader s, in PassIdentifier passIdentifier, in LocalKeyword keyword) { return PassAnyStageHasKeyword(s, passIdentifier, keyword.m_Index); } public static bool PassHasKeyword(Shader s, in PassIdentifier passIdentifier, in LocalKeyword keyword, ShaderType shaderType) { return PassStageHasKeyword(s, passIdentifier, keyword.m_Index, shaderType); } public static bool PassHasKeyword(Shader s, in PassIdentifier passIdentifier, in LocalKeyword keyword, ShaderType shaderType, ShaderCompilerPlatform shaderCompilerPlatform) { return PassStageHasKeywordForAPI(s, passIdentifier, keyword.m_Index, shaderType, shaderCompilerPlatform); } } }
UnityCsReference/Editor/Mono/ShaderUtil.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/ShaderUtil.bindings.cs", "repo_id": "UnityCsReference", "token_count": 7351 }
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; namespace UnityEditor { // Static Editor Flags [Flags] public enum StaticEditorFlags { // Considered static for lightmapping. [System.ComponentModel.Description("Contribute Global Illumination")] ContributeGI = 1, // Considered static for occlusion. OccluderStatic = 2, // Considered static for occlusion. OccludeeStatic = 16, // Consider for static batching. BatchingStatic = 4, [Obsolete("Enum member StaticEditorFlags.NavigationStatic has been deprecated. The precise selection of the objects is now done using NavMeshBuilder.CollectSources() and NavMeshBuildMarkup.", false)] // Considered static for navigation. NavigationStatic = 8, [Obsolete("Enum member StaticEditorFlags.OffMeshLinkGeneration has been deprecated. You can now use NavMeshBuilder.CollectSources() and NavMeshBuildMarkup to nominate the objects that will generate Off-Mesh Links.", false)] // Auto-generate OffMeshLink. OffMeshLinkGeneration = 32, ReflectionProbeStatic = 64, [Obsolete("Enum member StaticEditorFlags.LightmapStatic has been deprecated. Use StaticEditorFlags.ContributeGI instead. (UnityUpgradable) -> ContributeGI", false)] LightmapStatic = 1, } }
UnityCsReference/Editor/Mono/StaticEditorFlags.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/StaticEditorFlags.cs", "repo_id": "UnityCsReference", "token_count": 533 }
348
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor.Actions; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.EditorTools { [EditorToolContext, Icon(k_IconPath)] public sealed class GameObjectToolContext : EditorToolContext { const string k_IconPath = "GameObject Icon"; GameObjectToolContext() {} public override void PopulateMenu(DropdownMenu menu) { ContextMenuUtility.AddGameObjectEntriesTo(menu); } } }
UnityCsReference/Editor/Mono/Tools/GameObjectToolContext.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Tools/GameObjectToolContext.cs", "repo_id": "UnityCsReference", "token_count": 219 }
349
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using UnityEngine; namespace UnityEditor { // NOTE : Corresponds to the native TypeFlags [Flags] enum UnityTypeFlags { Abstract = 1 << 0, Sealed = 1 << 1, EditorOnly = 1 << 2 } [System.Diagnostics.DebuggerDisplay("{module}:{name}")] sealed partial class UnityType { public string name { get; private set; } public string nativeNamespace { get; private set; } public string module { get; private set; } public int persistentTypeID { get; private set; } public UnityType baseClass { get; private set; } public UnityTypeFlags flags { get; private set; } public bool isAbstract { get { return (flags & UnityTypeFlags.Abstract) != 0; } } public bool isSealed { get { return (flags & UnityTypeFlags.Sealed) != 0; } } public bool isEditorOnly { get { return (flags & UnityTypeFlags.EditorOnly) != 0; } } uint runtimeTypeIndex; uint descendantCount; public string qualifiedName { get { return hasNativeNamespace ? nativeNamespace + "::" + name : name; } } // NOTE : nativeNamespace == "" for types with no namespace so added this helper for convenience // in case the caller wasn't sure whether to compare nativeNamespace with null or empty public bool hasNativeNamespace { get { return nativeNamespace.Length > 0; } } public bool IsDerivedFrom(UnityType baseClass) { // NOTE : Type indices are ordered so all derived classes are immediately following the // base class allowing us to test inheritance with only a range check return (runtimeTypeIndex - baseClass.runtimeTypeIndex) < baseClass.descendantCount; } public static UnityType FindTypeByPersistentTypeID(int persistentTypeId) { UnityType result = null; ms_idToType.TryGetValue(persistentTypeId, out result); return result; } public static uint TypeCount { get { return (uint)ms_types.Length; } } public static UnityType GetTypeByRuntimeTypeIndex(uint index) { return ms_types[index]; } public static UnityType FindTypeByName(string name) { UnityType result = null; ms_nameToType.TryGetValue(name, out result); return result; } public static UnityType FindTypeByNameCaseInsensitive(string name) { return ms_types.FirstOrDefault(t => string.Equals(name, t.name, StringComparison.OrdinalIgnoreCase)); } public static ReadOnlyCollection<UnityType> GetTypes() { return ms_typesReadOnly; } static UnityType() { var types = UnityType.Internal_GetAllTypes(); ms_types = new UnityType[types.Length]; ms_idToType = new Dictionary<int, UnityType>(); ms_nameToType = new Dictionary<string, UnityType>(); for (int i = 0; i < types.Length; ++i) { // Types are sorted so base < derived and null baseclass is passed from native as 0xffffffff UnityType baseClass = null; if (types[i].baseClassIndex < types.Length) baseClass = ms_types[types[i].baseClassIndex]; var newType = new UnityType { runtimeTypeIndex = types[i].runtimeTypeIndex, descendantCount = types[i].descendantCount, name = types[i].className, nativeNamespace = types[i].classNamespace, module = types[i].module, persistentTypeID = types[i].persistentTypeID, baseClass = baseClass, flags = (UnityTypeFlags)types[i].flags }; Debug.Assert(types[i].runtimeTypeIndex == i); ms_types[i] = newType; ms_typesReadOnly = new ReadOnlyCollection<UnityType>(ms_types); ms_idToType[newType.persistentTypeID] = newType; ms_nameToType[newType.name] = newType; } } static UnityType[] ms_types; static ReadOnlyCollection<UnityType> ms_typesReadOnly; static Dictionary<int, UnityType> ms_idToType; static Dictionary<string, UnityType> ms_nameToType; } }
UnityCsReference/Editor/Mono/TypeSystem/UnityType.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/TypeSystem/UnityType.cs", "repo_id": "UnityCsReference", "token_count": 2038 }
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.Collections.Generic; using Unity.Properties; using UnityEngine; using UnityEngine.Internal; using UnityEngine.UIElements; namespace UnityEditor.UIElements { /// <summary> /// The base class for a search field. /// </summary> public abstract class SearchFieldBase<TextInputType, T> : VisualElement, INotifyValueChanged<T> where TextInputType : TextInputBaseField<T>, new() { internal static readonly BindingId valueProperty = nameof(value); internal static readonly BindingId placeholderTextProperty = nameof(placeholderText); private readonly Button m_SearchButton; private readonly Button m_CancelButton; private readonly TextInputType m_TextField; /// <summary> /// The text field used by the search field to draw and modify the search string. /// </summary> internal protected TextInputType textInputField { get { return m_TextField; } } /// <summary> /// The search button. /// </summary> protected Button searchButton { get { return m_SearchButton; } } /// <summary> /// The object currently being exposed by the field. /// </summary> /// <remarks> /// If the new value is different from the current value, this method notifies registered callbacks with a <see cref="ChangeEvent{T}"/>. /// </remarks> [CreateProperty] public T value { get { return m_TextField.value; } set { var previous = m_TextField.value; m_TextField.value = value; if (!EqualityComparer<T>.Default.Equals(m_TextField.value, previous)) NotifyPropertyChanged(valueProperty); } } /// <summary> /// USS class name of elements of this type. /// </summary> public static readonly string ussClassName = "unity-search-field-base"; /// <summary> /// USS class name of text elements in elements of this type. /// </summary> public static readonly string textUssClassName = ussClassName + "__text-field"; /// <summary> /// USS class name of text input elements in elements of this type. /// </summary> public static readonly string textInputUssClassName = textUssClassName + "__input"; /// <summary> /// USS class name of search buttons in elements of this type. /// </summary> public static readonly string searchButtonUssClassName = ussClassName + "__search-button"; /// <summary> /// USS class name of cancel buttons in elements of this type. /// </summary> public static readonly string cancelButtonUssClassName = ussClassName + "__cancel-button"; /// <summary> /// USS class name of cancel buttons in elements of this type, when they are off. /// </summary> public static readonly string cancelButtonOffVariantUssClassName = cancelButtonUssClassName + "--off"; /// <summary> /// USS class name of elements of this type, when they are using a popup menu. /// </summary> public static readonly string popupVariantUssClassName = ussClassName + "--popup"; [Serializable, ExcludeFromDocs] public abstract new class UxmlSerializedData : VisualElement.UxmlSerializedData { #pragma warning disable 649 [SerializeField] private string placeholderText; [SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags placeholderText_UxmlAttributeFlags; #pragma warning restore 649 [ExcludeFromDocs] public override void Deserialize(object obj) { base.Deserialize(obj); if (ShouldWriteAttributeValue(placeholderText_UxmlAttributeFlags)) { var e = (SearchFieldBase<TextInputType, T>)obj; e.placeholderText = placeholderText; } } } /// <summary> /// Defines <see cref="SearchFieldBase.UxmlTraits"/> for the <see cref="SearchFieldBase"/>. /// </summary> /// <remarks> /// This class defines the properties of a SearchFieldBase element that you can /// use in a UXML asset. /// </remarks> [Obsolete("UxmlTraits is deprecated and will be removed. Use UxmlElementAttribute instead.", false)] public new class UxmlTraits : VisualElement.UxmlTraits { /// <summary> /// Constructor. /// </summary> public UxmlTraits() { focusable.defaultValue = true; } } /// <summary> /// A short hint to help users understand what to enter in the field. /// </summary> [CreateProperty] public string placeholderText { get => m_TextField.textEdition.placeholder; set { if (value == m_TextField.textEdition.placeholder) return; m_TextField.textEdition.placeholder = value; NotifyPropertyChanged(placeholderTextProperty); } } protected SearchFieldBase() { isCompositeRoot = true; focusable = true; tabIndex = 0; excludeFromFocusRing = true; delegatesFocus = true; AddToClassList(ussClassName); m_SearchButton = new Button(() => {}) { name = "unity-search" }; m_SearchButton.AddToClassList(searchButtonUssClassName); m_SearchButton.focusable = false; hierarchy.Add(m_SearchButton); m_TextField = new TextInputType(); m_TextField.AddToClassList(textUssClassName); hierarchy.Add(m_TextField); m_TextField.RegisterValueChangedCallback(OnValueChanged); var textInput = m_TextField.Q(TextField.textInputUssName); textInput.RegisterCallback<KeyDownEvent>(OnTextFieldKeyDown, TrickleDown.TrickleDown); textInput.AddToClassList(textInputUssClassName); m_CancelButton = new Button(() => {}) { name = "unity-cancel" }; m_CancelButton.AddToClassList(cancelButtonUssClassName); m_CancelButton.AddToClassList(cancelButtonOffVariantUssClassName); hierarchy.Add(m_CancelButton); RegisterCallback<AttachToPanelEvent>(OnAttachToPanelEvent); m_CancelButton.clickable.clicked += OnCancelButtonClick; } private void OnAttachToPanelEvent(AttachToPanelEvent evt) { UpdateCancelButton(); } private void OnValueChanged(ChangeEvent<T> change) { UpdateCancelButton(); // We need to update it on value changed because in most cases the TextField is modified directly } /// <summary> /// Method used when clearing the text field. You should usually clear the value when overriding the method. /// </summary> protected abstract void ClearTextField(); private void OnTextFieldKeyDown(KeyDownEvent evt) { if (evt.keyCode == KeyCode.Escape) ClearTextField(); } private void OnCancelButtonClick() { ClearTextField(); } /// <summary> /// Sets the value for the toolbar search field without sending a change event. /// </summary> public virtual void SetValueWithoutNotify(T newValue) { m_TextField.SetValueWithoutNotify(newValue); UpdateCancelButton(); // We need to update it in that case because OnValueChanged will not be called } /// <summary> /// Tells if the field is empty. That meaning depends on the type of T. /// </summary> /// <param name="fieldValue">The value to check.</param> /// <returns>True if the parameter is empty. That meaning depends on the type of T.</returns> protected abstract bool FieldIsEmpty(T fieldValue); private void UpdateCancelButton() { m_CancelButton.EnableInClassList(cancelButtonOffVariantUssClassName, FieldIsEmpty(m_TextField.value)); } } }
UnityCsReference/Editor/Mono/UIElements/Controls/Toolbar/SearchFieldBase.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/UIElements/Controls/Toolbar/SearchFieldBase.cs", "repo_id": "UnityCsReference", "token_count": 3589 }
351
// 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.UIElements; namespace UnityEditor.UIElements { internal class EditorGenericDropdownMenuWindowContent : PopupWindowContent { internal Vector2 windowSize { get; set; } private GenericDropdownMenu m_GenericDropdownMenu; private static readonly string s_PopupUssClassName = GenericDropdownMenu.ussClassName + "__popup"; public EditorGenericDropdownMenuWindowContent(GenericDropdownMenu genericDropdownMenu) { m_GenericDropdownMenu = genericDropdownMenu; } public override Vector2 GetWindowSize() { if (windowSize == Vector2.zero) { return base.GetWindowSize(); } return windowSize; } public override void OnOpen() { base.OnOpen(); editorWindow.rootVisualElement.AddToClassList(s_PopupUssClassName); editorWindow.rootVisualElement.Add(m_GenericDropdownMenu.menuContainer); editorWindow.rootVisualElement.schedule.Execute(() => { if (editorWindow != null) { m_GenericDropdownMenu.contentContainer.Focus(); } }); } public override void OnGUI(Rect rect) { } } }
UnityCsReference/Editor/Mono/UIElements/GenericDropdownMenuWindowContent.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/UIElements/GenericDropdownMenuWindowContent.cs", "repo_id": "UnityCsReference", "token_count": 639 }
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.IO; using UnityEditor.Experimental; using UnityEngine; using UnityEngine.Bindings; using UnityEngine.UIElements; namespace UnityEditor.UIElements { [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal static class UIElementsEditorUtility { internal static readonly string s_DefaultCommonDarkStyleSheetPath = "StyleSheets/Generated/DefaultCommonDark.uss.asset"; internal static readonly string s_DefaultCommonLightStyleSheetPath = "StyleSheets/Generated/DefaultCommonLight.uss.asset"; static StyleSheet s_DefaultCommonDarkStyleSheet; static StyleSheet s_DefaultCommonLightStyleSheet; public const string hiddenClassName = "unity-hidden"; internal static string GetStyleSheetPathForFont(string sheetPath, string fontName) { return sheetPath.Replace(".uss", "_" + fontName.ToLowerInvariant() + ".uss"); } internal static string GetStyleSheetPathForCurrentFont(string sheetPath) { return GetStyleSheetPathForFont(sheetPath, EditorResources.currentFontName); } internal static StyleSheet LoadSkinnedStyleSheetForFont(int skin, string fontName) { return EditorGUIUtility.Load(GetStyleSheetPathForFont(skin == EditorResources.darkSkinIndex ? s_DefaultCommonDarkStyleSheetPath : s_DefaultCommonLightStyleSheetPath, fontName)) as StyleSheet; } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal static bool IsCommonDarkStyleSheetLoaded() { return s_DefaultCommonDarkStyleSheet != null; } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal static StyleSheet GetCommonDarkStyleSheet() { if (s_DefaultCommonDarkStyleSheet == null) { s_DefaultCommonDarkStyleSheet = LoadSkinnedStyleSheetForFont(EditorResources.darkSkinIndex, EditorResources.currentFontName); if (s_DefaultCommonDarkStyleSheet != null) s_DefaultCommonDarkStyleSheet.isDefaultStyleSheet = true; } return s_DefaultCommonDarkStyleSheet; } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal static bool IsCommonLightStyleSheetLoaded() { return s_DefaultCommonLightStyleSheet != null; } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal static StyleSheet GetCommonLightStyleSheet() { if (s_DefaultCommonLightStyleSheet == null) { s_DefaultCommonLightStyleSheet = LoadSkinnedStyleSheetForFont(EditorResources.normalSkinIndex, EditorResources.currentFontName); if (s_DefaultCommonLightStyleSheet != null) s_DefaultCommonLightStyleSheet.isDefaultStyleSheet = true; } return s_DefaultCommonLightStyleSheet; } static UIElementsEditorUtility() { } internal static int GetCursorId(StyleSheet sheet, StyleValueHandle handle) { var value = sheet.ReadEnum(handle); if (string.Equals(value, "arrow", StringComparison.OrdinalIgnoreCase)) return (int)MouseCursor.Arrow; else if (string.Equals(value, "text", StringComparison.OrdinalIgnoreCase)) return (int)MouseCursor.Text; else if (string.Equals(value, "resize-vertical", StringComparison.OrdinalIgnoreCase)) return (int)MouseCursor.ResizeVertical; else if (string.Equals(value, "resize-horizontal", StringComparison.OrdinalIgnoreCase)) return (int)MouseCursor.ResizeHorizontal; else if (string.Equals(value, "link", StringComparison.OrdinalIgnoreCase)) return (int)MouseCursor.Link; else if (string.Equals(value, "slide-arrow", StringComparison.OrdinalIgnoreCase)) return (int)MouseCursor.SlideArrow; else if (string.Equals(value, "resize-up-right", StringComparison.OrdinalIgnoreCase)) return (int)MouseCursor.ResizeUpRight; else if (string.Equals(value, "resize-up-left", StringComparison.OrdinalIgnoreCase)) return (int)MouseCursor.ResizeUpLeft; else if (string.Equals(value, "move-arrow", StringComparison.OrdinalIgnoreCase)) return (int)MouseCursor.MoveArrow; else if (string.Equals(value, "rotate-arrow", StringComparison.OrdinalIgnoreCase)) return (int)MouseCursor.RotateArrow; else if (string.Equals(value, "scale-arrow", StringComparison.OrdinalIgnoreCase)) return (int)MouseCursor.ScaleArrow; else if (string.Equals(value, "arrow-plus", StringComparison.OrdinalIgnoreCase)) return (int)MouseCursor.ArrowPlus; else if (string.Equals(value, "arrow-minus", StringComparison.OrdinalIgnoreCase)) return (int)MouseCursor.ArrowMinus; else if (string.Equals(value, "pan", StringComparison.OrdinalIgnoreCase)) return (int)MouseCursor.Pan; else if (string.Equals(value, "orbit", StringComparison.OrdinalIgnoreCase)) return (int)MouseCursor.Orbit; else if (string.Equals(value, "zoom", StringComparison.OrdinalIgnoreCase)) return (int)MouseCursor.Zoom; else if (string.Equals(value, "fps", StringComparison.OrdinalIgnoreCase)) return (int)MouseCursor.FPS; else if (string.Equals(value, "split-resize-up-down", StringComparison.OrdinalIgnoreCase)) return (int)MouseCursor.SplitResizeUpDown; else if (string.Equals(value, "split-resize-left-right", StringComparison.OrdinalIgnoreCase)) return (int)MouseCursor.SplitResizeLeftRight; else if (string.Equals(value, "not-allowed", StringComparison.OrdinalIgnoreCase)) return (int)MouseCursor.NotAllowed; return (int)MouseCursor.Arrow; } static readonly string k_DefaultStylesAppliedPropertyName = "DefaultStylesApplied"; internal static void AddDefaultEditorStyleSheets(VisualElement ve) { if (ve.styleSheets.count == 0 || ve.GetProperty(k_DefaultStylesAppliedPropertyName) == null) { if (EditorGUIUtility.isProSkin) { ve.styleSheets.Add(GetCommonDarkStyleSheet()); } else { ve.styleSheets.Add(GetCommonLightStyleSheet()); } ve.SetProperty(k_DefaultStylesAppliedPropertyName, true); } } internal static void ForceDarkStyleSheet(VisualElement ele) { if (!EditorGUIUtility.isProSkin) { var lightStyle = GetCommonLightStyleSheet(); var darkStyle = GetCommonDarkStyleSheet(); var e = ele; while (e != null) { if (e.styleSheets.Contains(lightStyle)) { e.styleSheets.Swap(lightStyle, darkStyle); break; } e = e.parent; } } } internal static void SetVisibility(VisualElement element, bool isVisible) { element.EnableInClassList(hiddenClassName, !isVisible); } internal static Action CreateDynamicVisibilityCallback(VisualElement element, Func<bool> visibilityCheck) { var messageCheck = () => SetVisibility(element, visibilityCheck.Invoke()); messageCheck(); return messageCheck; } internal static Action BindSerializedProperty<T>(BaseField<T> field, SerializedProperty property, Func<SerializedProperty, T> getter, Action<T, SerializedProperty> setter) where T : struct { BindingsStyleHelpers.RegisterRightClickMenu(field, property); field.TrackPropertyValue(property); field.AddToClassList(BaseField<bool>.alignedFieldUssClassName); field.RegisterValueChangedCallback(e => { setter.Invoke(e.newValue, property); }); var updateCallback = () => { field.value = getter.Invoke(property); field.schedule.Execute(() => BindingsStyleHelpers.UpdateElementStyle(field, property)); }; updateCallback?.Invoke(); return updateCallback; } internal static Action BindSerializedProperty(DropdownField dropdown, SerializedProperty property, GUIContent[] stringValues, int[] values) { var boolProperty = property.type == "bool"; dropdown.choices = new List<string>(stringValues.Length); foreach (var val in stringValues) dropdown.choices.Add(val.text); dropdown.TrackPropertyValue(property); return BindSerializedProperty(dropdown, property, p => { var value = boolProperty ? (property.boolValue ? 1 : 0) : property.intValue; return Array.IndexOf(values, value); }, (i, p) => { if (boolProperty) property.boolValue = i == 1; else property.intValue = values[i]; property.serializedObject.ApplyModifiedProperties(); dropdown.schedule.Execute(() => BindingsStyleHelpers.UpdateElementStyle(dropdown, property)); }); } internal static Action BindSerializedProperty(DropdownField dropdown, SerializedProperty property, Func<SerializedProperty, int> getter, Action<int, SerializedProperty> setter) { BindingsStyleHelpers.RegisterRightClickMenu(dropdown, property); dropdown.TrackPropertyValue(property); dropdown.AddToClassList(BaseField<bool>.alignedFieldUssClassName); dropdown.RegisterValueChangedCallback(e => { setter.Invoke(dropdown.index, property); }); var updateCallback = () => { dropdown.index = getter.Invoke(property); dropdown.schedule.Execute(() => BindingsStyleHelpers.UpdateElementStyle(dropdown, property)); }; updateCallback?.Invoke(); return updateCallback; } internal static Action BindSerializedProperty<T>(EnumField enumField, SerializedProperty property, Action<T> onValueChange = null) where T : struct, Enum, IConvertible { var boolProperty = property.type == "bool"; BindingsStyleHelpers.RegisterRightClickMenu(enumField, property); enumField.AddToClassList(BaseField<bool>.alignedFieldUssClassName); enumField.RegisterValueChangedCallback(e => { if (boolProperty) property.boolValue = Convert.ToInt32(e.newValue) == 1; else property.intValue = Convert.ToInt32(e.newValue); property.serializedObject.ApplyModifiedProperties(); onValueChange?.Invoke((T)e.newValue); }); var updateCallback = () => { foreach (T value in Enum.GetValues(typeof(T))) { var propertyValue = boolProperty ? (property.boolValue ? 1 : 0) : property.intValue; if (value.ToInt32(null) != propertyValue) continue; enumField.value = value; break; } enumField.schedule.Execute(() => BindingsStyleHelpers.UpdateElementStyle(enumField, property)); }; updateCallback?.Invoke(); return updateCallback; } } }
UnityCsReference/Editor/Mono/UIElements/UIElementsEditorUtility.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/UIElements/UIElementsEditorUtility.cs", "repo_id": "UnityCsReference", "token_count": 5632 }
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.IO; namespace UnityEditor.Utils { static class DirectoryExtensions { public static void DeleteRecursive(this string directoryPath) { Directory.Delete(directoryPath, true); } } }
UnityCsReference/Editor/Mono/Utils/DirectoryExtensions.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Utils/DirectoryExtensions.cs", "repo_id": "UnityCsReference", "token_count": 142 }
354
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEngine.Rendering; using System; using BuildTargetDiscovery = UnityEditor.BuildTargetDiscovery; using TargetAttributes = UnityEditor.BuildTargetDiscovery.TargetAttributes; namespace UnityEditor.Utils { internal class PerformanceChecks { static readonly string[] kShadersWithMobileVariants = { "VertexLit", "Diffuse", "Bumped Diffuse", "Bumped Specular", "Particles/Additive", "Particles/VertexLit Blended", "Particles/Alpha Blended", "Particles/Multiply", "RenderFX/Skybox" }; private static string FormattedTextContent(string localeString, params object[] args) { var content = EditorGUIUtility.TextContent(localeString); return UnityString.Format(content.text, args); } public static string CheckMaterial(Material mat, BuildTarget buildTarget) { if (mat == null || mat.shader == null) return null; string shaderName = mat.shader.name; int shaderLOD = ShaderUtil.GetLOD(mat.shader); bool hasMobileVariant = Array.Exists(kShadersWithMobileVariants, s => s == shaderName); bool isMobileTarget = BuildTargetDiscovery.PlatformHasFlag(buildTarget, TargetAttributes.HasIntegratedGPU); // Skip all performance-related checks if shader explicitly indicated that via a PerformanceChecks=False tag. bool noPerfChecks = (mat.GetTag("PerformanceChecks", true).ToLower() == "false"); if (!noPerfChecks) { // shaders that have faster / simpler equivalents already if (hasMobileVariant) { // has default white color? if (isMobileTarget && mat.HasProperty("_Color") && mat.GetColor("_Color") == new Color(1.0f, 1.0f, 1.0f, 1.0f)) { return FormattedTextContent("Shader is using white color which does nothing; Consider using {0} shader for performance.", "Mobile/" + shaderName); } // recommend Mobile particle shaders on mobile platforms if (isMobileTarget && shaderName.StartsWith("Particles/")) { return FormattedTextContent("Consider using {0} shader on this platform for performance.", "Mobile/" + shaderName); } // has default skybox tint color? if (shaderName == "RenderFX/Skybox" && mat.HasProperty("_Tint") && mat.GetColor("_Tint") == new Color(0.5f, 0.5f, 0.5f, 0.5f)) { return FormattedTextContent("Skybox shader is using gray color which does nothing; Consider using {0} shader for performance.", "Mobile/Skybox"); } } // recommend "something simpler" for complex shaders on mobile platforms if (shaderLOD >= 300 && isMobileTarget && !shaderName.StartsWith("Mobile/")) { return FormattedTextContent("Shader might be expensive on this platform. Consider switching to a simpler shader; look under Mobile shaders."); } // vertex lit shader with max. emission: recommend Unlit shaders if (shaderName.Contains("VertexLit") && mat.HasProperty("_Emission")) { bool isColor = false; Shader shader = mat.shader; int count = shader.GetPropertyCount(); for (int i = 0; i < count; i++) { if (shader.GetPropertyName(i) == "_Emission") { isColor = shader.GetPropertyType(i) == ShaderPropertyType.Color; break; } } if (isColor) { Color col = mat.GetColor("_Emission"); if (col.r >= 0.5f && col.g >= 0.5f && col.b >= 0.5f) { return FormattedTextContent("Looks like you're using VertexLit shader to simulate an unlit object (white emissive). Use one of Unlit shaders instead for performance."); } } } // normalmapped shader without a normalmap: recommend non-normal mapped one if (mat.HasProperty("_BumpMap") && mat.GetTexture("_BumpMap") == null) { return FormattedTextContent("Normal mapped shader without a normal map. Consider using a non-normal mapped shader for performance."); } } return null; } } }
UnityCsReference/Editor/Mono/Utils/PerformanceChecks.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Utils/PerformanceChecks.cs", "repo_id": "UnityCsReference", "token_count": 2417 }
355
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEditor.VersionControl { public interface ISettingsInspectorExtension { void OnInspectorGUI(); } }
UnityCsReference/Editor/Mono/VersionControl/Common/ISettingsInspectorExtension.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/VersionControl/Common/ISettingsInspectorExtension.cs", "repo_id": "UnityCsReference", "token_count": 95 }
356
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor.VersionControl; namespace UnityEditorInternal.VersionControl { // Menu used when right clicking on change lists only. As they are single select they will not get mixed up with asset selections. class ChangeSetContextMenu { // Get the selected change list. Only one valid at a time static ChangeSet GetChangeSet(ChangeSets changes) { if (changes.Count == 0) return null; return changes[0]; } //[MenuItem ("CONTEXT/Change/Submit...", true)] static bool SubmitTest(int userData) { ChangeSets sets = ListControl.FromID(userData).SelectedChangeSets; return (sets.Count > 0 && Provider.SubmitIsValid(sets[0], null)); } //[MenuItem ("CONTEXT/Change/Submit...", false, 100)] static void Submit(int userData) { ChangeSets set = ListControl.FromID(userData).SelectedChangeSets; ChangeSet change = GetChangeSet(set); if (change != null) WindowChange.Open(change, new AssetList(), true); } //[MenuItem ("CONTEXT/Change/Revert...", true)] static bool RevertTest(int userData) { ChangeSets list = ListControl.FromID(userData).SelectedChangeSets; return list.Count > 0; } //[MenuItem ("CONTEXT/Change/Revert...", false, 200)] static void Revert(int userData) { ChangeSets set = ListControl.FromID(userData).SelectedChangeSets; ChangeSet change = GetChangeSet(set); if (change != null) WindowRevert.Open(change); } //[MenuItem ("CONTEXT/Change/Revert Unchanged", true)] static bool RevertUnchangedTest(int userData) { ChangeSets sets = ListControl.FromID(userData).SelectedChangeSets; return sets.Count > 0; } //[MenuItem ("CONTEXT/Change/Revert Unchanged", false, 201)] static void RevertUnchanged(int userData) { ChangeSets sets = ListControl.FromID(userData).SelectedChangeSets; Provider.RevertChangeSets(sets, RevertMode.Unchanged).SetCompletionAction(CompletionAction.UpdatePendingWindow); Provider.InvalidateCache(); } //[MenuItem ("CONTEXT/Change/Resolve Conflicts...", true)] private static bool ResolveTest(int userData) { return ListControl.FromID(userData).SelectedChangeSets.Count > 0; } //[MenuItem ("CONTEXT/Change/Resolve Conflicts...", false, 202)] private static void Resolve(int userData) { ChangeSets set = ListControl.FromID(userData).SelectedChangeSets; ChangeSet change = GetChangeSet(set); if (change != null) WindowResolve.Open(change); } //[MenuItem ("CONTEXT/Change/New Changeset...", true)] static bool NewChangeSetTest(int userDatad) { return Provider.isActive; } //[MenuItem ("CONTEXT/Change/New Changeset...", false, 300)] static void NewChangeSet(int userData) { WindowChange.Open(new AssetList(), false); } //[MenuItem ("CONTEXT/Change/Edit Changeset...", true)] static bool EditChangeSetTest(int userData) { ChangeSets set = ListControl.FromID(userData).SelectedChangeSets; if (set.Count == 0) return false; ChangeSet change = GetChangeSet(set); return (change.id != "-1" && Provider.SubmitIsValid(set[0], null)); } //[MenuItem ("CONTEXT/Change/Edit Changeset...", false, 301)] static void EditChangeSet(int userData) { ChangeSets set = ListControl.FromID(userData).SelectedChangeSets; ChangeSet change = GetChangeSet(set); if (change != null) WindowChange.Open(change, new AssetList(), false); } //[MenuItem ("CONTEXT/Change/Delete Empty Changeset", true)] static bool DeleteChangeSetTest(int userData) { ListControl l = ListControl.FromID(userData); ChangeSets set = l.SelectedChangeSets; if (set.Count == 0) return false; ChangeSet change = GetChangeSet(set); if (change.id == "-1") return false; ListItem item = l.GetChangeSetItem(change); // TODO: Make changelist cache nonmanaged side to fix this! bool hasAssets = item != null && item.HasChildren && item.FirstChild.Asset != null && item.FirstChild.Name != ListControl.c_emptyChangeListMessage; if (!hasAssets) { Task task = Provider.ChangeSetStatus(change); task.Wait(); hasAssets = task.assetList.Count != 0; } return !hasAssets && Provider.DeleteChangeSetsIsValid(set); } //[MenuItem ("CONTEXT/Change/Delete Empty Changeset", false, 302)] static void DeleteChangeSet(int userData) { ChangeSets set = ListControl.FromID(userData).SelectedChangeSets; Provider.DeleteChangeSets(set).SetCompletionAction(CompletionAction.UpdatePendingWindow); } } }
UnityCsReference/Editor/Mono/VersionControl/UI/VCMenuChange.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/VersionControl/UI/VCMenuChange.cs", "repo_id": "UnityCsReference", "token_count": 2386 }
357
// Unity 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.InteropServices; namespace UnityEditor.VersionControl { [NativeType("Editor/Src/VersionControl/VCEnums.h")] public enum CompletionAction { UpdatePendingWindow = 1, OnChangeContentsPendingWindow = 2, OnIncomingPendingWindow = 3, OnChangeSetsPendingWindow = 4, OnGotLatestPendingWindow = 5, OnSubmittedChangeWindow = 6, OnAddedChangeWindow = 7, OnCheckoutCompleted = 8 } [Flags] public enum SubmitResult { OK = 1, Error = 2, ConflictingFiles = 4, UnaddedFiles = 8 } [NativeHeader("Editor/Src/VersionControl/VCTask.h")] [NativeHeader("Editor/Src/VersionControl/VC_bindings.h")] [UsedByNativeCode] [StructLayout(LayoutKind.Sequential)] public partial class Task { // The bindings generator will set the instance pointer in this field IntPtr m_Self; private Task(IntPtr self) { m_Self = self; } public extern void Wait(); public extern void SetCompletionAction(CompletionAction action); [NativeMethod("GetMonoAssetList")] extern Asset[] Internal_GetAssetList(); [NativeMethod("GetMonoChangeSets")] extern ChangeSet[] Internal_GetChangeSets(); [FreeFunction("VersionControlBindings::Task::Destroy", IsThreadSafe = true)] static extern void Destroy(IntPtr task); public void Dispose() { if (m_Self != IntPtr.Zero) { Destroy(m_Self); m_Self = IntPtr.Zero; } } internal Task() {} ~Task() { Dispose(); } public extern int userIdentifier { get; set; } public extern string text { get; } public extern string description { get; } public extern bool success { get; } public extern int secondsSpent { get; } public extern int progressPct { get; } public extern string progressMessage { get; } public extern int resultCode { get; } public extern Message[] messages { [NativeName("GetMonoMessages")] get; } internal static class BindingsMarshaller { public static IntPtr ConvertToNative(Task task) => task.m_Self; public static Task ConvertToManaged(IntPtr ptr) => new Task(ptr); } } }
UnityCsReference/Editor/Mono/VersionControl/VCTask.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/VersionControl/VCTask.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1160 }
358
// // File autogenerated from Include/C/Baselib_WakeupFallbackStrategy.h // using System; using System.Runtime.InteropServices; using UnityEngine.Bindings; using size_t = System.UIntPtr; namespace Unity.Baselib.LowLevel { [NativeHeader("baselib/CSharp/BindingsUnity/Baselib_WakeupFallbackStrategy.gen.binding.h")] internal static unsafe partial class Binding { /// <summary> /// Can be used to control the wakeup behavior on platforms that don't support waking up a specific number of thread. /// Syscalls don't come for free so you need to weigh the cost of doing multiple syscalls against the cost of having lots of context switches. /// </summary> /// <remarks> /// There are however two easy cases. /// * When you only want to notify one thread use Baselib_WakeupFallbackStrategy_OneByOne. /// * When you want to wakeup all threads use Baselib_WakeupFallbackStrategy_All /// /// For the not so easy cases. /// * Use Baselib_WakeupFallbackStrategy_OneByOne when wake count is low, or significantly lower than the number of waiting threads. /// * Use Baselib_WakeupFallbackStrategy_All if wake count is high. /// </remarks> public enum Baselib_WakeupFallbackStrategy : Int32 { /// <summary>Do one syscall for each waiting thread or notification.</summary> OneByOne = 0x0, /// <summary>Do a single syscall to wake all waiting threads.</summary> All = 0x1, } } }
UnityCsReference/External/baselib/baselib/CSharp/BindingsUnity/Baselib_WakeupFallbackStrategy.gen.binding.cs/0
{ "file_path": "UnityCsReference/External/baselib/baselib/CSharp/BindingsUnity/Baselib_WakeupFallbackStrategy.gen.binding.cs", "repo_id": "UnityCsReference", "token_count": 580 }
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.Runtime.InteropServices; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using Unity.Jobs; using UnityEngine.Bindings; using UnityEngine.AI; namespace UnityEngine.Experimental.AI { [Obsolete("The experimental PolygonId struct has been deprecated without replacement.")] public struct PolygonId : IEquatable<PolygonId> { internal ulong polyRef; public bool IsNull() { return polyRef == 0; } public static bool operator==(PolygonId x, PolygonId y) { return x.polyRef == y.polyRef; } public static bool operator!=(PolygonId x, PolygonId y) { return x.polyRef != y.polyRef; } public override int GetHashCode() { return polyRef.GetHashCode(); } public bool Equals(PolygonId rhs) { return rhs == this; } public override bool Equals(object obj) { if (obj == null || !(obj is PolygonId)) return false; var rhs = (PolygonId)obj; return rhs == this; } } [Obsolete("The experimental NavMeshLocation struct has been deprecated without replacement.")] public struct NavMeshLocation { public PolygonId polygon { get; } public Vector3 position { get; } internal NavMeshLocation(Vector3 position, PolygonId polygon) { this.position = position; this.polygon = polygon; } } //public struct NavMeshHit //{ // public NavMeshLocation position; // public Vector3 normal; // public float distance; // public int area; //Think if this should be a struct etc // public bool hit; //} //public struct NavMeshPolyData //{ // internal unsafe fixed ulong neighbors[6]; // internal unsafe fixed float vertices[6 * 3]; // internal int areaType; // internal int vertexCount; //} //public struct NavMeshSegment //{ // public Vector3 begin; // public Vector3 end; //} // Keep in sync with the values in NavMeshTypes.h [Obsolete("The experimental PathQueryStatus struct has been deprecated without replacement.")] [Flags] public enum PathQueryStatus { // High level status. Failure = 1 << 31, Success = 1 << 30, InProgress = 1 << 29, // Detail information for status. StatusDetailMask = 0x0ffffff, WrongMagic = 1 << 0, // Input data is not recognized. WrongVersion = 1 << 1, // Input data is in wrong version. OutOfMemory = 1 << 2, // Operation ran out of memory. InvalidParam = 1 << 3, // An input parameter was invalid. BufferTooSmall = 1 << 4, // Result buffer for the query was too small to store all results. OutOfNodes = 1 << 5, // Query ran out of nodes during search. PartialResult = 1 << 6 // Query did not reach the end location, returning best guess. } // Flags describing polygon properties. Keep in sync with the enum declared in NavMesh.h [Obsolete("The experimental NavMeshPolyTypes enum has been deprecated without replacement.")] public enum NavMeshPolyTypes { Ground = 0, // Regular ground polygons. OffMeshConnection = 1 // Off-mesh connections. } [Obsolete("The experimental NavMeshWorld struct has been deprecated without replacement.")] [StaticAccessor("NavMeshWorldBindings", StaticAccessorType.DoubleColon)] public struct NavMeshWorld { internal IntPtr world; public bool IsValid() { return world != IntPtr.Zero; } public static extern NavMeshWorld GetDefaultWorld(); static extern void AddDependencyInternal(IntPtr navmesh, JobHandle handle); public void AddDependency(JobHandle job) { if (!IsValid()) throw new InvalidOperationException("The NavMesh world is invalid."); AddDependencyInternal(world, job); } } [Obsolete("The experimental NavMeshQuery struct has been deprecated without replacement.")] [NativeContainer] [StructLayout(LayoutKind.Sequential)] [NativeHeader("Modules/AI/NavMeshExperimental.bindings.h")] [NativeHeader("Modules/AI/Public/NavMeshBindingTypes.h")] [NativeHeader("Runtime/Math/Matrix4x4.h")] [StaticAccessor("NavMeshQueryBindings", StaticAccessorType.DoubleColon)] public struct NavMeshQuery : IDisposable { [NativeDisableUnsafePtrRestriction] internal IntPtr m_NavMeshQuery; const string k_NoBufferAllocatedErrorMessage = "This query has no buffer allocated for pathfinding operations. " + "Create a different NavMeshQuery with an explicit node pool size."; internal AtomicSafetyHandle m_Safety; public NavMeshQuery(NavMeshWorld world, Allocator allocator, int pathNodePoolSize = 0) { if (!world.IsValid()) throw new ArgumentNullException("world", "Invalid world"); if (pathNodePoolSize < 0 || pathNodePoolSize > ushort.MaxValue) throw new ArgumentException($"The path node pool size ({pathNodePoolSize}) must be greater than or equal to 0 and less than {ushort.MaxValue + 1}."); m_NavMeshQuery = Create(world, pathNodePoolSize); UnsafeUtility.LeakRecord(m_NavMeshQuery, LeakCategory.NavMeshQuery, 0); AtomicSafetyHandle.CreateHandle(out m_Safety, allocator); AddQuerySafety(m_NavMeshQuery, m_Safety); } public void Dispose() { // When the NavMesh destroys itself it will disable read or write access. // Since it has been deallocated, we shouldn't deregister the query from it... // We need to extract removeQuery before disposing the handle, // because the atomic safety handle stores that state. var removeQuery = AtomicSafetyHandle.GetAllowReadOrWriteAccess(m_Safety); AtomicSafetyHandle.DisposeHandle(ref m_Safety); if (removeQuery) RemoveQuerySafety(m_NavMeshQuery, m_Safety); UnsafeUtility.LeakErase(m_NavMeshQuery, LeakCategory.NavMeshQuery); Destroy(m_NavMeshQuery); m_NavMeshQuery = IntPtr.Zero; } static extern IntPtr Create(NavMeshWorld world, int nodePoolSize); static extern void Destroy(IntPtr navMeshQuery); static extern void AddQuerySafety(IntPtr navMeshQuery, AtomicSafetyHandle handle); static extern void RemoveQuerySafety(IntPtr navMeshQuery, AtomicSafetyHandle handle); [ThreadSafe] static extern bool HasNodePool(IntPtr navMeshQuery); public unsafe PathQueryStatus BeginFindPath(NavMeshLocation start, NavMeshLocation end, int areaMask = NavMesh.AllAreas, NativeArray<float> costs = new NativeArray<float>()) { AtomicSafetyHandle.CheckWriteAndThrow(m_Safety); if (!HasNodePool(m_NavMeshQuery)) throw new InvalidOperationException(k_NoBufferAllocatedErrorMessage); const int kAreaCount = 32; if (costs.Length != 0) { if (costs.Length != kAreaCount) throw new ArgumentException( string.Format("The number of costs ({0}) must be exactly {1}, one for each possible area type.", costs.Length, kAreaCount) , "costs"); for (var i = 0; i < costs.Length; i++) { if (costs[i] < 1.0f) throw new ArgumentException( string.Format("The area cost ({0}) at index ({1}) must be greater or equal to 1.", costs[i], i), "costs"); } } if (!IsValid(start.polygon)) throw new ArgumentException("The start location doesn't belong to any active NavMesh surface.", "start"); if (!IsValid(end.polygon)) throw new ArgumentException("The end location doesn't belong to any active NavMesh surface.", "end"); var agentTypeStart = GetAgentTypeIdForPolygon(start.polygon); var agentTypeEnd = GetAgentTypeIdForPolygon(end.polygon); if (agentTypeStart != agentTypeEnd) throw new ArgumentException(string.Format( "The start and end locations belong to different NavMesh surfaces, with agent type IDs {0} and {1}.", agentTypeStart, agentTypeEnd)); void* costsPtr = costs.Length > 0 ? costs.GetUnsafePtr() : null; return BeginFindPath(m_NavMeshQuery, start, end, areaMask, costsPtr); } public PathQueryStatus UpdateFindPath(int iterations, out int iterationsPerformed) { AtomicSafetyHandle.CheckWriteAndThrow(m_Safety); if (!HasNodePool(m_NavMeshQuery)) throw new InvalidOperationException(k_NoBufferAllocatedErrorMessage); return UpdateFindPath(m_NavMeshQuery, iterations, out iterationsPerformed); } public PathQueryStatus EndFindPath(out int pathSize) { AtomicSafetyHandle.CheckWriteAndThrow(m_Safety); if (!HasNodePool(m_NavMeshQuery)) throw new InvalidOperationException(k_NoBufferAllocatedErrorMessage); return EndFindPath(m_NavMeshQuery, out pathSize); } public unsafe int GetPathResult(NativeSlice<PolygonId> path) { AtomicSafetyHandle.CheckWriteAndThrow(m_Safety); if (!HasNodePool(m_NavMeshQuery)) throw new InvalidOperationException(k_NoBufferAllocatedErrorMessage); return GetPathResult(m_NavMeshQuery, path.GetUnsafePtr(), path.Length); } [ThreadSafe] static extern unsafe PathQueryStatus BeginFindPath(IntPtr navMeshQuery, NavMeshLocation start, NavMeshLocation end, int areaMask, void* costs); [ThreadSafe] static extern PathQueryStatus UpdateFindPath(IntPtr navMeshQuery, int iterations, out int iterationsPerformed); [ThreadSafe] static extern PathQueryStatus EndFindPath(IntPtr navMeshQuery, out int pathSize); [ThreadSafe] static extern unsafe int GetPathResult(IntPtr navMeshQuery, void* path, int maxPath); // If BeginFindPath/UpdateFindPath/EndFindPath existing NativeArray become invalid... // extern NavMeshPathStatus GetPath(out NativeArray<PolygonId> outputPath); //void DidScheduleJob(JobHandle handle); [ThreadSafe] static extern bool IsValidPolygon(IntPtr navMeshQuery, PolygonId polygon); public bool IsValid(PolygonId polygon) { AtomicSafetyHandle.CheckReadAndThrow(m_Safety); return polygon.polyRef != 0 && IsValidPolygon(m_NavMeshQuery, polygon); } public bool IsValid(NavMeshLocation location) { return IsValid(location.polygon); } [ThreadSafe] static extern int GetAgentTypeIdForPolygon(IntPtr navMeshQuery, PolygonId polygon); public int GetAgentTypeIdForPolygon(PolygonId polygon) { AtomicSafetyHandle.CheckReadAndThrow(m_Safety); return GetAgentTypeIdForPolygon(m_NavMeshQuery, polygon); } [ThreadSafe] static extern bool IsPositionInPolygon(IntPtr navMeshQuery, Vector3 position, PolygonId polygon); [ThreadSafe] static extern PathQueryStatus GetClosestPointOnPoly(IntPtr navMeshQuery, PolygonId polygon, Vector3 position, out Vector3 nearest); public NavMeshLocation CreateLocation(Vector3 position, PolygonId polygon) { AtomicSafetyHandle.CheckReadAndThrow(m_Safety); Vector3 nearest; var status = GetClosestPointOnPoly(m_NavMeshQuery, polygon, position, out nearest); return (status & PathQueryStatus.Success) != 0 ? new NavMeshLocation(nearest, polygon) : new NavMeshLocation(); } [ThreadSafe] static extern NavMeshLocation MapLocation(IntPtr navMeshQuery, Vector3 position, Vector3 extents, int agentTypeID, int areaMask = NavMesh.AllAreas); public NavMeshLocation MapLocation(Vector3 position, Vector3 extents, int agentTypeID, int areaMask = NavMesh.AllAreas) { AtomicSafetyHandle.CheckReadAndThrow(m_Safety); return MapLocation(m_NavMeshQuery, position, extents, agentTypeID, areaMask); } [ThreadSafe] static extern unsafe void MoveLocations(IntPtr navMeshQuery, void* locations, void* targets, void* areaMasks, int count); public unsafe void MoveLocations(NativeSlice<NavMeshLocation> locations, NativeSlice<Vector3> targets, NativeSlice<int> areaMasks) { if (locations.Length != targets.Length || locations.Length != areaMasks.Length) throw new ArgumentException("locations.Length, targets.Length and areaMasks.Length must be equal"); AtomicSafetyHandle.CheckReadAndThrow(m_Safety); MoveLocations(m_NavMeshQuery, locations.GetUnsafePtr(), targets.GetUnsafeReadOnlyPtr(), areaMasks.GetUnsafeReadOnlyPtr(), locations.Length); } [ThreadSafe] static extern unsafe void MoveLocationsInSameAreas(IntPtr navMeshQuery, void* locations, void* targets, int count, int areaMask); public unsafe void MoveLocationsInSameAreas(NativeSlice<NavMeshLocation> locations, NativeSlice<Vector3> targets, int areaMask = NavMesh.AllAreas) { if (locations.Length != targets.Length) throw new ArgumentException("locations.Length and targets.Length must be equal"); AtomicSafetyHandle.CheckReadAndThrow(m_Safety); MoveLocationsInSameAreas(m_NavMeshQuery, locations.GetUnsafePtr(), targets.GetUnsafeReadOnlyPtr(), locations.Length, areaMask); } [ThreadSafe] static extern NavMeshLocation MoveLocation(IntPtr navMeshQuery, NavMeshLocation location, Vector3 target, int areaMask); public NavMeshLocation MoveLocation(NavMeshLocation location, Vector3 target, int areaMask = NavMesh.AllAreas) { AtomicSafetyHandle.CheckReadAndThrow(m_Safety); return MoveLocation(m_NavMeshQuery, location, target, areaMask); } [ThreadSafe] static extern bool GetPortalPoints(IntPtr navMeshQuery, PolygonId polygon, PolygonId neighbourPolygon, out Vector3 left, out Vector3 right); public bool GetPortalPoints(PolygonId polygon, PolygonId neighbourPolygon, out Vector3 left, out Vector3 right) { AtomicSafetyHandle.CheckReadAndThrow(m_Safety); return GetPortalPoints(m_NavMeshQuery, polygon, neighbourPolygon, out left, out right); } [ThreadSafe] static extern Matrix4x4 PolygonLocalToWorldMatrix(IntPtr navMeshQuery, PolygonId polygon); public Matrix4x4 PolygonLocalToWorldMatrix(PolygonId polygon) { AtomicSafetyHandle.CheckReadAndThrow(m_Safety); return PolygonLocalToWorldMatrix(m_NavMeshQuery, polygon); } [ThreadSafe] static extern Matrix4x4 PolygonWorldToLocalMatrix(IntPtr navMeshQuery, PolygonId polygon); public Matrix4x4 PolygonWorldToLocalMatrix(PolygonId polygon) { AtomicSafetyHandle.CheckReadAndThrow(m_Safety); return PolygonWorldToLocalMatrix(m_NavMeshQuery, polygon); } [ThreadSafe] static extern NavMeshPolyTypes GetPolygonType(IntPtr navMeshQuery, PolygonId polygon); public NavMeshPolyTypes GetPolygonType(PolygonId polygon) { AtomicSafetyHandle.CheckReadAndThrow(m_Safety); return GetPolygonType(m_NavMeshQuery, polygon); } //NavMeshStatus MoveAlongSurface(NavMeshLocation location, Vector3 targetPosition, int agentTypeID, int areaMask, // out NavMeshLocation outputLocation, NativeArray<PolygonId> visitedBuffer, out int actualVisited); // Trace a ray between two points on the NavMesh. [ThreadSafe] static extern unsafe PathQueryStatus Raycast(IntPtr navMeshQuery, NavMeshLocation start, Vector3 targetPosition, int areaMask, void* costs, out NavMeshHit hit, void* path, out int pathCount, int maxPath); public unsafe PathQueryStatus Raycast(out NavMeshHit hit, NavMeshLocation start, Vector3 targetPosition, int areaMask = NavMesh.AllAreas, NativeArray<float> costs = new NativeArray<float>()) { const int kAreaCount = 32; AtomicSafetyHandle.CheckReadAndThrow(m_Safety); if (costs.Length != 0) { if (costs.Length != kAreaCount) throw new ArgumentException( string.Format("The number of costs ({0}) must be exactly {1}, one for each possible area type.", costs.Length, kAreaCount), "costs"); } int pathCount; var costsPtr = costs.Length == kAreaCount ? costs.GetUnsafePtr() : null; var status = Raycast(m_NavMeshQuery, start, targetPosition, areaMask, costsPtr, out hit, null, out pathCount, 0); status &= ~PathQueryStatus.BufferTooSmall; return status; } public unsafe PathQueryStatus Raycast(out NavMeshHit hit, NativeSlice<PolygonId> path, out int pathCount, NavMeshLocation start, Vector3 targetPosition, int areaMask = NavMesh.AllAreas, NativeArray<float> costs = new NativeArray<float>()) { const int kAreaCount = 32; AtomicSafetyHandle.CheckReadAndThrow(m_Safety); if (costs.Length != 0) { if (costs.Length != kAreaCount) throw new ArgumentException( string.Format("The number of costs ({0}) must be exactly {1}, one for each possible area type.", costs.Length, kAreaCount), "costs"); } var costsPtr = costs.Length == kAreaCount ? costs.GetUnsafePtr() : null; var pathPtr = path.Length > 0 ? path.GetUnsafePtr() : null; var maxPath = pathPtr != null ? path.Length : 0; var status = Raycast(m_NavMeshQuery, start, targetPosition, areaMask, costsPtr, out hit, pathPtr, out pathCount, maxPath); return status; } [ThreadSafe] static extern unsafe PathQueryStatus GetEdgesAndNeighbors(IntPtr navMeshQuery, PolygonId node, int maxVerts, int maxNei, void* verts, void* neighbors, void* edgeIndices, out int vertCount, out int neighborsCount); public unsafe PathQueryStatus GetEdgesAndNeighbors(PolygonId node, NativeSlice<Vector3> edgeVertices, NativeSlice<PolygonId> neighbors, NativeSlice<byte> edgeIndices, out int verticesCount, out int neighborsCount) { AtomicSafetyHandle.CheckReadAndThrow(m_Safety); if (edgeIndices.Length != neighbors.Length && neighbors.Length > 0 && edgeIndices.Length > 0) { throw new ArgumentException($"The length of the {nameof(edgeIndices)} buffer ({edgeIndices.Length}) " + $"needs to be the same as that of the {nameof(neighbors)} buffer ({neighbors.Length}) " + "because the elements from the two arrays will pair up at the same index."); } var vertPtr = edgeVertices.Length > 0 ? edgeVertices.GetUnsafePtr() : null; var neiPtr = neighbors.Length > 0 ? neighbors.GetUnsafePtr() : null; var edgesPtr = edgeIndices.Length > 0 ? edgeIndices.GetUnsafePtr() : null; var maxVertices = edgeVertices.Length; var maxNeighbors = neighbors.Length > 0 ? neighbors.Length : edgeIndices.Length; var status = GetEdgesAndNeighbors(m_NavMeshQuery, node, maxVertices, maxNeighbors, vertPtr, neiPtr, edgesPtr, out verticesCount, out neighborsCount); return status; } //// Polygon Queries //public NavMeshPolyData GetPolygon(PolygonId poly); //public void GetPolygon(NativeArray<PolygonId> polygonIDs, NativeArray<NavMeshPolyData> polygons); //public void GetPolygons(MappedPosition position, float distance, NativeList<NavMeshPolyData> polygons); //public static void LocalizePolygonIndices(NativeArray<NavMeshPolyData> polygons); //// Segments //public NativeArray<NavMeshSegment> FindBoundarySegments (MappedPosition position, float distance, Allocator allocator); //// Voxel rasterize //public void Rasterize (MappedPosition position, Quaternion orientation, float cellWidth, float cellHeight, NativeArray2D<bool> grid); //// DetailMesh queries //void ProjectToDetailMesh(NativeArray<MappedPosition> positions, NativeArray<Vector3> outputPositions); } }
UnityCsReference/Modules/AI/NavMeshExperimental.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/AI/NavMeshExperimental.bindings.cs", "repo_id": "UnityCsReference", "token_count": 8500 }
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; namespace UnityEngine.Accessibility; /// <summary> /// Provides access to the accessibility settings for the current platform. /// </summary> /// <remarks> /// The currently supported platforms are: /// ///- <see cref="RuntimePlatform.Android"/> ///- <see cref="RuntimePlatform.IPhonePlayer"/> /// /// This class also provides events that are invoked when the user changes accessibility settings. /// </remarks> public static partial class AccessibilitySettings { /// <summary> /// Gets the font scale set by the user in the system settings. /// </summary> /// <remarks> /// For all the supported platforms, refer to /// <see cref="AccessibilitySettings"/>. /// </remarks> public static float fontScale => GetFontScale(); /// <summary> /// Checks whether or not bold text is enabled in the system settings. /// </summary> /// <remarks> /// For all the supported platforms, refer to /// <see cref="AccessibilitySettings"/>. /// /// For Android, this requires at least API level 31. However, it might not /// be supported on non-stock Android. Here, non-stock refers to versions /// of Android that have been modified by the device manufacturer. /// </remarks> public static bool isBoldTextEnabled => IsBoldTextEnabled(); /// <summary> /// Checks whether or not closed captioning is enabled in the system /// settings. /// </summary> /// <remarks> /// For all the supported platforms, refer to /// <see cref="AccessibilitySettings"/>. /// </remarks> public static bool isClosedCaptioningEnabled => IsClosedCaptioningEnabled(); /// <summary> /// Event that is invoked on the main thread when the user changes the /// font scale in the system settings. /// </summary> /// <remarks> /// For all the supported platforms, refer to /// <see cref="AccessibilitySettings"/>. /// </remarks> public static event Action<float> fontScaleChanged; internal static void InvokeFontScaleChanged(float newFontScale) { fontScaleChanged?.Invoke(newFontScale); } /// <summary> /// Event that is invoked on the main thread when the user changes the /// bold text setting in the system settings. /// </summary> /// <remarks> /// This is only supported on iOS. On Android, the app restarts when the /// user changes the bold text setting in the system settings, so this event /// is not necessary. /// </remarks> public static event Action<bool> boldTextStatusChanged; internal static void InvokeBoldTextStatusChanged(bool enabled) { boldTextStatusChanged?.Invoke(enabled); } /// <summary> /// Event that is invoked on the main thread when the user changes the /// closed captioning setting in the system settings. /// </summary> /// <remarks> /// For all the supported platforms, refer to /// <see cref="AccessibilitySettings"/>. /// </remarks> public static event Action<bool> closedCaptioningStatusChanged; internal static void InvokeClosedCaptionStatusChanged(bool enabled) { closedCaptioningStatusChanged?.Invoke(enabled); } }
UnityCsReference/Modules/Accessibility/Managed/AccessibilitySettings.cs/0
{ "file_path": "UnityCsReference/Modules/Accessibility/Managed/AccessibilitySettings.cs", "repo_id": "UnityCsReference", "token_count": 1023 }
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 System.IO; using System.Collections.Generic; using UnityEngine; namespace UnityEditor.AdaptivePerformance { [UnityEngine.Internal.ExcludeFromDocs] class AdaptivePerformanceInstaller : SettingsProvider { static string s_ManagementPackageId = "com.unity.adaptiveperformance"; static string s_ManagementPackagePath = $"Packages/{s_ManagementPackageId}/package.json"; private PackageManager.Requests.AddRequest m_AddManagementRequest = null; private static class Content { internal const string s_InstallationHelpText = "In order to use Adaptive Performance you need to install the Adaptive Performance package. Clicking the button below will install the latest Adaptive Performance package and allow you to configure your project for Adaptive Performance."; internal static readonly string s_SettingsRootTitle = "Project/Adaptive Performance"; internal static readonly Uri s_DocUri = new Uri("https://docs.unity3d.com/Packages/com.unity.adaptiveperformance@latest"); internal static readonly GUIContent s_AddAdaptivePerformance = EditorGUIUtility.TrTextContent(L10n.Tr("Install Adaptive Performance")); internal static readonly GUIContent s_DownloadingText = new GUIContent(L10n.Tr("Downloading Adaptive Performance ...")); internal static readonly GUIContent s_InstallingText = new GUIContent(L10n.Tr("Installing Adaptive Performance ...")); } private static class Styles { public static readonly GUIStyle verticalStyle; public static readonly GUIStyle linkLabel; public static readonly GUIStyle textLabel; static Styles() { verticalStyle = new GUIStyle(EditorStyles.inspectorFullWidthMargins); verticalStyle.margin = new RectOffset(10, 10, 10, 10); linkLabel = new GUIStyle(EditorStyles.linkLabel); linkLabel.fontSize = EditorStyles.miniLabel.fontSize; linkLabel.wordWrap = true; textLabel = new GUIStyle(EditorStyles.miniLabel); textLabel.wordWrap = true; } } [UnityEngine.Internal.ExcludeFromDocs] AdaptivePerformanceInstaller(string path, SettingsScope scopes = SettingsScope.Project) : base(path, scopes) { } [UnityEngine.Internal.ExcludeFromDocs] public override void OnGUI(string searchContext) { GUILayout.Space(15); if (m_AddManagementRequest != null) { if (m_AddManagementRequest.IsCompleted) { EditorGUILayout.LabelField(Content.s_DownloadingText); } else { EditorGUILayout.LabelField(Content.s_InstallingText); } } else { HelpBox(L10n.Tr(Content.s_InstallationHelpText), L10n.Tr("Read more"), () => { System.Diagnostics.Process.Start(Content.s_DocUri.AbsoluteUri); }); GUILayout.Space(15); if (GUILayout.Button(Content.s_AddAdaptivePerformance)) { m_AddManagementRequest = PackageManager.Client.Add(s_ManagementPackageId); } } } [SettingsProvider] static SettingsProvider CreateAdaptivePerformanceInstallerProvider() { try { var packagePath = Path.GetFullPath(s_ManagementPackagePath); if (String.IsNullOrEmpty(packagePath) || !File.Exists(packagePath) || String.Compare(s_ManagementPackagePath, packagePath, true) == 0) return new AdaptivePerformanceInstaller(Content.s_SettingsRootTitle); } catch (Exception) { // DO NOTHING... } return null; } private static void HelpBox(string message, string link, Action linkClicked) { GUILayout.BeginHorizontal(EditorStyles.helpBox); GUILayout.Label(EditorGUIUtility.GetHelpIcon(MessageType.Info), GUILayout.ExpandWidth(false)); GUILayout.BeginVertical(); GUILayout.Label(message, Styles.textLabel); if (GUILayout.Button(link, Styles.linkLabel)) linkClicked?.Invoke(); EditorGUIUtility.AddCursorRect(GUILayoutUtility.GetLastRect(), MouseCursor.Link); GUILayout.EndVertical(); GUILayout.EndHorizontal(); } } }
UnityCsReference/Modules/AdaptivePerformance/Editor/AdaptivePerformanceInstaller.cs/0
{ "file_path": "UnityCsReference/Modules/AdaptivePerformance/Editor/AdaptivePerformanceInstaller.cs", "repo_id": "UnityCsReference", "token_count": 2131 }
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; namespace UnityEngine { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("Use AnimatorClipInfo instead (UnityUpgradable) -> AnimatorClipInfo", true)] public struct AnimationInfo { public AnimationClip clip { get { return default(AnimationClip); } } public float weight { get { return 0.0f; } } } partial class Animator { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("GetCurrentAnimationClipState is obsolete. Use GetCurrentAnimatorClipInfo instead (UnityUpgradable) -> GetCurrentAnimatorClipInfo(*)", true)] public AnimationInfo[] GetCurrentAnimationClipState(int layerIndex) { return null; } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("GetNextAnimationClipState is obsolete. Use GetNextAnimatorClipInfo instead (UnityUpgradable) -> GetNextAnimatorClipInfo(*)", true)] public AnimationInfo[] GetNextAnimationClipState(int layerIndex) { return null; } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("Stop is obsolete. Use Animator.enabled = false instead", true)] public void Stop() {} } }
UnityCsReference/Modules/Animation/Managed/Animator.deprecated.cs/0
{ "file_path": "UnityCsReference/Modules/Animation/Managed/Animator.deprecated.cs", "repo_id": "UnityCsReference", "token_count": 491 }
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 UnityEngine.Playables; using UnityObject = UnityEngine.Object; namespace UnityEngine.Animations { [NativeHeader("Modules/Animation/ScriptBindings/AnimationMixerPlayable.bindings.h")] [NativeHeader("Modules/Animation/Director/AnimationMixerPlayable.h")] [NativeHeader("Runtime/Director/Core/HPlayable.h")] [StaticAccessor("AnimationMixerPlayableBindings", StaticAccessorType.DoubleColon)] [RequiredByNativeCode] public struct AnimationMixerPlayable : IPlayable, IEquatable<AnimationMixerPlayable> { PlayableHandle m_Handle; static readonly AnimationMixerPlayable m_NullPlayable = new AnimationMixerPlayable(PlayableHandle.Null); public static AnimationMixerPlayable Null { get { return m_NullPlayable; } } [Obsolete("normalizeWeights is obsolete. It has no effect and will be removed.")] public static AnimationMixerPlayable Create(PlayableGraph graph, int inputCount, bool normalizeWeights) { return Create(graph, inputCount); } public static AnimationMixerPlayable Create(PlayableGraph graph, int inputCount = 0) { var handle = CreateHandle(graph, inputCount); return new AnimationMixerPlayable(handle); } private static PlayableHandle CreateHandle(PlayableGraph graph, int inputCount = 0) { PlayableHandle handle = PlayableHandle.Null; if (!CreateHandleInternal(graph, ref handle)) return PlayableHandle.Null; handle.SetInputCount(inputCount); return handle; } internal AnimationMixerPlayable(PlayableHandle handle) { if (handle.IsValid()) { if (!handle.IsPlayableOfType<AnimationMixerPlayable>()) throw new InvalidCastException("Can't set handle: the playable is not an AnimationMixerPlayable."); } m_Handle = handle; } public PlayableHandle GetHandle() { return m_Handle; } public static implicit operator Playable(AnimationMixerPlayable playable) { return new Playable(playable.GetHandle()); } public static explicit operator AnimationMixerPlayable(Playable playable) { return new AnimationMixerPlayable(playable.GetHandle()); } public bool Equals(AnimationMixerPlayable other) { return GetHandle() == other.GetHandle(); } [NativeThrows] extern private static bool CreateHandleInternal(PlayableGraph graph, ref PlayableHandle handle); } }
UnityCsReference/Modules/Animation/ScriptBindings/AnimationMixerPlayable.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Animation/ScriptBindings/AnimationMixerPlayable.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1118 }
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 UnityEngine.Bindings; using UnityEngine.Scripting; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Collections; using System.Collections.Generic; namespace UnityEngine { [Obsolete("This class is not used anymore. See AnimatorOverrideController.GetOverrides() and AnimatorOverrideController.ApplyOverrides()")] [Serializable] [StructLayout(LayoutKind.Sequential)] public class AnimationClipPair { public AnimationClip originalClip; public AnimationClip overrideClip; } [NativeHeader("Modules/Animation/AnimatorOverrideController.h")] [NativeHeader("Modules/Animation/ScriptBindings/Animation.bindings.h")] [UsedByNativeCode] public class AnimatorOverrideController : RuntimeAnimatorController { public AnimatorOverrideController() { Internal_Create(this, null); OnOverrideControllerDirty = null; } public AnimatorOverrideController(RuntimeAnimatorController controller) { Internal_Create(this, controller); OnOverrideControllerDirty = null; } [FreeFunction("AnimationBindings::CreateAnimatorOverrideController")] extern private static void Internal_Create([Writable] AnimatorOverrideController self, RuntimeAnimatorController controller); // The runtime representation of AnimatorController that controls the Animator extern public RuntimeAnimatorController runtimeAnimatorController { [NativeMethod("GetAnimatorController")] get; [NativeMethod("SetAnimatorController")] set; } // Returns the animation clip named /name/. public AnimationClip this[string name] { get { return Internal_GetClipByName(name, true); } set { Internal_SetClipByName(name, value); } } [NativeMethod("GetClip")] extern private AnimationClip Internal_GetClipByName(string name, bool returnEffectiveClip); [NativeMethod("SetClip")] extern private void Internal_SetClipByName(string name, AnimationClip clip); // Returns the animation clip named /name/. public AnimationClip this[AnimationClip clip] { get { return GetClip(clip, true); } set { SetClip(clip, value, true); } } extern private AnimationClip GetClip(AnimationClip originalClip, bool returnEffectiveClip); extern private void SetClip(AnimationClip originalClip, AnimationClip overrideClip, bool notify); extern private void SendNotification(); extern private AnimationClip GetOriginalClip(int index); extern private AnimationClip GetOverrideClip(AnimationClip originalClip); extern public int overridesCount { [NativeMethod("GetOriginalClipsCount")] get; } public void GetOverrides(List<KeyValuePair<AnimationClip, AnimationClip>> overrides) { if (overrides == null) throw new System.ArgumentNullException("overrides"); int count = overridesCount; if (overrides.Capacity < count) overrides.Capacity = count; overrides.Clear(); for (int i = 0; i < count; ++i) { AnimationClip originalClip = GetOriginalClip(i); overrides.Add(new KeyValuePair<AnimationClip, AnimationClip>(originalClip, GetOverrideClip(originalClip))); } } public void ApplyOverrides(IList<KeyValuePair<AnimationClip, AnimationClip>> overrides) { if (overrides == null) throw new System.ArgumentNullException("overrides"); for (int i = 0; i < overrides.Count; i++) SetClip(overrides[i].Key, overrides[i].Value, false); SendNotification(); } [Obsolete("AnimatorOverrideController.clips property is deprecated. Use AnimatorOverrideController.GetOverrides and AnimatorOverrideController.ApplyOverrides instead.")] public AnimationClipPair[] clips { get { int count = overridesCount; AnimationClipPair[] clipPair = new AnimationClipPair[count]; for (int i = 0; i < count; i++) { clipPair[i] = new AnimationClipPair(); clipPair[i].originalClip = GetOriginalClip(i); clipPair[i].overrideClip = GetOverrideClip(clipPair[i].originalClip); } return clipPair; } set { for (int i = 0; i < value.Length; i++) SetClip(value[i].originalClip, value[i].overrideClip, false); SendNotification(); } } [NativeConditional("UNITY_EDITOR")] extern internal void PerformOverrideClipListCleanup(); internal delegate void OnOverrideControllerDirtyCallback(); internal OnOverrideControllerDirtyCallback OnOverrideControllerDirty; [NativeConditional("UNITY_EDITOR")] [RequiredByNativeCode] internal static void OnInvalidateOverrideController(AnimatorOverrideController controller) { if (controller.OnOverrideControllerDirty != null) controller.OnOverrideControllerDirty(); } } }
UnityCsReference/Modules/Animation/ScriptBindings/AnimatorOverrideController.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Animation/ScriptBindings/AnimatorOverrideController.bindings.cs", "repo_id": "UnityCsReference", "token_count": 2350 }
365
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine.Bindings; using UnityEngine; using UnityEngine.Scripting; using UnityEngineInternal; namespace UnityEngine { public enum AssetBundleLoadResult { Success, Cancelled, NotMatchingCrc, FailedCache, NotValidAssetBundle, NoSerializedData, NotCompatible, AlreadyLoaded, FailedRead, FailedDecompression, FailedWrite, FailedDeleteRecompressionTarget, RecompressionTargetIsLoaded, RecompressionTargetExistsButNotArchive } [NativeHeader("Modules/AssetBundle/Public/AssetBundleLoadFromFileAsyncOperation.h")] [NativeHeader("Modules/AssetBundle/Public/AssetBundleLoadFromMemoryAsyncOperation.h")] [NativeHeader("Modules/AssetBundle/Public/AssetBundleLoadFromManagedStreamAsyncOperation.h")] [NativeHeader("Modules/AssetBundle/Public/AssetBundleLoadAssetOperation.h")] [NativeHeader("Runtime/Scripting/ScriptingExportUtility.h")] [NativeHeader("Runtime/Scripting/ScriptingUtility.h")] [NativeHeader("AssetBundleScriptingClasses.h")] [NativeHeader("Modules/AssetBundle/Public/AssetBundleSaveAndLoadHelper.h")] [NativeHeader("Modules/AssetBundle/Public/AssetBundleUtility.h")] [NativeHeader("Modules/AssetBundle/Public/AssetBundleLoadAssetUtility.h")] [ExcludeFromPreset] public partial class AssetBundle : Object { private AssetBundle() {} [Obsolete("mainAsset has been made obsolete. Please use the new AssetBundle build system introduced in 5.0 and check BuildAssetBundles documentation for details.")] public Object mainAsset { get { return returnMainAsset(this); } } [FreeFunction("LoadMainObjectFromAssetBundle", true)] internal static extern Object returnMainAsset([NotNull] AssetBundle bundle); [FreeFunction("UnloadAllAssetBundles")] public extern static void UnloadAllAssetBundles(bool unloadAllObjects); [FreeFunction("GetAllAssetBundles")] internal extern static AssetBundle[] GetAllLoadedAssetBundles_Native(); public static IEnumerable<AssetBundle> GetAllLoadedAssetBundles() { return GetAllLoadedAssetBundles_Native(); } [FreeFunction("LoadFromFileAsync")] internal extern static AssetBundleCreateRequest LoadFromFileAsync_Internal(string path, uint crc, ulong offset); public static AssetBundleCreateRequest LoadFromFileAsync(string path) { return LoadFromFileAsync_Internal(path, 0, 0); } public static AssetBundleCreateRequest LoadFromFileAsync(string path, uint crc) { return LoadFromFileAsync_Internal(path, crc, 0); } public static AssetBundleCreateRequest LoadFromFileAsync(string path, uint crc, ulong offset) { return LoadFromFileAsync_Internal(path, crc, offset); } [FreeFunction("LoadFromFile")] internal extern static AssetBundle LoadFromFile_Internal(string path, uint crc, ulong offset); public static AssetBundle LoadFromFile(string path) { return LoadFromFile_Internal(path, 0, 0); } public static AssetBundle LoadFromFile(string path, uint crc) { return LoadFromFile_Internal(path, crc, 0); } public static AssetBundle LoadFromFile(string path, uint crc, ulong offset) { return LoadFromFile_Internal(path, crc, offset); } [FreeFunction("LoadFromMemoryAsync")] internal extern static AssetBundleCreateRequest LoadFromMemoryAsync_Internal(byte[] binary, uint crc); public static AssetBundleCreateRequest LoadFromMemoryAsync(byte[] binary) { return LoadFromMemoryAsync_Internal(binary, 0); } public static AssetBundleCreateRequest LoadFromMemoryAsync(byte[] binary, uint crc) { return LoadFromMemoryAsync_Internal(binary, crc); } [FreeFunction("LoadFromMemory")] internal extern static AssetBundle LoadFromMemory_Internal(byte[] binary, uint crc); public static AssetBundle LoadFromMemory(byte[] binary) { return LoadFromMemory_Internal(binary, 0); } public static AssetBundle LoadFromMemory(byte[] binary, uint crc) { return LoadFromMemory_Internal(binary, crc); } internal static void ValidateLoadFromStream(System.IO.Stream stream) { if (stream == null) throw new System.ArgumentNullException("ManagedStream object must be non-null", "stream"); if (!stream.CanRead) throw new System.ArgumentException("ManagedStream object must be readable (stream.CanRead must return true)", "stream"); if (!stream.CanSeek) throw new System.ArgumentException("ManagedStream object must be seekable (stream.CanSeek must return true)", "stream"); } public static AssetBundleCreateRequest LoadFromStreamAsync(System.IO.Stream stream, uint crc, uint managedReadBufferSize) { ValidateLoadFromStream(stream); return LoadFromStreamAsyncInternal(stream, crc, managedReadBufferSize); } public static AssetBundleCreateRequest LoadFromStreamAsync(System.IO.Stream stream, uint crc) { ValidateLoadFromStream(stream); return LoadFromStreamAsyncInternal(stream, crc, 0); } public static AssetBundleCreateRequest LoadFromStreamAsync(System.IO.Stream stream) { ValidateLoadFromStream(stream); return LoadFromStreamAsyncInternal(stream, 0, 0); } public static AssetBundle LoadFromStream(System.IO.Stream stream, uint crc, uint managedReadBufferSize) { ValidateLoadFromStream(stream); return LoadFromStreamInternal(stream, crc, managedReadBufferSize); } public static AssetBundle LoadFromStream(System.IO.Stream stream, uint crc) { ValidateLoadFromStream(stream); return LoadFromStreamInternal(stream, crc, 0); } public static AssetBundle LoadFromStream(System.IO.Stream stream) { ValidateLoadFromStream(stream); return LoadFromStreamInternal(stream, 0, 0); } [FreeFunction("LoadFromStreamAsyncInternal")] internal extern static AssetBundleCreateRequest LoadFromStreamAsyncInternal(System.IO.Stream stream, uint crc, uint managedReadBufferSize); [FreeFunction("LoadFromStreamInternal")] internal extern static AssetBundle LoadFromStreamInternal(System.IO.Stream stream, uint crc, uint managedReadBufferSize); public extern bool isStreamedSceneAssetBundle { [NativeMethod("GetIsStreamedSceneAssetBundle")] get; } [NativeMethod("Contains")] public extern bool Contains(string name); [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("Method Load has been deprecated. Script updater cannot update it as the loading behaviour has changed. Please use LoadAsset instead and check the documentation for details.", true)] public Object Load(string name) { return null; } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("Method Load has been deprecated. Script updater cannot update it as the loading behaviour has changed. Please use LoadAsset instead and check the documentation for details.", true)] public Object Load<T>(string name) { return null; } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("Method Load has been deprecated. Script updater cannot update it as the loading behaviour has changed. Please use LoadAsset instead and check the documentation for details.", true)] Object Load(string name, Type type) { return null; } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("Method LoadAsync has been deprecated. Script updater cannot update it as the loading behaviour has changed. Please use LoadAssetAsync instead and check the documentation for details.", true)] AssetBundleRequest LoadAsync(string name, Type type) { return null; } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("Method LoadAll has been deprecated. Script updater cannot update it as the loading behaviour has changed. Please use LoadAllAssets instead and check the documentation for details.", true)] Object[] LoadAll(Type type) { return null; } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("Method LoadAll has been deprecated. Script updater cannot update it as the loading behaviour has changed. Please use LoadAllAssets instead and check the documentation for details.", true)] public UnityEngine.Object[] LoadAll() { return null; } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("Method LoadAll has been deprecated. Script updater cannot update it as the loading behaviour has changed. Please use LoadAllAssets instead and check the documentation for details.", true)] public T[] LoadAll<T>() where T : Object { return null; } public Object LoadAsset(string name) { return LoadAsset(name, typeof(Object)); } public T LoadAsset<T>(string name) where T : Object { return (T)LoadAsset(name, typeof(T)); } [TypeInferenceRule(TypeInferenceRules.TypeReferencedBySecondArgument)] public Object LoadAsset(string name, Type type) { if (name == null) { throw new System.NullReferenceException("The input asset name cannot be null."); } if (name.Length == 0) { throw new System.ArgumentException("The input asset name cannot be empty."); } if (type == null) { throw new System.NullReferenceException("The input type cannot be null."); } return LoadAsset_Internal(name, type); } [NativeThrows] [NativeMethod("LoadAsset_Internal")] [TypeInferenceRule(TypeInferenceRules.TypeReferencedBySecondArgument)] private extern Object LoadAsset_Internal(string name, Type type); public AssetBundleRequest LoadAssetAsync(string name) { return LoadAssetAsync(name, typeof(UnityEngine.Object)); } public AssetBundleRequest LoadAssetAsync<T>(string name) { return LoadAssetAsync(name, typeof(T)); } public AssetBundleRequest LoadAssetAsync(string name, Type type) { if (name == null) { throw new System.NullReferenceException("The input asset name cannot be null."); } if (name.Length == 0) { throw new System.ArgumentException("The input asset name cannot be empty."); } if (type == null) { throw new System.NullReferenceException("The input type cannot be null."); } return LoadAssetAsync_Internal(name, type); } public Object[] LoadAssetWithSubAssets(string name) { return LoadAssetWithSubAssets(name, typeof(Object)); } internal static T[] ConvertObjects<T>(Object[] rawObjects) where T : Object { if (rawObjects == null) return null; T[] typedObjects = new T[rawObjects.Length]; for (int i = 0; i < typedObjects.Length; i++) typedObjects[i] = (T)rawObjects[i]; return typedObjects; } public T[] LoadAssetWithSubAssets<T>(string name) where T : Object { return ConvertObjects<T>(LoadAssetWithSubAssets(name, typeof(T))); } public Object[] LoadAssetWithSubAssets(string name, Type type) { if (name == null) { throw new System.NullReferenceException("The input asset name cannot be null."); } if (name.Length == 0) { throw new System.ArgumentException("The input asset name cannot be empty."); } if (type == null) { throw new System.NullReferenceException("The input type cannot be null."); } return LoadAssetWithSubAssets_Internal(name, type); } public AssetBundleRequest LoadAssetWithSubAssetsAsync(string name) { return LoadAssetWithSubAssetsAsync(name, typeof(UnityEngine.Object)); } public AssetBundleRequest LoadAssetWithSubAssetsAsync<T>(string name) { return LoadAssetWithSubAssetsAsync(name, typeof(T)); } public AssetBundleRequest LoadAssetWithSubAssetsAsync(string name, Type type) { if (name == null) { throw new System.NullReferenceException("The input asset name cannot be null."); } if (name.Length == 0) { throw new System.ArgumentException("The input asset name cannot be empty."); } if (type == null) { throw new System.NullReferenceException("The input type cannot be null."); } return LoadAssetWithSubAssetsAsync_Internal(name, type); } public UnityEngine.Object[] LoadAllAssets() { return LoadAllAssets(typeof(UnityEngine.Object)); } public T[] LoadAllAssets<T>() where T : Object { return ConvertObjects<T>(LoadAllAssets(typeof(T))); } public UnityEngine.Object[] LoadAllAssets(Type type) { if (type == null) { throw new System.NullReferenceException("The input type cannot be null."); } return LoadAssetWithSubAssets_Internal("", type); } public AssetBundleRequest LoadAllAssetsAsync() { return LoadAllAssetsAsync(typeof(UnityEngine.Object)); } public AssetBundleRequest LoadAllAssetsAsync<T>() { return LoadAllAssetsAsync(typeof(T)); } public AssetBundleRequest LoadAllAssetsAsync(Type type) { if (type == null) { throw new System.NullReferenceException("The input type cannot be null."); } return LoadAssetWithSubAssetsAsync_Internal("", type); } [Obsolete("This method is deprecated.Use GetAllAssetNames() instead.", false)] public string[] AllAssetNames() { return GetAllAssetNames(); } [NativeThrows] [NativeMethod("LoadAssetAsync_Internal")] private extern AssetBundleRequest LoadAssetAsync_Internal(string name, Type type); [NativeThrows] [NativeMethod("Unload")] public extern void Unload(bool unloadAllLoadedObjects); [NativeThrows] [NativeMethod("UnloadAsync")] public extern AssetBundleUnloadOperation UnloadAsync(bool unloadAllLoadedObjects); [NativeMethod("GetAllAssetNames")] public extern string[] GetAllAssetNames(); [NativeMethod("GetAllScenePaths")] public extern string[] GetAllScenePaths(); [NativeThrows] [NativeMethod("LoadAssetWithSubAssets_Internal")] internal extern Object[] LoadAssetWithSubAssets_Internal(string name, Type type); [NativeThrows] [NativeMethod("LoadAssetWithSubAssetsAsync_Internal")] private extern AssetBundleRequest LoadAssetWithSubAssetsAsync_Internal(string name, Type type); public static AssetBundleRecompressOperation RecompressAssetBundleAsync(string inputPath, string outputPath, BuildCompression method, UInt32 expectedCRC = 0, ThreadPriority priority = ThreadPriority.Low) { return RecompressAssetBundleAsync_Internal(inputPath, outputPath, method, expectedCRC, priority); } [NativeThrows] [FreeFunction("RecompressAssetBundleAsync_Internal")] internal static extern AssetBundleRecompressOperation RecompressAssetBundleAsync_Internal(string inputPath, string outputPath, BuildCompression method, UInt32 expectedCRC, ThreadPriority priority); public static uint memoryBudgetKB { get { return AssetBundleLoadingCache.memoryBudgetKB; } set { AssetBundleLoadingCache.memoryBudgetKB = value; } } } }
UnityCsReference/Modules/AssetBundle/Managed/AssetBundle.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/AssetBundle/Managed/AssetBundle.bindings.cs", "repo_id": "UnityCsReference", "token_count": 6860 }
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 System.Collections.Generic; using System.Globalization; using System.Linq; using UnityEngine; namespace UnityEditor { internal partial class ArtifactDifferenceReporter { internal static void Test_GraphicsAPIMaskModified(ref ArtifactInfoDifference diff, List<string> msgsList) { //Only way to test internals GraphicsAPIMaskModified(ref diff, msgsList); } internal static void Test_GlobalArtifactFormatVersionModified(ref ArtifactInfoDifference diff, List<string> msgsList) { //Only way to test internals GlobalArtifactFormatVersionModified(ref diff, msgsList); } internal static void Test_GlobalAllImporterVersionModified(ref ArtifactInfoDifference diff, List<string> msgsList) { //Only way to test internals GlobalAllImporterVersionModified(ref diff, msgsList); } internal static void Test_ImporterVersionModified(ref ArtifactInfoDifference diff, List<string> msgsList) { //Only way to test internals ImporterVersionModified(ref diff, msgsList); } internal static void Test_ArtifactFileIdOfMainObjectModified(ref ArtifactInfoDifference diff, List<string> msgsList) { //Only way to test internals ArtifactFileIdOfMainObjectModified(ref diff, msgsList); } internal static void Test_ScriptingRuntimeVersionModified(ref ArtifactInfoDifference diff, List<string> msgsList) { //Only way to test internals ScriptingRuntimeVersionModified(ref diff, msgsList); } internal static void Test_PlatformGroupModified(ref ArtifactInfoDifference diff, List<string> msgsList) { PlatformGroupModified(ref diff, msgsList); } internal static void Test_PlatformDependencyModified(ref ArtifactInfoDifference diff, List<string> msgsList) { PlatformDependencyModified(ref diff, msgsList); } internal static void Test_PostProcessorVersionHashModified(ref ArtifactInfoDifference diff, List<string> msgsList) { PostProcessorVersionHashModified(ref diff, msgsList); } internal static void Test_TextureCompressionModified(ref ArtifactInfoDifference diff, List<string> msgsList) { TextureCompressionModified(ref diff, msgsList); } internal static void Test_GuidOfPathLocationModifiedViaHashOfSourceAsset(ref ArtifactInfoDifference diff, List<string> msgsList, string pathOfDependency) { GuidOfPathLocationModifiedViaHashOfSourceAsset(ref diff, msgsList, pathOfDependency); } } }
UnityCsReference/Modules/AssetDatabase/Editor/V2/Managed/ArtifactDifferenceReporterTesting.cs/0
{ "file_path": "UnityCsReference/Modules/AssetDatabase/Editor/V2/Managed/ArtifactDifferenceReporterTesting.cs", "repo_id": "UnityCsReference", "token_count": 1119 }
367
// Unity 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 UnityEditor.AssetImporters; using UnityEngine; using Object = UnityEngine.Object; namespace UnityEditor { internal class ModelImporterMaterialEditor : BaseAssetImporterTabUI { bool m_ShowAllMaterialNameOptions = true; bool m_ShowMaterialRemapOptions = false; // Material SerializedProperty m_MaterialName; SerializedProperty m_MaterialSearch; SerializedProperty m_MaterialLocation; SerializedProperty m_Materials; SerializedProperty m_ExternalObjects; SerializedProperty m_HasEmbeddedTextures; SerializedProperty m_SupportsEmbeddedMaterials; SerializedProperty m_UseSRGBMaterialColor; SerializedProperty m_MaterialImportMode; private bool m_CanExtractEmbeddedMaterials = false; class ExternalObjectCache { public int propertyIdx = 0; public SerializedProperty property; } class MaterialCache { public string name; public string type; public string assembly; } List<MaterialCache> m_MaterialsCache = new List<MaterialCache>(); Dictionary<Tuple<string, string>, ExternalObjectCache> m_ExternalObjectsCache = new Dictionary<Tuple<string, string>, ExternalObjectCache>(); Object m_CacheCurrentTarget = null; static class Styles { public static GUIContent MaterialLocation = EditorGUIUtility.TrTextContent("Location"); public static GUIContent MaterialName = EditorGUIUtility.TrTextContent("Naming"); public static GUIContent[] MaterialNameOptMain = { EditorGUIUtility.TrTextContent("By Base Texture Name"), EditorGUIUtility.TrTextContent("From Model's Material"), EditorGUIUtility.TrTextContent("Model Name + Model's Material"), }; public static GUIContent[] MaterialNameOptAll = { EditorGUIUtility.TrTextContent("By Base Texture Name"), EditorGUIUtility.TrTextContent("From Model's Material"), EditorGUIUtility.TrTextContent("Model Name + Model's Material"), EditorGUIUtility.TrTextContent("Texture Name or Model Name + Model's Material (Obsolete)"), }; public static GUIContent MaterialSearch = EditorGUIUtility.TrTextContent("Search"); public static GUIContent[] MaterialSearchOpt = { EditorGUIUtility.TrTextContent("Local Materials Folder"), EditorGUIUtility.TrTextContent("Recursive-Up"), EditorGUIUtility.TrTextContent("Project-Wide") }; public static GUIContent NoMaterialHelp = EditorGUIUtility.TrTextContent("Do not generate materials. Use Unity's default material instead."); public static GUIContent ExternalMaterialHelpStart = EditorGUIUtility.TrTextContent("For each imported material, Unity first looks for an existing material named %MAT%."); public static GUIContent[] ExternalMaterialNameHelp = { EditorGUIUtility.TrTextContent("[BaseTextureName]"), EditorGUIUtility.TrTextContent("[MaterialName]"), EditorGUIUtility.TrTextContent("[ModelFileName]-[MaterialName]"), EditorGUIUtility.TrTextContent("[BaseTextureName] or [ModelFileName]-[MaterialName] if no base texture can be found"), }; public static GUIContent[] ExternalMaterialSearchHelp = { EditorGUIUtility.TrTextContent("Unity will look for it in the local Materials folder."), EditorGUIUtility.TrTextContent("Unity will do a recursive-up search for it in all Materials folders up to the Assets folder."), EditorGUIUtility.TrTextContent("Unity will search for it anywhere inside the Assets folder.") }; public static GUIContent ExternalMaterialHelpEnd = EditorGUIUtility.TrTextContent("If it doesn't exist, a new one is created in the local Materials folder."); public static GUIContent InternalMaterialHelp = EditorGUIUtility.TrTextContent("Materials are embedded inside the imported asset."); public static GUIContent MaterialAssignmentsHelp = EditorGUIUtility.TrTextContent("Material assignments can be remapped below."); public static GUIContent ExternalMaterialMappings = EditorGUIUtility.TrTextContent("Remapped Materials", "External materials to use for each embedded material."); public static GUIContent NoMaterialMappingsHelp = EditorGUIUtility.TrTextContent("Re-import the asset to see the list of used materials."); public static GUIContent Textures = EditorGUIUtility.TrTextContent("Textures"); public static GUIContent ExtractEmbeddedTextures = EditorGUIUtility.TrTextContent("Extract Textures...", "Click on this button to extract the embedded textures."); public static GUIContent Materials = EditorGUIUtility.TrTextContent("Materials"); public static GUIContent ExtractEmbeddedMaterials = EditorGUIUtility.TrTextContent("Extract Materials...", "Click on this button to extract the embedded materials."); public static GUIContent RemapOptions = EditorGUIUtility.TrTextContent("On Demand Remap"); public static GUIContent RemapMaterialsInProject = EditorGUIUtility.TrTextContent("Search and Remap", "Click on this button to search and remap the materials from the project."); public static GUIContent SRGBMaterialColor = EditorGUIUtility.TrTextContent("sRGB Albedo Colors", "Albedo colors in gamma space. Disable this for projects using linear color space."); public static GUIContent MaterialCreationMode = EditorGUIUtility.TrTextContent("Material Creation Mode", "Select the method used to generate materials during the import process."); } public ModelImporterMaterialEditor(AssetImporterEditor panelContainer) : base(panelContainer) {} private void UpdateShowAllMaterialNameOptions() { // We need to display BasedOnTextureName_Or_ModelNameAndMaterialName obsolete option for objects which use this option #pragma warning disable 618 m_ShowAllMaterialNameOptions = (m_MaterialName.intValue == (int)ModelImporterMaterialName.BasedOnTextureName_Or_ModelNameAndMaterialName); #pragma warning restore 618 } internal override void OnEnable() { // Material m_MaterialName = serializedObject.FindProperty("m_MaterialName"); m_MaterialSearch = serializedObject.FindProperty("m_MaterialSearch"); m_MaterialLocation = serializedObject.FindProperty("m_MaterialLocation"); m_Materials = serializedObject.FindProperty("m_Materials"); m_ExternalObjects = serializedObject.FindProperty("m_ExternalObjects"); m_HasEmbeddedTextures = serializedObject.FindProperty("m_HasEmbeddedTextures"); m_SupportsEmbeddedMaterials = serializedObject.FindProperty("m_SupportsEmbeddedMaterials"); m_UseSRGBMaterialColor = serializedObject.FindProperty("m_UseSRGBMaterialColor"); m_MaterialImportMode = serializedObject.FindProperty("m_MaterialImportMode"); if (m_CacheCurrentTarget != target) { m_CacheCurrentTarget = target; BuildMaterialsCache(); BuildExternalObjectsCache(); EvaluateMaterialExtractionState(); } Undo.undoRedoEvent += OnUndoRedo; } internal override void OnDisable() { Undo.undoRedoEvent -= OnUndoRedo; base.OnDisable(); } private void OnUndoRedo(in UndoRedoInfo info) { ResetValues(); } private void BuildMaterialsCache() { // do not set if multiple selection. if (m_Materials.hasMultipleDifferentValues) return; m_MaterialsCache.Clear(); for (int materialIdx = 0; materialIdx < m_Materials.arraySize; ++materialIdx) { var mat = new MaterialCache(); var id = m_Materials.GetArrayElementAtIndex(materialIdx); mat.name = id.FindPropertyRelative("name").stringValue; mat.type = id.FindPropertyRelative("type").stringValue; mat.assembly = id.FindPropertyRelative("assembly").stringValue; m_MaterialsCache.Add(mat); } } private void BuildExternalObjectsCache() { // do not set if multiple selection. if (m_ExternalObjects.hasMultipleDifferentValues) return; m_ExternalObjectsCache.Clear(); for (int externalObjectIdx = 0, count = m_ExternalObjects.arraySize; externalObjectIdx < count; ++externalObjectIdx) { var pair = m_ExternalObjects.GetArrayElementAtIndex(externalObjectIdx); var cachedObject = new ExternalObjectCache(); cachedObject.property = pair.FindPropertyRelative("second"); cachedObject.propertyIdx = externalObjectIdx; var externalName = pair.FindPropertyRelative("first.name").stringValue; var externalType = pair.FindPropertyRelative("first.type").stringValue; m_ExternalObjectsCache.Add(new Tuple<string, string>(externalName, externalType), cachedObject); } } private void EvaluateMaterialExtractionState() { if (m_Materials.arraySize == 0) m_CanExtractEmbeddedMaterials = false; //Are there any materials that haven't been extracted? foreach (var t in m_ExternalObjects.serializedObject.targetObjects) { var importer = t as ModelImporter; var externalObjectMap = importer.GetExternalObjectMap(); var materialsList = importer.sourceMaterials; int mappedMaterialCount = externalObjectMap.Count(x => x.Key.type == typeof(Material) && x.Value != null && Array.Exists(materialsList, y => y.name == x.Key.name)); if (mappedMaterialCount != materialsList.Length) { m_CanExtractEmbeddedMaterials = true; return; } } m_CanExtractEmbeddedMaterials = false; } public override void OnInspectorGUI() { DoMaterialsGUI(); } private void ExtractTexturesGUI() { using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.PrefixLabel(Styles.Textures); using ( new EditorGUI.DisabledScope(!m_HasEmbeddedTextures.boolValue && !m_HasEmbeddedTextures.hasMultipleDifferentValues)) { if (GUILayout.Button(Styles.ExtractEmbeddedTextures)) { // when extracting textures, we must handle the case when multiple selected assets could generate textures with the same name at the user supplied path // we proceed as follows: // 1. each asset extracts the textures in a separate temp folder // 2. we remap the extracted assets to the respective asset importer // 3. we generate unique names for each asset and move them to the user supplied path // 4. we re-import all the assets to have the internal materials linked to the newly extracted textures List<Tuple<Object, string>> outputsForTargets = new List<Tuple<Object, string>>(); // use the first target for selecting the destination folder, but apply that path for all targets string assetPath = (target as ModelImporter).assetPath; assetPath = EditorUtility.SaveFolderPanel("Select Textures Folder", FileUtil.DeleteLastPathNameComponent(assetPath), ""); if (string.IsNullOrEmpty(assetPath)) { // cancel the extraction if the user did not select a folder return; } var destinationPath = FileUtil.GetProjectRelativePath(assetPath); if (!destinationPath.StartsWith("Assets")) { assetPath = FileUtil.NiceWinPath(assetPath); // Destination could be a package. Need to get assetPath instead of relativePath // The GUID isn't known yet so can't find it from that var packageInfo = PackageManager.PackageInfo.FindForAssetPath(assetPath); if (packageInfo != null) destinationPath = packageInfo.assetPath + assetPath.Substring(packageInfo.resolvedPath.Length); } try { // batch the extraction of the textures AssetDatabase.StartAssetEditing(); foreach (var t in targets) { var tempPath = FileUtil.GetUniqueTempPathInProject(); tempPath = tempPath.Replace("Temp", UnityEditorInternal.InternalEditorUtility.GetAssetsFolder()); outputsForTargets.Add(Tuple.Create(t, tempPath)); var importer = t as ModelImporter; importer.ExtractTextures(tempPath); } } finally { AssetDatabase.StopAssetEditing(); } try { // batch the remapping and the reimport of the assets AssetDatabase.Refresh(); AssetDatabase.StartAssetEditing(); foreach (var item in outputsForTargets) { var importer = item.Item1 as ModelImporter; var guids = AssetDatabase.FindAssets("t:Texture", new string[] {item.Item2}); foreach (var guid in guids) { var path = AssetDatabase.GUIDToAssetPath(guid); var tex = AssetDatabase.LoadAssetAtPath<Texture>(path); if (tex == null) continue; importer.AddRemap(new AssetImporter.SourceAssetIdentifier(tex), tex); var newPath = Path.Combine(destinationPath, FileUtil.UnityGetFileName(path)); newPath = AssetDatabase.GenerateUniqueAssetPath(newPath); AssetDatabase.MoveAsset(path, newPath); } AssetDatabase.ImportAsset(importer.assetPath, ImportAssetOptions.ForceUpdate); AssetDatabase.DeleteAsset(item.Item2); } } finally { AssetDatabase.StopAssetEditing(); } } } } } private bool ExtractMaterialsGUI() { using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.PrefixLabel(Styles.Materials); using (new EditorGUI.DisabledScope(!m_CanExtractEmbeddedMaterials)) { if (GUILayout.Button(Styles.ExtractEmbeddedMaterials)) { // use the first target for selecting the destination folder, but apply that path for all targets string destinationPath = (target as ModelImporter).assetPath; destinationPath = EditorUtility.SaveFolderPanel("Select Materials Folder", FileUtil.DeleteLastPathNameComponent(destinationPath), ""); if (string.IsNullOrEmpty(destinationPath)) { // cancel the extraction if the user did not select a folder return false; } string assetPath = FileUtil.GetProjectRelativePath(destinationPath); //Where all the required embedded materials are not in the asset database, we need to reimport them if (!AllEmbeddedMaterialsAreImported()) { if (EditorUtility.DisplayDialog(L10n.Tr("Are you sure you want to re-extract the Materials?"), L10n.Tr("In order to re-extract the Materials we'll need to reimport the mesh, this might take a while. Do you want to continue?"), L10n.Tr("Yes"), L10n.Tr("No"))) ReimportEmbeddedMaterials(); else return false; } if (!assetPath.StartsWith("Assets")) { destinationPath = FileUtil.NiceWinPath(destinationPath); // Destination could be a package. Need to get assetPath instead of relativePath // The GUID isn't known yet so can't find it from that var packageInfo = PackageManager.PackageInfo.FindForAssetPath(destinationPath); if (packageInfo != null) destinationPath = packageInfo.assetPath + destinationPath.Substring(packageInfo.resolvedPath.Length); } if (string.IsNullOrEmpty(assetPath)) return false; try { // batch the extraction of the textures AssetDatabase.StartAssetEditing(); PrefabUtility.ExtractMaterialsFromAsset(targets, assetPath); } finally { AssetDatabase.StopAssetEditing(); } // AssetDatabase.StopAssetEditing() invokes OnEnable(), which invalidates all the serialized properties, so we must return. return true; } } } return false; } public bool AllEmbeddedMaterialsAreImported() { foreach (ModelImporter modelImporter in m_ExternalObjects.serializedObject.targetObjects) { //Find the names of embedded materials - the source materials that are not re-mapped in the externalObjectsCache IEnumerable<string> namesOfEmbeddedMaterials = modelImporter.sourceMaterials .Where(x => !m_ExternalObjectsCache.Any(y => y.Key.Item1 == x.name && y.Value.property != null && y.Value.property.objectReferenceValue != null)) .Select(x => x.name); //Find the names of embedded materials in the AssetDatabase IEnumerable<string> namesOfMaterialsInAssetDatabase = AssetDatabase.LoadAllAssetsAtPath(modelImporter.assetPath) .Where(x => x.GetType() == typeof(Material)) .Select(x => x.name); //Are there any embedded materials that *arent* in the AssetDatabase? if (namesOfEmbeddedMaterials.Except(namesOfMaterialsInAssetDatabase).Any()) return false; } return true; } public void ReimportEmbeddedMaterials() { //Select any material properties which are marked as "missing" int[] missingMaterialIndexes = m_ExternalObjectsCache.Values.Select((extObj, index) => new { extObj, index }) .Where(x => x.extObj.property != null && x.extObj.property.objectReferenceValue == null && x.extObj.property.objectReferenceInstanceIDValue != 0) .Select(x => x.index) .ToArray(); //Remove missing materials for (int i = missingMaterialIndexes.Length - 1; i >= 0; i--) m_ExternalObjects.DeleteArrayElementAtIndex(missingMaterialIndexes[i]); serializedObject.ApplyModifiedProperties(); //Force a reimport - any materials marked "None" (including former missing Materials), will now be assigned an embedded material AssetImporter assetImporter = (AssetImporter)target; AssetDatabase.ImportAsset(assetImporter.assetPath, ImportAssetOptions.ForceUpdate); } private bool MaterialRemapOptions() { m_ShowMaterialRemapOptions = EditorGUILayout.Foldout(m_ShowMaterialRemapOptions, Styles.RemapOptions, true); if (m_ShowMaterialRemapOptions) { EditorGUI.indentLevel++; EditorGUILayout.Popup(m_MaterialName, m_ShowAllMaterialNameOptions ? Styles.MaterialNameOptAll : Styles.MaterialNameOptMain, Styles.MaterialName); EditorGUILayout.Popup(m_MaterialSearch, Styles.MaterialSearchOpt, Styles.MaterialSearch); string searchHelp = Styles.ExternalMaterialHelpStart.text.Replace("%MAT%", Styles.ExternalMaterialNameHelp[m_MaterialName.intValue].text) + "\n" + Styles.ExternalMaterialSearchHelp[m_MaterialSearch.intValue].text; EditorGUILayout.HelpBox(searchHelp, MessageType.Info); EditorGUI.indentLevel--; using (new EditorGUILayout.HorizontalScope()) { GUILayout.FlexibleSpace(); using (new EditorGUI.DisabledScope(assetTarget == null)) { if (GUILayout.Button(Styles.RemapMaterialsInProject)) { Undo.RecordObjects(targets, "Search and Remap Materials"); foreach (var t in targets) { var importer = t as ModelImporter; // SearchAndReplaceMaterials will ensure the material name and search options get saved, while all other pending changes stay pending. importer.SearchAndRemapMaterials((ModelImporterMaterialName)m_MaterialName.intValue, (ModelImporterMaterialSearch)m_MaterialSearch.intValue); } ResetValues(); EditorGUIUtility.ExitGUI(); return true; } } } EditorGUILayout.Space(); } return false; } void DoMaterialsGUI() { if (targets.Length > 1) { EditorGUILayout.HelpBox(L10n.Tr("Material Editing is not supported on multiple selection"), MessageType.Info); return; } serializedObject.UpdateIfRequiredOrScript(); UpdateShowAllMaterialNameOptions(); using (var horizontal = new EditorGUILayout.HorizontalScope()) { using (var prop = new EditorGUI.PropertyScope(horizontal.rect, Styles.MaterialCreationMode, m_MaterialImportMode)) { EditorGUI.BeginChangeCheck(); var newValue = (int)(ModelImporterMaterialImportMode)EditorGUILayout.EnumPopup(prop.content, (ModelImporterMaterialImportMode)m_MaterialImportMode.intValue); if (EditorGUI.EndChangeCheck()) { m_MaterialImportMode.intValue = newValue; } } } string materialHelp = string.Empty; if (!m_MaterialImportMode.hasMultipleDifferentValues) { if (m_MaterialImportMode.intValue != (int)ModelImporterMaterialImportMode.None) { if (m_MaterialImportMode.intValue == (int)ModelImporterMaterialImportMode.ImportStandard) { EditorGUILayout.PropertyField(m_UseSRGBMaterialColor, Styles.SRGBMaterialColor); } using (var horizontal = new EditorGUILayout.HorizontalScope()) { using (var prop = new EditorGUI.PropertyScope(horizontal.rect, Styles.MaterialLocation, m_MaterialLocation)) { EditorGUI.BeginChangeCheck(); var newValue = (int)(ModelImporterMaterialLocation)EditorGUILayout.EnumPopup(prop.content, (ModelImporterMaterialLocation)m_MaterialLocation.intValue); if (EditorGUI.EndChangeCheck()) { m_MaterialLocation.intValue = newValue; } } } if (!m_MaterialLocation.hasMultipleDifferentValues) { if (m_MaterialLocation.intValue == 0) { // (legacy) we're generating materials in the Materials folder EditorGUILayout.Popup(m_MaterialName, m_ShowAllMaterialNameOptions ? Styles.MaterialNameOptAll : Styles.MaterialNameOptMain, Styles.MaterialName); EditorGUILayout.Popup(m_MaterialSearch, Styles.MaterialSearchOpt, Styles.MaterialSearch); materialHelp = Styles.ExternalMaterialHelpStart.text.Replace("%MAT%", Styles.ExternalMaterialNameHelp[m_MaterialName.intValue].text) + "\n" + Styles.ExternalMaterialSearchHelp[m_MaterialSearch.intValue].text + "\n" + Styles.ExternalMaterialHelpEnd.text; } else if (m_Materials.arraySize > 0 && m_CanExtractEmbeddedMaterials) { // we're generating materials inside the prefab materialHelp = Styles.InternalMaterialHelp.text; } } if (targets.Length == 1 && m_Materials.arraySize > 0 && m_MaterialLocation.intValue != 0) { materialHelp += " " + Styles.MaterialAssignmentsHelp.text; } // display the extract buttons if (m_MaterialLocation.intValue != 0 && !m_MaterialLocation.hasMultipleDifferentValues) { ExtractTexturesGUI(); if (ExtractMaterialsGUI()) return; } } else { // we're not importing materials materialHelp = Styles.NoMaterialHelp.text; } } if (!string.IsNullOrEmpty(materialHelp)) { EditorGUILayout.HelpBox(materialHelp, MessageType.Info); } if ((targets.Length == 1 || m_SupportsEmbeddedMaterials.hasMultipleDifferentValues == false) && m_SupportsEmbeddedMaterials.boolValue == false && m_MaterialLocation.intValue != 0 && !m_MaterialLocation.hasMultipleDifferentValues) { EditorGUILayout.Space(); EditorGUILayout.HelpBox(Styles.NoMaterialMappingsHelp.text, MessageType.Warning); } // hidden for multi-selection if (m_MaterialImportMode.intValue != (int)ModelImporterMaterialImportMode.None && targets.Length == 1 && m_Materials.arraySize > 0 && m_MaterialLocation.intValue != 0 && !m_MaterialLocation.hasMultipleDifferentValues && !m_Materials.hasMultipleDifferentValues && !m_ExternalObjects.hasMultipleDifferentValues) { GUILayout.Label(Styles.ExternalMaterialMappings, EditorStyles.boldLabel); MaterialRemapOptions(); DoMaterialRemapList(); } } internal override void ResetValues() { serializedObject.Update(); BuildMaterialsCache(); BuildExternalObjectsCache(); EvaluateMaterialExtractionState(); } void DoMaterialRemapList() { // OnEnabled is not called consistently when the asset gets reimported, we need to rebuild the cache here if it's outdated. if (m_ExternalObjects.arraySize != m_ExternalObjectsCache.Count()) ResetValues(); // The list of material names is immutable, whereas the map of external objects can change based on user actions. // For each material name, map the external object associated with it where one exists. for (int materialIdx = 0; materialIdx < m_MaterialsCache.Count; ++materialIdx) { var mat = m_MaterialsCache[materialIdx]; bool hasMatchingCachedObject = m_ExternalObjectsCache.TryGetValue(new Tuple<string, string>(mat.name, mat.type), out var cachedExternalObject) && cachedExternalObject != null; if (hasMatchingCachedObject) { //The material already has a serialized property, so use it! MaterialPropertyGUI(mat, cachedExternalObject); } else { //The material doesn't have a serialized property, so it's going to have to draw the GUI a different way! MaterialPropertyGUI(mat); } } } void MaterialPropertyGUI(MaterialCache materialCache, ExternalObjectCache externalObjectCache) { GUIContent nameLabel = EditorGUIUtility.TextContent(materialCache.name); nameLabel.tooltip = materialCache.name; EditorGUI.BeginChangeCheck(); SerializedProperty property = externalObjectCache.property; var previousMaterial = property.objectReferenceValue as Material; EditorGUILayout.ObjectField(property, typeof(Material), nameLabel); Material material = property.objectReferenceValue as Material; if (EditorGUI.EndChangeCheck()) { if (material == null) { m_ExternalObjects.DeleteArrayElementAtIndex(externalObjectCache.propertyIdx); BuildExternalObjectsCache(); } else { var importer = target as ModelImporter; if (AssetDatabase.GetAssetPath(material) == importer.assetPath) { Debug.LogError(string.Format("{0} is a sub-asset of {1} and cannot be used as an external material.", material.name, Path.GetFileName(importer.assetPath))); property.objectReferenceValue = previousMaterial; } else { var pair = m_ExternalObjects.GetArrayElementAtIndex(externalObjectCache.propertyIdx); pair.FindPropertyRelative("second").objectReferenceValue = material; BuildExternalObjectsCache(); } } EvaluateMaterialExtractionState(); } } void MaterialPropertyGUI(MaterialCache materialCache) { GUIContent nameLabel = EditorGUIUtility.TextContent(materialCache.name); nameLabel.tooltip = materialCache.name; EditorGUI.BeginChangeCheck(); Material material = ObjectFieldWithPPtrHashID(nameLabel, null, typeof(Material), false) as Material; if (EditorGUI.EndChangeCheck()) { if (material != null) { var importer = target as ModelImporter; if (AssetDatabase.GetAssetPath(material) == importer.assetPath) { Debug.LogError(string.Format("{0} is a sub-asset of {1} and cannot be used as an external material.", material.name, Path.GetFileName(importer.assetPath))); } else { m_ExternalObjects.arraySize++; var pair = m_ExternalObjects.GetArrayElementAtIndex(m_ExternalObjects.arraySize - 1); pair.FindPropertyRelative("first.name").stringValue = materialCache.name; pair.FindPropertyRelative("first.type").stringValue = materialCache.type; pair.FindPropertyRelative("first.assembly").stringValue = materialCache.assembly; pair.FindPropertyRelative("second").objectReferenceValue = material; // ExternalObjects is serialized as a map, so items are reordered when deserializing. // We need to update the serializedObject to trigger the reordering before rebuilding the cache. serializedObject.ApplyModifiedProperties(); serializedObject.Update(); BuildExternalObjectsCache(); } } EvaluateMaterialExtractionState(); } } private static readonly int s_PPtrHash = "s_PPtrHash".GetHashCode(); // Taken from EditorGUI in order to work arround the issue of ObjectField using different ControlIDs when a Serialized property is passed as argument. private static Object ObjectFieldWithPPtrHashID(GUIContent label, Object obj, Type objType, bool allowSceneObjects, params GUILayoutOption[] options) { var height = EditorGUIUtility.HasObjectThumbnail(objType) ? EditorGUI.kObjectFieldThumbnailHeight : EditorGUI.kSingleLineHeight; Rect position = EditorGUILayout.GetControlRect(true, height, options); int id = GUIUtility.GetControlID(s_PPtrHash, FocusType.Keyboard, position); position = EditorGUI.PrefixLabel(position, id, label); if (EditorGUIUtility.HasObjectThumbnail(objType) && position.height > EditorGUI.kSingleLineHeight) { // Make object field with thumbnail quadratic and align to the right float size = Mathf.Min(position.width, position.height); position.height = size; position.xMin = position.xMax - size; } return EditorGUI.DoObjectField(position, position, id, obj, null, objType, null, allowSceneObjects); } } }
UnityCsReference/Modules/AssetPipelineEditor/ImportSettings/ModelImporterMaterialEditor.cs/0
{ "file_path": "UnityCsReference/Modules/AssetPipelineEditor/ImportSettings/ModelImporterMaterialEditor.cs", "repo_id": "UnityCsReference", "token_count": 17068 }
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 System.IO; using System.Runtime.InteropServices; using UnityEditor.Utils; using UnityEngine; using UnityEngine.Bindings; namespace UnityEditor { [NativeHeader("Editor/Src/ScriptCompilation/RuleSetFiles.h")] [ExcludeFromPreset] internal sealed class RuleSetFileCache { [FreeFunction("GetAllRuleSetFilePaths")] internal static extern string[] GetAllPaths(); [FreeFunction] internal static extern string GetRuleSetFilePathInRootFolder(string ruleSetFileNameWithoutExtension); [FreeFunction] internal static extern string GetRuleSetFilePathForScriptAssembly(string scriptAssemblyOriginPath); internal static string GetPathForAssembly(string scriptAssemblyOriginPath) { if (String.IsNullOrEmpty(scriptAssemblyOriginPath)) { return default; } string formattedPath = scriptAssemblyOriginPath.ConvertSeparatorsToUnity().TrimTrailingSlashes(); string ruleSetFilePath = GetRuleSetFilePathForScriptAssembly(formattedPath); return String.IsNullOrEmpty(ruleSetFilePath) ? GetRuleSetFilePathInRootFolder("Default") : ruleSetFilePath; } } }
UnityCsReference/Modules/AssetPipelineEditor/Public/RuleSetCache.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/AssetPipelineEditor/Public/RuleSetCache.bindings.cs", "repo_id": "UnityCsReference", "token_count": 472 }
369
// Unity 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; namespace UnityEngine.Audio { [NativeHeader("Modules/Audio/Public/ScriptBindings/AudioPlayableOutput.bindings.h")] [NativeHeader("Modules/Audio/Public/Director/AudioPlayableOutput.h")] [NativeHeader("Modules/Audio/Public/AudioSource.h")] [StaticAccessor("AudioPlayableOutputBindings", StaticAccessorType.DoubleColon)] [RequiredByNativeCode] public struct AudioPlayableOutput : IPlayableOutput { private PlayableOutputHandle m_Handle; public static AudioPlayableOutput Create(PlayableGraph graph, string name, AudioSource target) { PlayableOutputHandle handle; if (!AudioPlayableGraphExtensions.InternalCreateAudioOutput(ref graph, name, out handle)) return AudioPlayableOutput.Null; AudioPlayableOutput output = new AudioPlayableOutput(handle); output.SetTarget(target); return output; } internal AudioPlayableOutput(PlayableOutputHandle handle) { if (handle.IsValid()) { if (!handle.IsPlayableOutputOfType<AudioPlayableOutput>()) throw new InvalidCastException("Can't set handle: the playable is not an AudioPlayableOutput."); } m_Handle = handle; } public static AudioPlayableOutput Null { get { return new AudioPlayableOutput(PlayableOutputHandle.Null); } } public PlayableOutputHandle GetHandle() { return m_Handle; } public static implicit operator PlayableOutput(AudioPlayableOutput output) { return new PlayableOutput(output.GetHandle()); } public static explicit operator AudioPlayableOutput(PlayableOutput output) { return new AudioPlayableOutput(output.GetHandle()); } public AudioSource GetTarget() { return InternalGetTarget(ref m_Handle); } public void SetTarget(AudioSource value) { InternalSetTarget(ref m_Handle, value); } public bool GetEvaluateOnSeek() { return InternalGetEvaluateOnSeek(ref m_Handle); } public void SetEvaluateOnSeek(bool value) { InternalSetEvaluateOnSeek(ref m_Handle, value); } [NativeThrows] extern private static AudioSource InternalGetTarget(ref PlayableOutputHandle output); [NativeThrows] extern private static void InternalSetTarget(ref PlayableOutputHandle output, AudioSource target); [NativeThrows] extern private static bool InternalGetEvaluateOnSeek(ref PlayableOutputHandle output); [NativeThrows] extern private static void InternalSetEvaluateOnSeek(ref PlayableOutputHandle output, bool value); } }
UnityCsReference/Modules/Audio/Public/ScriptBindings/AudioPlayableOutput.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Audio/Public/ScriptBindings/AudioPlayableOutput.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1245 }
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 UnityEngine; using UnityEngine.Scripting; using UnityEngine.Bindings; using UnityEngine.Scripting.APIUpdating; //TODO: This entire file can be removed in 2019.1 or above, with the associated ScriptUpdater Integration Tests namespace UnityEditor.Experimental.Build.AssetBundle { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("UnityEditor.Experimental.Build.AssetBundle.CompressionType has been deprecated. Use UnityEngine.CompressionType instead (UnityUpgradable) -> [UnityEngine] UnityEngine.CompressionType", true)] public enum CompressionType { None, Lzma, Lz4, Lz4HC, } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("UnityEditor.Experimental.Build.AssetBundle.CompressionLevel has been deprecated. Use UnityEngine.CompressionLevel instead (UnityUpgradable) -> [UnityEngine] UnityEngine.CompressionLevel", true)] public enum CompressionLevel { None, Fastest, Fast, Normal, High, Maximum, } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("UnityEditor.Experimental.Build.AssetBundle.BuildCompression has been deprecated. Use UnityEngine.BuildCompression instead (UnityUpgradable) -> [UnityEngine] UnityEngine.BuildCompression", true)] public partial struct BuildCompression { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("DefaultUncompressed has been deprecated. Use Uncompressed instead (UnityUpgradable) -> [UnityEngine] UnityEngine.BuildCompression.Uncompressed", true)] public static readonly BuildCompression DefaultUncompressed; [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("DefaultLZ4 has been deprecated. Use LZ4 instead (UnityUpgradable) -> [UnityEngine] UnityEngine.BuildCompression.LZ4", true)] public static readonly BuildCompression DefaultLZ4; [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("DefaultLZMA has been deprecated. Use LZMA instead (UnityUpgradable) -> [UnityEngine] UnityEngine.BuildCompression.LZMA", true)] public static readonly BuildCompression DefaultLZMA; } }
UnityCsReference/Modules/BuildPipeline/Editor/Managed/BuildCompression.deprecated.cs/0
{ "file_path": "UnityCsReference/Modules/BuildPipeline/Editor/Managed/BuildCompression.deprecated.cs", "repo_id": "UnityCsReference", "token_count": 847 }
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 System.Runtime.InteropServices; using UnityEngine.Bindings; using UnityEngine; using UnityEngine.Scripting; namespace UnityEditor.Build.Content { public enum FileType { NonAssetType = 0, DeprecatedCachedAssetType = 1, SerializedAssetType = 2, MetaAssetType = 3 } [Serializable] [UsedByNativeCode] [StructLayout(LayoutKind.Sequential)] [NativeHeader("Modules/BuildPipeline/Editor/Public/ObjectIdentifier.h")] [StaticAccessor("BuildPipeline", StaticAccessorType.DoubleColon)] public struct ObjectIdentifier : IEquatable<ObjectIdentifier> { [NativeName("guid")] internal GUID m_GUID; public GUID guid { get => m_GUID; internal set => m_GUID = value; } [NativeName("localIdentifierInFile")] internal long m_LocalIdentifierInFile; public long localIdentifierInFile { get => m_LocalIdentifierInFile; internal set => m_LocalIdentifierInFile = value; } [NativeName("fileType")] internal FileType m_FileType; public FileType fileType { get => m_FileType; internal set => m_FileType = value; } [NativeName("filePath")] internal string m_FilePath; public string filePath { get => m_FilePath; internal set => m_FilePath = value; } public override string ToString() { return UnityString.Format("{{ guid: {0}, fileID: {1}, type: {2}, path: {3}}}", m_GUID, m_LocalIdentifierInFile, m_FileType, m_FilePath); } public static bool operator==(ObjectIdentifier a, ObjectIdentifier b) { if (a.m_GUID != b.m_GUID) return false; if (a.m_LocalIdentifierInFile != b.m_LocalIdentifierInFile) return false; if (a.m_FileType != b.m_FileType) return false; if (a.m_FilePath != b.m_FilePath) return false; return true; } public static bool operator!=(ObjectIdentifier a, ObjectIdentifier b) { return !(a == b); } public static bool operator<(ObjectIdentifier a, ObjectIdentifier b) { if (a.m_GUID == b.m_GUID) return a.m_LocalIdentifierInFile < b.m_LocalIdentifierInFile; return a.m_GUID < b.m_GUID; } public static bool operator>(ObjectIdentifier a, ObjectIdentifier b) { if (a.m_GUID == b.m_GUID) return a.m_LocalIdentifierInFile > b.m_LocalIdentifierInFile; return a.m_GUID > b.m_GUID; } public override bool Equals(object obj) { return obj is ObjectIdentifier && Equals((ObjectIdentifier)obj); } public bool Equals(ObjectIdentifier other) { return this == other; } public override int GetHashCode() { unchecked { var hashCode = m_GUID.GetHashCode(); hashCode = (hashCode * 397) ^ m_LocalIdentifierInFile.GetHashCode(); hashCode = (hashCode * 397) ^ (int)m_FileType; if (!string.IsNullOrEmpty(m_FilePath)) hashCode = (hashCode * 397) ^ m_FilePath.GetHashCode(); return hashCode; } } [FreeFunction("GetObjectFromObjectIdentifier")] public static extern UnityEngine.Object ToObject(ObjectIdentifier objectId); [FreeFunction("GetInstanceIDFromObjectIdentifier")] public static extern int ToInstanceID(ObjectIdentifier objectId); public static bool TryGetObjectIdentifier(UnityEngine.Object targetObject, out ObjectIdentifier objectId) { return GetObjectIdentifierFromObject(targetObject, out objectId); } public static bool TryGetObjectIdentifier(int instanceID, out ObjectIdentifier objectId) { return GetObjectIdentifierFromInstanceID(instanceID, out objectId); } internal static extern bool GetObjectIdentifierFromObject(UnityEngine.Object targetObject, out ObjectIdentifier objectId); internal static extern bool GetObjectIdentifierFromInstanceID(int instanceID, out ObjectIdentifier objectId); } }
UnityCsReference/Modules/BuildPipeline/Editor/Managed/ObjectIdentifier.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/BuildPipeline/Editor/Managed/ObjectIdentifier.bindings.cs", "repo_id": "UnityCsReference", "token_count": 2068 }
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 UnityEditor.IMGUI.Controls; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.Build.Profile.Elements { internal class BuildProfileSceneList { static readonly GUIContent s_AddOpenScene = EditorGUIUtility.TrTextContent("Add Open Scenes"); BuildProfile m_Target; BuildProfileSceneTreeView m_SceneTreeView; public BuildProfileSceneList() { m_Target = null; } public BuildProfileSceneList(BuildProfile target) { m_Target = target; } public VisualElement GetSceneListGUI(IResolvedStyle container, bool showOpenScenes) { TreeViewState m_TreeViewState = new TreeViewState(); m_SceneTreeView = new BuildProfileSceneTreeView(m_TreeViewState, m_Target); m_SceneTreeView.Reload(); return new IMGUIContainer(() => { Rect rect = GUILayoutUtility.GetRect(0, container.width, 0, m_SceneTreeView.totalHeight, GUILayout.MinHeight(50)); m_SceneTreeView.OnGUI(rect); if (showOpenScenes) { GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(s_AddOpenScene)) m_SceneTreeView.AddOpenScenes(); GUILayout.EndHorizontal(); } }); } public void OnUndoRedo(in UndoRedoInfo info) { m_SceneTreeView.Reload(); } } }
UnityCsReference/Modules/BuildProfileEditor/Elements/BuildProfileSceneList.cs/0
{ "file_path": "UnityCsReference/Modules/BuildProfileEditor/Elements/BuildProfileSceneList.cs", "repo_id": "UnityCsReference", "token_count": 836 }
373
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; namespace UnityEditor.Build.Reporting { [Flags] internal enum BuildType { Player = 1, AssetBundle = 2 } }
UnityCsReference/Modules/BuildReportingEditor/Managed/BuildType.cs/0
{ "file_path": "UnityCsReference/Modules/BuildReportingEditor/Managed/BuildType.cs", "repo_id": "UnityCsReference", "token_count": 113 }
374
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine.Bindings; namespace UnityEngine { public enum ClusterInputType { Button = 0, Axis = 1, Tracker = 2, CustomProvidedInput = 3 } [NativeHeader("Modules/ClusterInput/ClusterInput.h")] [NativeConditional("ENABLE_CLUSTERINPUT")] public class ClusterInput { extern public static float GetAxis(string name); extern public static bool GetButton(string name); [NativeConditional("ENABLE_CLUSTERINPUT", "Vector3f(0.0f, 0.0f, 0.0f)")] extern public static Vector3 GetTrackerPosition(string name); [NativeConditional("ENABLE_CLUSTERINPUT", "Quartenion::identity")] extern public static Quaternion GetTrackerRotation(string name); extern public static void SetAxis(string name, float value); extern public static void SetButton(string name, bool value); extern public static void SetTrackerPosition(string name, Vector3 value); extern public static void SetTrackerRotation(string name, Quaternion value); extern public static bool AddInput(string name, string deviceName, string serverUrl, int index, ClusterInputType type); extern public static bool EditInput(string name, string deviceName, string serverUrl, int index, ClusterInputType type); extern public static bool CheckConnectionToServer(string name); } }
UnityCsReference/Modules/ClusterInput/ClusterInput.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/ClusterInput/ClusterInput.bindings.cs", "repo_id": "UnityCsReference", "token_count": 539 }
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 System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering; namespace UnityEditor.DeviceSimulation { internal class DeviceInfoAsset : ScriptableObject, ISerializationCallbackReceiver { public DeviceInfo deviceInfo; public string[] parseErrors; [NonSerialized] public bool editorResource; public string directory; public HashSet<string> availableSystemInfoFields = new HashSet<string>(); public Dictionary<GraphicsDeviceType, HashSet<string>> availableGraphicsSystemInfoFields = new Dictionary<GraphicsDeviceType, HashSet<string>>(); [SerializeField] private List<string> m_AvailableSystemInfoFields; [SerializeField] private List<GraphicsTypeFields> m_AvailableGraphicsSystemInfoFields; public void OnBeforeSerialize() { m_AvailableSystemInfoFields = new List<string>(availableSystemInfoFields); m_AvailableGraphicsSystemInfoFields = new List<GraphicsTypeFields>(); if (availableGraphicsSystemInfoFields == null) return; foreach (var graphicsDevice in availableGraphicsSystemInfoFields) { m_AvailableGraphicsSystemInfoFields.Add(new GraphicsTypeFields { type = graphicsDevice.Key, fields = new List<string>(graphicsDevice.Value) }); } } public void OnAfterDeserialize() { availableSystemInfoFields = new HashSet<string>(m_AvailableSystemInfoFields); availableGraphicsSystemInfoFields = new Dictionary<GraphicsDeviceType, HashSet<string>>(); foreach (var graphicsDevice in m_AvailableGraphicsSystemInfoFields) availableGraphicsSystemInfoFields.Add(graphicsDevice.type, new HashSet<string>(graphicsDevice.fields)); } // Wrapper because Unity can't serialize a list of lists [Serializable] private class GraphicsTypeFields { public GraphicsDeviceType type; public List<string> fields; } } [CustomEditor(typeof(DeviceInfoAsset))] internal class DeviceInfoAssetEditor : Editor { public override void OnInspectorGUI() { var asset = serializedObject.targetObject as DeviceInfoAsset; if (asset.parseErrors != null && asset.parseErrors.Length > 0) { foreach (var error in asset.parseErrors) { EditorGUILayout.HelpBox(error, MessageType.Error); } } else { EditorGUILayout.LabelField(asset.deviceInfo.friendlyName); } } } }
UnityCsReference/Modules/DeviceSimulatorEditor/DeviceInfo/DeviceInfoAsset.cs/0
{ "file_path": "UnityCsReference/Modules/DeviceSimulatorEditor/DeviceInfo/DeviceInfoAsset.cs", "repo_id": "UnityCsReference", "token_count": 1195 }
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; using UnityEngine.Rendering; namespace UnityEditor.DeviceSimulation { /// <summary> /// This class contains a subset of player settings that we need to initialize ScreenSimulation. /// </summary> [Serializable] internal class SimulationPlayerSettings { public ResolutionScalingMode resolutionScalingMode = ResolutionScalingMode.Disabled; public int targetDpi; public bool androidStartInFullscreen = true; public bool androidRenderOutsideSafeArea = true; public UIOrientation defaultOrientation = UIOrientation.AutoRotation; public bool allowedPortrait = true; public bool allowedPortraitUpsideDown = true; public bool allowedLandscapeLeft = true; public bool allowedLandscapeRight = true; public bool autoGraphicsAPI = true; public GraphicsDeviceType[] androidGraphicsAPIs = { GraphicsDeviceType.Vulkan, GraphicsDeviceType.OpenGLES3 }; public GraphicsDeviceType[] iOSGraphicsAPIs = { GraphicsDeviceType.Metal }; public SimulationPlayerSettings() { var serializedSettings = PlayerSettings.GetSerializedObject(); serializedSettings.Update(); resolutionScalingMode = (ResolutionScalingMode)serializedSettings.FindProperty("resolutionScalingMode").intValue; targetDpi = serializedSettings.FindProperty("targetPixelDensity").intValue; androidStartInFullscreen = serializedSettings.FindProperty("androidStartInFullscreen").boolValue; androidRenderOutsideSafeArea = serializedSettings.FindProperty("androidRenderOutsideSafeArea").boolValue; defaultOrientation = PlayerSettings.defaultInterfaceOrientation; allowedPortrait = PlayerSettings.allowedAutorotateToPortrait; allowedPortraitUpsideDown = PlayerSettings.allowedAutorotateToPortraitUpsideDown; allowedLandscapeLeft = PlayerSettings.allowedAutorotateToLandscapeLeft; allowedLandscapeRight = PlayerSettings.allowedAutorotateToLandscapeRight; if (!PlayerSettings.GetUseDefaultGraphicsAPIs(BuildTarget.Android)) androidGraphicsAPIs = PlayerSettings.GetGraphicsAPIs(BuildTarget.Android); if (!PlayerSettings.GetUseDefaultGraphicsAPIs(BuildTarget.iOS)) iOSGraphicsAPIs = PlayerSettings.GetGraphicsAPIs(BuildTarget.iOS); } } }
UnityCsReference/Modules/DeviceSimulatorEditor/SimulatorPlayerSettings.cs/0
{ "file_path": "UnityCsReference/Modules/DeviceSimulatorEditor/SimulatorPlayerSettings.cs", "repo_id": "UnityCsReference", "token_count": 879 }
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; using System.Collections.Generic; using System.Threading; using UnityEngine; using UnityEngine.Bindings; using UnityEngine.Scripting; namespace UnityEngine.Playables { [NativeHeader("Modules/Director/ScriptBindings/PlayableSystems.bindings.h")] [StaticAccessor("PlayableSystemsBindings", StaticAccessorType.DoubleColon)] internal static class PlayableSystems { public delegate void PlayableSystemDelegate(IReadOnlyList<DataPlayableOutput> outputs); public enum PlayableSystemStage : ushort { FixedUpdate, FixedUpdatePostPhysics, Update, AnimationBegin, AnimationEnd, LateUpdate, Render } public static void RegisterSystemPhaseDelegate<TDataStream>(PlayableSystemStage stage, PlayableSystemDelegate systemDelegate) where TDataStream : new() { RegisterSystemPhaseDelegate(typeof(TDataStream), stage, systemDelegate); } static void RegisterSystemPhaseDelegate(System.Type streamType, PlayableSystemStage stage, PlayableSystemDelegate systemDelegate) { int typeIndex = RegisterStreamStage(streamType, (int)stage); try { s_RWLock.EnterWriteLock(); s_SystemTypes.TryAdd(typeIndex, streamType); int combinedId = CombineTypeAndIndex(typeIndex, stage); if (!s_Delegates.TryAdd(combinedId, systemDelegate)) { s_Delegates[combinedId] = systemDelegate; } } finally { s_RWLock.ExitWriteLock(); } } static int CombineTypeAndIndex(int typeIndex, PlayableSystemStage stage) { return typeIndex << 16 | (int)stage; } private unsafe class DataPlayableOutputList : IReadOnlyList<DataPlayableOutput> { public DataPlayableOutputList(PlayableOutputHandle* outputs, int count) { m_Outputs = outputs; m_Count = count; } public DataPlayableOutput this[int index] { get { if (index >= m_Count) throw new IndexOutOfRangeException($"index {index} is greater than the number of items: {m_Count}"); if (index < 0) throw new IndexOutOfRangeException($"index cannot be negative"); return new DataPlayableOutput(m_Outputs[index]); } } public int Count => m_Count; public IEnumerator<DataPlayableOutput> GetEnumerator() { return new DataPlayableOutputEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private class DataPlayableOutputEnumerator : IEnumerator<DataPlayableOutput> { public DataPlayableOutputEnumerator(DataPlayableOutputList list) { m_List = list; m_Index = -1; } public DataPlayableOutput Current { get { try { return m_List[m_Index]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException("Enumeration has either not started or has already finished."); } } } object IEnumerator.Current => Current; public void Dispose() { m_List = null; } public bool MoveNext() { m_Index++; return m_Index < m_List.Count; } public void Reset() { m_Index = -1; } DataPlayableOutputList m_List; int m_Index; } PlayableOutputHandle* m_Outputs; int m_Count; } [RequiredByNativeCode] private unsafe static bool Internal_CallSystemDelegate(int systemIndex, PlayableSystemStage stage, IntPtr outputsPtr, int numOutputs) { PlayableOutputHandle* outputs = (PlayableOutputHandle*)outputsPtr; int combinedId = CombineTypeAndIndex(systemIndex, stage); bool typeFound = false; bool systemFound = false; PlayableSystemDelegate systemDelegate = null; s_RWLock.EnterReadLock(); typeFound = s_SystemTypes.TryGetValue(systemIndex, out Type systemType); if (typeFound) { systemFound = s_Delegates.TryGetValue(combinedId, out systemDelegate) && systemDelegate != null; } s_RWLock.ExitReadLock(); if (!typeFound || !systemFound) return false; var outputsArgument = new DataPlayableOutputList(outputs, numOutputs); systemDelegate(outputsArgument); return true; } [ThreadAndSerializationSafe] private extern static int RegisterStreamStage(System.Type streamType, int stage); static PlayableSystems() { s_Delegates = new Dictionary<int, PlayableSystemDelegate>(); s_SystemTypes = new Dictionary<int, Type>(); s_RWLock = new ReaderWriterLockSlim(); } static Dictionary<int, Type> s_SystemTypes; static Dictionary<int, PlayableSystemDelegate> s_Delegates; static ReaderWriterLockSlim s_RWLock; } }
UnityCsReference/Modules/Director/ScriptBindings/PlayableSystems.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Director/ScriptBindings/PlayableSystems.bindings.cs", "repo_id": "UnityCsReference", "token_count": 3077 }
378
// 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.UIElements; namespace UnityEditor.Toolbars { [EditorToolbarElement("Editor Utility/Layout", typeof(DefaultMainToolbar))] sealed class LayoutDropdown : EditorToolbarDropdown { public LayoutDropdown() { name = "LayoutDropdown"; text = Toolbar.lastLoadedLayoutName; //Only assigned once, UI is recreated when changing layout clicked += () => OpenLayoutWindow(worldBound); tooltip = L10n.Tr("Select editor layout"); RegisterCallback<AttachToPanelEvent>(OnAttachedToPanel); RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel); EditorApplication.delayCall += CheckAvailability; //Immediately after a domain reload, calling check availability sometimes returns the wrong value } void OnAttachedToPanel(AttachToPanelEvent evt) { ModeService.modeChanged += OnModeChanged; } void OnDetachFromPanel(DetachFromPanelEvent evt) { ModeService.modeChanged -= OnModeChanged; } void OpenLayoutWindow(Rect buttonRect) { Vector2 temp = GUIUtility.GUIToScreenPoint(new Vector2(buttonRect.x, buttonRect.y)); buttonRect.x = temp.x; buttonRect.y = temp.y; EditorUtility.Internal_DisplayPopupMenu(buttonRect, "Window/Layouts", Toolbar.get, 0, true); } void OnModeChanged(ModeService.ModeChangedArgs args) { CheckAvailability(); } void CheckAvailability() { style.display = ModeService.HasCapability(ModeCapability.LayoutWindowMenu, true) ? DisplayStyle.Flex : DisplayStyle.None; } } }
UnityCsReference/Modules/EditorToolbar/ToolbarElements/LayoutDropdown.cs/0
{ "file_path": "UnityCsReference/Modules/EditorToolbar/ToolbarElements/LayoutDropdown.cs", "repo_id": "UnityCsReference", "token_count": 755 }
379
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEditor.Experimental.GraphView { public enum Direction { Input = 0, Output = 1 } }
UnityCsReference/Modules/GraphViewEditor/Direction.cs/0
{ "file_path": "UnityCsReference/Modules/GraphViewEditor/Direction.cs", "repo_id": "UnityCsReference", "token_count": 100 }
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.Internal; using UnityEngine.UIElements; namespace UnityEditor.Experimental.GraphView { public class Pill : VisualElement { [ExcludeFromDocs, Serializable] public new class UxmlSerializedData : VisualElement.UxmlSerializedData { #pragma warning disable 649 [SerializeField] bool highlighted; [SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags highlighted_UxmlAttributeFlags; [SerializeField] string text; [SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags text_UxmlAttributeFlags; #pragma warning restore 649 public override object CreateInstance() => new Pill(); public override void Deserialize(object obj) { base.Deserialize(obj); var e = (Pill)obj; if (ShouldWriteAttributeValue(highlighted_UxmlAttributeFlags)) e.highlighted = highlighted; if (ShouldWriteAttributeValue(text_UxmlAttributeFlags)) e.text = text; } } [Obsolete("UxmlFactory is deprecated and will be removed. Use UxmlElementAttribute instead.", false)] public new class UxmlFactory : UxmlFactory<Pill, UxmlTraits> {} [Obsolete("UxmlTraits is deprecated and will be removed. Use UxmlElementAttribute instead.", false)] public new class UxmlTraits : VisualElement.UxmlTraits { UxmlBoolAttributeDescription m_Highlighted = new UxmlBoolAttributeDescription { name = "highlighted" }; UxmlStringAttributeDescription m_Text = new UxmlStringAttributeDescription { name = "text" }; public override IEnumerable<UxmlChildElementDescription> uxmlChildElementsDescription { get { yield break; } } public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) { base.Init(ve, bag, cc); ((Pill)ve).highlighted = m_Highlighted.GetValueFromBag(bag, cc); ((Pill)ve).text = m_Text.GetValueFromBag(bag, cc); } } private readonly Label m_TitleLabel; private readonly Image m_Icon; private VisualElement m_Left; private readonly VisualElement m_LeftContainer; private VisualElement m_Right; private readonly VisualElement m_RightContainer; private bool m_Highlighted = false; public bool highlighted { get { return m_Highlighted; } set { if (m_Highlighted == value) { return; } m_Highlighted = value; if (m_Highlighted) AddToClassList("highlighted"); else RemoveFromClassList("highlighted"); } } public string text { get { return m_TitleLabel.text; } set { m_TitleLabel.text = value; } } public Texture icon { get { return m_Icon != null ? m_Icon.image : null; } set { if (m_Icon == null || m_Icon.image == value) return; m_Icon.image = value; UpdateIconVisibility(); } } public VisualElement left { get { return m_Left; } set { if (m_Left == value) return; if (m_Left != null) m_LeftContainer.Remove(m_Left); m_Left = value; if (m_Left != null) m_LeftContainer.Add(m_Left); UpdateVisibility(); } } public VisualElement right { get { return m_Right; } set { if (m_Right == value) return; if (m_Right != null) m_RightContainer.Remove(m_Right); m_Right = value; if (m_Right != null) m_RightContainer.Add(m_Right); UpdateVisibility(); } } void UpdateIconVisibility() { if (icon == null) { RemoveFromClassList("has-icon"); m_Icon.visible = false; } else { AddToClassList("has-icon"); m_Icon.visible = true; } } void UpdateVisibility() { if (m_Left != null) { AddToClassList("has-left"); m_LeftContainer.visible = true; } else { RemoveFromClassList("has-left"); m_LeftContainer.visible = false; } if (m_Right != null) { AddToClassList("has-right"); m_RightContainer.visible = true; } else { RemoveFromClassList("has-right"); m_RightContainer.visible = false; } } public Pill() { AddStyleSheetPath("StyleSheets/GraphView/Pill.uss"); var tpl = EditorGUIUtility.Load("UXML/GraphView/Pill.uxml") as VisualTreeAsset; VisualElement mainContainer = tpl.Instantiate(); m_TitleLabel = mainContainer.Q<Label>("title-label"); m_Icon = mainContainer.Q<Image>("icon"); m_LeftContainer = mainContainer.Q("input"); m_RightContainer = mainContainer.Q("output"); Add(mainContainer); AddToClassList("pill"); UpdateVisibility(); UpdateIconVisibility(); } public Pill(VisualElement left, VisualElement right) : this() { this.left = left; this.right = right; UpdateVisibility(); UpdateIconVisibility(); } } }
UnityCsReference/Modules/GraphViewEditor/Elements/Pill.cs/0
{ "file_path": "UnityCsReference/Modules/GraphViewEditor/Elements/Pill.cs", "repo_id": "UnityCsReference", "token_count": 3291 }
381
// 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.UIElements; namespace UnityEditor.Experimental.GraphView { public interface ISelectable { bool IsSelectable(); bool HitTest(Vector2 localPoint); bool Overlaps(Rect rectangle); void Select(VisualElement selectionContainer, bool additive); void Unselect(VisualElement selectionContainer); bool IsSelected(VisualElement selectionContainer); } }
UnityCsReference/Modules/GraphViewEditor/ISelectable.cs/0
{ "file_path": "UnityCsReference/Modules/GraphViewEditor/ISelectable.cs", "repo_id": "UnityCsReference", "token_count": 194 }
382
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Collections.Generic; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.Experimental.GraphView { public enum EventPropagation { Stop, Continue } public delegate EventPropagation ShortcutDelegate(); public class ShortcutHandler : Manipulator { readonly Dictionary<Event, ShortcutDelegate> m_Dictionary; public ShortcutHandler(Dictionary<Event, ShortcutDelegate> dictionary) { m_Dictionary = dictionary; } protected override void RegisterCallbacksOnTarget() { target.RegisterCallback<KeyDownEvent>(OnKeyDown); } protected override void UnregisterCallbacksFromTarget() { target.UnregisterCallback<KeyDownEvent>(OnKeyDown); } void OnKeyDown(KeyDownEvent evt) { IPanel panel = (evt.target as VisualElement)?.panel; if (panel.GetCapturingElement(PointerId.mousePointerId) != null) return; if (m_Dictionary.ContainsKey(evt.imguiEvent)) { var result = m_Dictionary[evt.imguiEvent](); if (result == EventPropagation.Stop) { evt.StopPropagation(); if (evt.imguiEvent != null) { evt.imguiEvent.Use(); } } } } } }
UnityCsReference/Modules/GraphViewEditor/Manipulators/ShortcutHandler.cs/0
{ "file_path": "UnityCsReference/Modules/GraphViewEditor/Manipulators/ShortcutHandler.cs", "repo_id": "UnityCsReference", "token_count": 768 }
383
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine.Bindings; namespace UnityEngine { [RequireComponent(typeof(Transform))] [NativeHeader("Modules/Grid/Public/GridMarshalling.h")] [NativeType(Header = "Modules/Grid/Public/Grid.h")] public sealed partial class Grid : GridLayout { public new extern Vector3 cellSize { [FreeFunction("GridBindings::GetCellSize", HasExplicitThis = true)] get; [FreeFunction("GridBindings::SetCellSize", HasExplicitThis = true)] set; } public new extern Vector3 cellGap { [FreeFunction("GridBindings::GetCellGap", HasExplicitThis = true)] get; [FreeFunction("GridBindings::SetCellGap", HasExplicitThis = true)] set; } public new extern GridLayout.CellLayout cellLayout { get; set; } public new extern GridLayout.CellSwizzle cellSwizzle { get; set; } [FreeFunction("GridBindings::CellSwizzle")] public extern static Vector3 Swizzle(GridLayout.CellSwizzle swizzle, Vector3 position); [FreeFunction("GridBindings::InverseCellSwizzle")] public extern static Vector3 InverseSwizzle(GridLayout.CellSwizzle swizzle, Vector3 position); } }
UnityCsReference/Modules/Grid/ScriptBindings/Grid.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Grid/ScriptBindings/Grid.bindings.cs", "repo_id": "UnityCsReference", "token_count": 634 }
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 System.Runtime.CompilerServices; namespace Unity.Hierarchy { /// <summary> /// Represent an enumerable of <see cref="HierarchyNode"/> with specific <see cref="HierarchyNodeFlags"/>. /// </summary> public readonly struct HierarchyViewNodesEnumerable { /// <summary> /// Delegate to filter <see cref="HierarchyNode"/> with specific <see cref="HierarchyNodeFlags"/>. /// </summary> /// <param name="node">The hierarchy node.</param> /// <param name="flags">The hierarchy node flags.</param> /// <returns><see langword="true"/> if the node passes the predicate, <see langword="false"/> otherwise</returns> internal delegate bool Predicate(in HierarchyNode node, HierarchyNodeFlags flags); readonly HierarchyViewModel m_HierarchyViewModel; readonly Predicate m_Predicate; readonly HierarchyNodeFlags m_Flags; internal HierarchyViewNodesEnumerable(HierarchyViewModel viewModel, HierarchyNodeFlags flags, Predicate predicate) { m_HierarchyViewModel = viewModel ?? throw new ArgumentNullException(nameof(viewModel)); m_Predicate = predicate ?? throw new ArgumentNullException(nameof(predicate)); m_Flags = flags; } /// <summary> /// Gets the <see cref="HierarchyNode"/> enumerator. /// </summary> /// <returns>An enumerator.</returns> public Enumerator GetEnumerator() => new Enumerator(this); /// <summary> /// An enumerator of <see cref="HierarchyNode"/>. /// </summary> public struct Enumerator { readonly HierarchyFlattened m_HierarchyFlattened; readonly HierarchyViewModel m_HierarchyViewModel; readonly int m_Version; readonly HierarchyNode m_Root; readonly HierarchyNodeFlags m_Flags; readonly Predicate m_Predicate; int m_Index; internal Enumerator(HierarchyViewNodesEnumerable enumerable) { m_HierarchyFlattened = enumerable.m_HierarchyViewModel.HierarchyFlattened; m_HierarchyViewModel = enumerable.m_HierarchyViewModel; m_Version = m_HierarchyViewModel.Version; m_Root = m_HierarchyFlattened.Hierarchy.Root; m_Flags = enumerable.m_Flags; m_Predicate = enumerable.m_Predicate; m_Index = -1; } /// <summary> /// Get the current item being enumerated. /// </summary> public ref readonly HierarchyNode Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { ThrowIfVersionChanged(); return ref HierarchyFlattenedNode.GetNodeByRef(in m_HierarchyFlattened[m_Index]); } } /// <summary> /// Move to next iterable value. /// </summary> /// <returns><see langword="true"/> if Current item is valid, <see langword="false"/> otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool MoveNext() { ThrowIfVersionChanged(); var count = m_HierarchyFlattened.Count; for (;;) { if (++m_Index >= count) return false; var node = m_HierarchyFlattened[m_Index].Node; if (node == m_Root) continue; if (m_Predicate(in node, m_Flags)) return true; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] void ThrowIfVersionChanged() { if (m_Version != m_HierarchyViewModel.Version) throw new InvalidOperationException("HierarchyViewModel was modified."); } } } }
UnityCsReference/Modules/HierarchyCore/Managed/HierarchyViewNodesEnumerable.cs/0
{ "file_path": "UnityCsReference/Modules/HierarchyCore/Managed/HierarchyViewNodesEnumerable.cs", "repo_id": "UnityCsReference", "token_count": 1974 }
385
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Runtime.CompilerServices; // Make internal visible to UIElements module. [assembly: InternalsVisibleTo("UnityEngine.UIElementsModule")] [assembly: InternalsVisibleTo("Unity.UIElements")] [assembly: InternalsVisibleTo("Unity.UIElements.Editor")] [assembly: InternalsVisibleTo("Unity.UIElements.EditorTests")] [assembly: InternalsVisibleTo("Unity.UIElements.Tests")] [assembly: InternalsVisibleTo("UnityEngine.UI.Tests")] // Make internal visible to integration test project [assembly: InternalsVisibleTo("UnityEngine.InputForUIVisualizer")] [assembly: InternalsVisibleTo("UnityEngine.InputForUITests")] [assembly: InternalsVisibleTo("Unity.Motion.Editor.AnimationWindow")]
UnityCsReference/Modules/IMGUI/AssemblyInfo.cs/0
{ "file_path": "UnityCsReference/Modules/IMGUI/AssemblyInfo.cs", "repo_id": "UnityCsReference", "token_count": 253 }
386
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; namespace UnityEngine { // The GUILayout class is the interface for Unity gui with automatic layout. public partial class GUILayout { static public void Label(Texture image, params GUILayoutOption[] options) { DoLabel(GUIContent.Temp(image), GUI.skin.label, options); } static public void Label(string text, params GUILayoutOption[] options) { DoLabel(GUIContent.Temp(text), GUI.skin.label, options); } static public void Label(GUIContent content, params GUILayoutOption[] options) { DoLabel(content, GUI.skin.label, options); } static public void Label(Texture image, GUIStyle style, params GUILayoutOption[] options) { DoLabel(GUIContent.Temp(image), style, options); } static public void Label(string text, GUIStyle style, params GUILayoutOption[] options) { DoLabel(GUIContent.Temp(text), style, options); } // Make an auto-layout label. static public void Label(GUIContent content, GUIStyle style, params GUILayoutOption[] options) { DoLabel(content, style, options); } static void DoLabel(GUIContent content, GUIStyle style, GUILayoutOption[] options) { GUI.Label(GUILayoutUtility.GetRect(content, style, options), content, style); } static public void Box(Texture image, params GUILayoutOption[] options) { DoBox(GUIContent.Temp(image), GUI.skin.box, options); } static public void Box(string text, params GUILayoutOption[] options) { DoBox(GUIContent.Temp(text), GUI.skin.box, options); } static public void Box(GUIContent content, params GUILayoutOption[] options) { DoBox(content, GUI.skin.box, options); } static public void Box(Texture image, GUIStyle style, params GUILayoutOption[] options) { DoBox(GUIContent.Temp(image), style, options); } static public void Box(string text, GUIStyle style, params GUILayoutOption[] options) { DoBox(GUIContent.Temp(text), style, options); } // Make an auto-layout box. static public void Box(GUIContent content, GUIStyle style, params GUILayoutOption[] options) { DoBox(content, style, options); } static void DoBox(GUIContent content, GUIStyle style, GUILayoutOption[] options) { GUI.Box(GUILayoutUtility.GetRect(content, style, options), content, style); } static public bool Button(Texture image, params GUILayoutOption[] options) { return DoButton(GUIContent.Temp(image), GUI.skin.button, options); } static public bool Button(string text, params GUILayoutOption[] options) { return DoButton(GUIContent.Temp(text), GUI.skin.button, options); } static public bool Button(GUIContent content, params GUILayoutOption[] options) { return DoButton(content, GUI.skin.button, options); } static public bool Button(Texture image, GUIStyle style, params GUILayoutOption[] options) { return DoButton(GUIContent.Temp(image), style, options); } static public bool Button(string text, GUIStyle style, params GUILayoutOption[] options) { return DoButton(GUIContent.Temp(text), style, options); } // Make a single press button. The user clicks them and something happens immediately. static public bool Button(GUIContent content, GUIStyle style, params GUILayoutOption[] options) { return DoButton(content, style, options); } static bool DoButton(GUIContent content, GUIStyle style, GUILayoutOption[] options) { return GUI.Button(GUILayoutUtility.GetRect(content, style, options), content, style); } static public bool RepeatButton(Texture image, params GUILayoutOption[] options) { return DoRepeatButton(GUIContent.Temp(image), GUI.skin.button, options); } static public bool RepeatButton(string text, params GUILayoutOption[] options) { return DoRepeatButton(GUIContent.Temp(text), GUI.skin.button, options); } static public bool RepeatButton(GUIContent content, params GUILayoutOption[] options) { return DoRepeatButton(content, GUI.skin.button, options); } static public bool RepeatButton(Texture image, GUIStyle style, params GUILayoutOption[] options) { return DoRepeatButton(GUIContent.Temp(image), style, options); } static public bool RepeatButton(string text, GUIStyle style, params GUILayoutOption[] options) { return DoRepeatButton(GUIContent.Temp(text), style, options); } // Make a repeating button. The button returns true as long as the user holds down the mouse static public bool RepeatButton(GUIContent content, GUIStyle style, params GUILayoutOption[] options) { return DoRepeatButton(content, style, options); } static bool DoRepeatButton(GUIContent content, GUIStyle style, GUILayoutOption[] options) { return GUI.RepeatButton(GUILayoutUtility.GetRect(content, style, options), content, style); } public static string TextField(string text, params GUILayoutOption[] options) { return DoTextField(text, -1, false, GUI.skin.textField, options); } public static string TextField(string text, int maxLength, params GUILayoutOption[] options) { return DoTextField(text, maxLength, false, GUI.skin.textField, options); } public static string TextField(string text, GUIStyle style, params GUILayoutOption[] options) { return DoTextField(text, -1, false, style, options); } // Make a single-line text field where the user can edit a string. public static string TextField(string text, int maxLength, GUIStyle style, params GUILayoutOption[] options) { return DoTextField(text, maxLength, false, style, options); } public static string PasswordField(string password, char maskChar, params GUILayoutOption[] options) { return PasswordField(password, maskChar, -1, GUI.skin.textField, options); } public static string PasswordField(string password, char maskChar, int maxLength, params GUILayoutOption[] options) { return PasswordField(password, maskChar, maxLength, GUI.skin.textField, options); } public static string PasswordField(string password, char maskChar, GUIStyle style, params GUILayoutOption[] options) { return PasswordField(password, maskChar, -1, style, options); } // Make a text field where the user can enter a password. public static string PasswordField(string password, char maskChar, int maxLength, GUIStyle style, params GUILayoutOption[] options) { GUIContent t = GUIContent.Temp(GUI.PasswordFieldGetStrToShow(password, maskChar)); return GUI.PasswordField(GUILayoutUtility.GetRect(t, GUI.skin.textField, options), password, maskChar, maxLength, style); } public static string TextArea(string text, params GUILayoutOption[] options) { return DoTextField(text, -1, true, GUI.skin.textArea, options); } public static string TextArea(string text, int maxLength, params GUILayoutOption[] options) { return DoTextField(text, maxLength, true, GUI.skin.textArea, options); } public static string TextArea(string text, GUIStyle style, params GUILayoutOption[] options) { return DoTextField(text, -1, true, style, options); } // Make a multi-line text field where the user can edit a string. public static string TextArea(string text, int maxLength, GUIStyle style, params GUILayoutOption[] options) { return DoTextField(text, maxLength, true, style, options); } static string DoTextField(string text, int maxLength, bool multiline, GUIStyle style, GUILayoutOption[] options) { int id = GUIUtility.GetControlID(FocusType.Keyboard); GUIContent content = GUIContent.Temp(text); Rect r; if (GUIUtility.keyboardControl != id) content = GUIContent.Temp(text); else content = GUIContent.Temp(text + GUIUtility.compositionString); r = GUILayoutUtility.GetRect(content, style, options); if (GUIUtility.keyboardControl == id) content = GUIContent.Temp(text); GUI.DoTextField(r, id, content, multiline, maxLength, style); return content.text; } static public bool Toggle(bool value, Texture image, params GUILayoutOption[] options) { return DoToggle(value, GUIContent.Temp(image), GUI.skin.toggle, options); } static public bool Toggle(bool value, string text, params GUILayoutOption[] options) { return DoToggle(value, GUIContent.Temp(text), GUI.skin.toggle, options); } static public bool Toggle(bool value, GUIContent content, params GUILayoutOption[] options) { return DoToggle(value, content, GUI.skin.toggle, options); } static public bool Toggle(bool value, Texture image, GUIStyle style, params GUILayoutOption[] options) { return DoToggle(value, GUIContent.Temp(image), style, options); } static public bool Toggle(bool value, string text, GUIStyle style, params GUILayoutOption[] options) { return DoToggle(value, GUIContent.Temp(text), style, options); } // Make an on/off toggle button. static public bool Toggle(bool value, GUIContent content, GUIStyle style, params GUILayoutOption[] options) { return DoToggle(value, content, style, options); } static bool DoToggle(bool value, GUIContent content, GUIStyle style, GUILayoutOption[] options) { return GUI.Toggle(GUILayoutUtility.GetRect(content, style, options), value, content, style); } public static int Toolbar(int selected, string[] texts, params GUILayoutOption[] options) { return Toolbar(selected, GUIContent.Temp(texts), GUI.skin.button, options); } public static int Toolbar(int selected, Texture[] images, params GUILayoutOption[] options) { return Toolbar(selected, GUIContent.Temp(images), GUI.skin.button, options); } public static int Toolbar(int selected, GUIContent[] contents, params GUILayoutOption[] options) { return Toolbar(selected, contents, GUI.skin.button, options); } public static int Toolbar(int selected, string[] texts, GUIStyle style, params GUILayoutOption[] options) { return Toolbar(selected, GUIContent.Temp(texts), style, options); } public static int Toolbar(int selected, Texture[] images, GUIStyle style, params GUILayoutOption[] options) { return Toolbar(selected, GUIContent.Temp(images), style, options); } public static int Toolbar(int selected, string[] texts, GUIStyle style, GUI.ToolbarButtonSize buttonSize, params GUILayoutOption[] options) { return Toolbar(selected, GUIContent.Temp(texts), style, buttonSize, options); } public static int Toolbar(int selected, Texture[] images, GUIStyle style, GUI.ToolbarButtonSize buttonSize, params GUILayoutOption[] options) { return Toolbar(selected, GUIContent.Temp(images), style, buttonSize, options); } public static int Toolbar(int selected, GUIContent[] contents, GUIStyle style, params GUILayoutOption[] options) { return Toolbar(selected, contents, style, GUI.ToolbarButtonSize.Fixed, options); } public static int Toolbar(int selected, GUIContent[] contents, GUIStyle style, GUI.ToolbarButtonSize buttonSize, params GUILayoutOption[] options) { return Toolbar(selected, contents, null, style, buttonSize, options); } public static int Toolbar(int selected, GUIContent[] contents, bool[] enabled, GUIStyle style, params GUILayoutOption[] options) { return Toolbar(selected, contents, enabled, style, GUI.ToolbarButtonSize.Fixed, options); } internal static int Toolbar(int selected, GUIContent[] contents, bool[] enabled, GUIStyle style, GUIStyle firstStyle, GUIStyle midStyle, GUIStyle lastStyle, params GUILayoutOption[] options) { return Toolbar(selected, contents, enabled, style, firstStyle, midStyle, lastStyle, GUI.ToolbarButtonSize.Fixed, options); } public static int Toolbar(int selected, GUIContent[] contents, bool[] enabled, GUIStyle style, GUI.ToolbarButtonSize buttonSize, params GUILayoutOption[] options) { GUIStyle firstStyle, midStyle, lastStyle; GUI.FindStyles(ref style, out firstStyle, out midStyle, out lastStyle, "left", "mid", "right"); return Toolbar(selected, contents, enabled, style, firstStyle, midStyle, lastStyle, buttonSize, options); } internal static int Toolbar(int selected, GUIContent[] contents, bool[] enabled, GUIStyle style, GUIStyle firstStyle, GUIStyle midStyle, GUIStyle lastStyle, GUI.ToolbarButtonSize buttonSize, params GUILayoutOption[] options) { Vector2 size = new Vector2(); int count = contents.Length; GUIStyle currentStyle = count > 1 ? firstStyle : style; GUIStyle nextStyle = count > 1 ? midStyle : style; GUIStyle endStyle = count > 1 ? lastStyle : style; float margins = 0; for (int i = 0; i < contents.Length; i++) { if (i == count - 2) nextStyle = endStyle; Vector2 thisSize = currentStyle.CalcSize(contents[i]); switch (buttonSize) { case GUI.ToolbarButtonSize.Fixed: if (thisSize.x > size.x) size.x = thisSize.x; break; case GUI.ToolbarButtonSize.FitToContents: size.x += thisSize.x; break; } if (thisSize.y > size.y) size.y = thisSize.y; // add spacing if (i == count - 1) margins += currentStyle.margin.right; else margins += Mathf.Max(currentStyle.margin.right, nextStyle.margin.left); currentStyle = nextStyle; } switch (buttonSize) { case GUI.ToolbarButtonSize.Fixed: size.x = size.x * contents.Length + margins; break; case GUI.ToolbarButtonSize.FitToContents: size.x += margins; break; } return GUI.Toolbar(GUILayoutUtility.GetRect(size.x, size.y, style, options), selected, contents, null, style, firstStyle, midStyle, lastStyle, buttonSize, enabled); } public static int SelectionGrid(int selected, string[] texts, int xCount, params GUILayoutOption[] options) { return SelectionGrid(selected, GUIContent.Temp(texts), xCount, GUI.skin.button, options); } public static int SelectionGrid(int selected, Texture[] images, int xCount, params GUILayoutOption[] options) { return SelectionGrid(selected, GUIContent.Temp(images), xCount, GUI.skin.button, options); } public static int SelectionGrid(int selected, GUIContent[] content, int xCount, params GUILayoutOption[] options) { return SelectionGrid(selected, content, xCount, GUI.skin.button, options); } public static int SelectionGrid(int selected, string[] texts, int xCount, GUIStyle style, params GUILayoutOption[] options) { return SelectionGrid(selected, GUIContent.Temp(texts), xCount, style, options); } public static int SelectionGrid(int selected, Texture[] images, int xCount, GUIStyle style, params GUILayoutOption[] options) { return SelectionGrid(selected, GUIContent.Temp(images), xCount, style, options); } // Make a Selection Grid public static int SelectionGrid(int selected, GUIContent[] contents, int xCount, GUIStyle style, params GUILayoutOption[] options) { return GUI.SelectionGrid(GUIGridSizer.GetRect(contents, xCount, style, options), selected, contents, xCount, style); } static public float HorizontalSlider(float value, float leftValue, float rightValue, params GUILayoutOption[] options) { return DoHorizontalSlider(value, leftValue, rightValue, GUI.skin.horizontalSlider, GUI.skin.horizontalSliderThumb, options); } // A horizontal slider the user can drag to change a value between a min and a max. static public float HorizontalSlider(float value, float leftValue, float rightValue, GUIStyle slider, GUIStyle thumb, params GUILayoutOption[] options) { return DoHorizontalSlider(value, leftValue, rightValue, slider, thumb, options); } static float DoHorizontalSlider(float value, float leftValue, float rightValue, GUIStyle slider, GUIStyle thumb, GUILayoutOption[] options) { return GUI.HorizontalSlider(GUILayoutUtility.GetRect(GUIContent.Temp("mmmm"), slider, options), value, leftValue, rightValue, slider, thumb); } static public float VerticalSlider(float value, float leftValue, float rightValue, params GUILayoutOption[] options) { return DoVerticalSlider(value, leftValue, rightValue, GUI.skin.verticalSlider, GUI.skin.verticalSliderThumb, options); } // A vertical slider the user can drag to change a value between a min and a max. static public float VerticalSlider(float value, float leftValue, float rightValue, GUIStyle slider, GUIStyle thumb, params GUILayoutOption[] options) { return DoVerticalSlider(value, leftValue, rightValue, slider, thumb, options); } static float DoVerticalSlider(float value, float leftValue, float rightValue, GUIStyle slider, GUIStyle thumb, params GUILayoutOption[] options) { return GUI.VerticalSlider(GUILayoutUtility.GetRect(GUIContent.Temp("\n\n\n\n\n"), slider, options), value, leftValue, rightValue, slider, thumb); } public static float HorizontalScrollbar(float value, float size, float leftValue, float rightValue, params GUILayoutOption[] options) { return HorizontalScrollbar(value, size, leftValue, rightValue, GUI.skin.horizontalScrollbar, options); } // Make a horiztonal scrollbar. public static float HorizontalScrollbar(float value, float size, float leftValue, float rightValue, GUIStyle style, params GUILayoutOption[] options) { return GUI.HorizontalScrollbar(GUILayoutUtility.GetRect(GUIContent.Temp("mmmm"), style, options), value, size, leftValue, rightValue, style); } public static float VerticalScrollbar(float value, float size, float topValue, float bottomValue, params GUILayoutOption[] options) { return VerticalScrollbar(value, size, topValue, bottomValue, GUI.skin.verticalScrollbar, options); } // Make a vertical scrollbar. public static float VerticalScrollbar(float value, float size, float topValue, float bottomValue, GUIStyle style, params GUILayoutOption[] options) { return GUI.VerticalScrollbar(GUILayoutUtility.GetRect(GUIContent.Temp("\n\n\n\n"), style, options), value, size, topValue, bottomValue, style); } // Insert a space in the current layout group. static public void Space(float pixels) { GUIUtility.CheckOnGUI(); if (GUILayoutUtility.current.topLevel.isVertical) GUILayoutUtility.GetRect(0, pixels, GUILayoutUtility.spaceStyle, GUILayout.Height(pixels)); else GUILayoutUtility.GetRect(pixels, 0, GUILayoutUtility.spaceStyle, GUILayout.Width(pixels)); // Instead of handling margins normally, we just want to insert the size. // This ensures that Space(1) adds ONE space, and doesn't prevent margin collapse. if (Event.current.type == EventType.Layout) { GUILayoutUtility.current.topLevel.entries[GUILayoutUtility.current.topLevel.entries.Count - 1].consideredForMargin = false; } } // Insert a flexible space element. static public void FlexibleSpace() { GUIUtility.CheckOnGUI(); GUILayoutOption op; if (GUILayoutUtility.current.topLevel.isVertical) op = ExpandHeight(true); else op = ExpandWidth(true); op = new GUILayoutOption(op.type, 10000); GUILayoutUtility.GetRect(0, 0, GUILayoutUtility.spaceStyle, op); if (Event.current.type == EventType.Layout) { GUILayoutUtility.current.topLevel.entries[GUILayoutUtility.current.topLevel.entries.Count - 1].consideredForMargin = false; } } public static void BeginHorizontal(params GUILayoutOption[] options) { BeginHorizontal(GUIContent.none, GUIStyle.none, options); } public static void BeginHorizontal(GUIStyle style, params GUILayoutOption[] options) { BeginHorizontal(GUIContent.none, style, options); } public static void BeginHorizontal(string text, GUIStyle style, params GUILayoutOption[] options) { BeginHorizontal(GUIContent.Temp(text), style, options); } public static void BeginHorizontal(Texture image, GUIStyle style, params GUILayoutOption[] options) { BeginHorizontal(GUIContent.Temp(image), style, options); } // Begin a Horizontal control group. public static void BeginHorizontal(GUIContent content, GUIStyle style, params GUILayoutOption[] options) { GUILayoutGroup g = GUILayoutUtility.BeginLayoutGroup(style, options, typeof(GUILayoutGroup)); g.isVertical = false; if (style != GUIStyle.none || content != GUIContent.none) GUI.Box(g.rect, content, style); } // Close a group started with BeginHorizontal public static void EndHorizontal() { GUILayoutUtility.EndLayoutGroup(); } public static void BeginVertical(params GUILayoutOption[] options) { BeginVertical(GUIContent.none, GUIStyle.none, options); } public static void BeginVertical(GUIStyle style, params GUILayoutOption[] options) { BeginVertical(GUIContent.none, style, options); } public static void BeginVertical(string text, GUIStyle style, params GUILayoutOption[] options) { BeginVertical(GUIContent.Temp(text), style, options); } public static void BeginVertical(Texture image, GUIStyle style, params GUILayoutOption[] options) { BeginVertical(GUIContent.Temp(image), style, options); } // Begin a vertical control group. public static void BeginVertical(GUIContent content, GUIStyle style, params GUILayoutOption[] options) { GUILayoutGroup g = GUILayoutUtility.BeginLayoutGroup(style, options, typeof(GUILayoutGroup)); g.isVertical = true; if (style != GUIStyle.none || content != GUIContent.none) GUI.Box(g.rect, content, style); } // Close a group started with BeginVertical public static void EndVertical() { GUILayoutUtility.EndLayoutGroup(); } static public void BeginArea(Rect screenRect) { BeginArea(screenRect, GUIContent.none, GUIStyle.none); } static public void BeginArea(Rect screenRect, string text) { BeginArea(screenRect, GUIContent.Temp(text), GUIStyle.none); } static public void BeginArea(Rect screenRect, Texture image) { BeginArea(screenRect, GUIContent.Temp(image), GUIStyle.none); } static public void BeginArea(Rect screenRect, GUIContent content) { BeginArea(screenRect, content, GUIStyle.none); } static public void BeginArea(Rect screenRect, GUIStyle style) { BeginArea(screenRect, GUIContent.none, style); } static public void BeginArea(Rect screenRect, string text, GUIStyle style) { BeginArea(screenRect, GUIContent.Temp(text), style); } static public void BeginArea(Rect screenRect, Texture image, GUIStyle style) { BeginArea(screenRect, GUIContent.Temp(image), style); } // Begin a GUILayout block of GUI controls in a fixed screen area. static public void BeginArea(Rect screenRect, GUIContent content, GUIStyle style) { GUIUtility.CheckOnGUI(); GUILayoutGroup g = GUILayoutUtility.BeginLayoutArea(style, typeof(GUILayoutGroup)); if (Event.current.type == EventType.Layout) { g.resetCoords = true; g.minWidth = g.maxWidth = screenRect.width; g.minHeight = g.maxHeight = screenRect.height; g.rect = Rect.MinMaxRect(screenRect.xMin, screenRect.yMin, g.rect.xMax, g.rect.yMax); } GUI.BeginGroup(g.rect, content, style); } // Close a GUILayout block started with BeginArea static public void EndArea() { GUIUtility.CheckOnGUI(); GUILayoutUtility.EndLayoutArea(); if (Event.current.type == EventType.Used) return; GUI.EndGroup(); } // ====================================================== SCROLLVIEWS =============================== public static Vector2 BeginScrollView(Vector2 scrollPosition, params GUILayoutOption[] options) { return BeginScrollView(scrollPosition, false, false, GUI.skin.horizontalScrollbar, GUI.skin.verticalScrollbar, GUI.skin.scrollView, options); } public static Vector2 BeginScrollView(Vector2 scrollPosition, bool alwaysShowHorizontal, bool alwaysShowVertical, params GUILayoutOption[] options) { return BeginScrollView(scrollPosition, alwaysShowHorizontal, alwaysShowVertical, GUI.skin.horizontalScrollbar, GUI.skin.verticalScrollbar, GUI.skin.scrollView, options); } public static Vector2 BeginScrollView(Vector2 scrollPosition, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, params GUILayoutOption[] options) { return BeginScrollView(scrollPosition, false, false, horizontalScrollbar, verticalScrollbar, GUI.skin.scrollView, options); } // We need to keep both of the following versions of BeginScrollView() since it was added with a different signature in 3.5 // Adding an optional argument with params unfortunately *does* change the function signature public static Vector2 BeginScrollView(Vector2 scrollPosition, GUIStyle style) { GUILayoutOption[] option = null; return BeginScrollView(scrollPosition, style, option); } public static Vector2 BeginScrollView(Vector2 scrollPosition, GUIStyle style, params GUILayoutOption[] options) { string name = style.name; GUIStyle vertical = GUI.skin.FindStyle(name + "VerticalScrollbar"); if (vertical == null) vertical = GUI.skin.verticalScrollbar; GUIStyle horizontal = GUI.skin.FindStyle(name + "HorizontalScrollbar"); if (horizontal == null) horizontal = GUI.skin.horizontalScrollbar; return BeginScrollView(scrollPosition, false, false, horizontal, vertical, style, options); } public static Vector2 BeginScrollView(Vector2 scrollPosition, bool alwaysShowHorizontal, bool alwaysShowVertical, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, params GUILayoutOption[] options) { return BeginScrollView(scrollPosition, alwaysShowHorizontal, alwaysShowVertical, horizontalScrollbar, verticalScrollbar, GUI.skin.scrollView, options); } // Begin an automatically laid out scrollview. public static Vector2 BeginScrollView(Vector2 scrollPosition, bool alwaysShowHorizontal, bool alwaysShowVertical, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, GUIStyle background, params GUILayoutOption[] options) { GUIUtility.CheckOnGUI(); GUIScrollGroup g = (GUIScrollGroup)GUILayoutUtility.BeginLayoutGroup(background, null, typeof(GUIScrollGroup)); switch (Event.current.type) { case EventType.Layout: g.resetCoords = true; g.isVertical = true; g.stretchWidth = 1; g.stretchHeight = 1; g.verticalScrollbar = verticalScrollbar; g.horizontalScrollbar = horizontalScrollbar; g.needsVerticalScrollbar = alwaysShowVertical; g.needsHorizontalScrollbar = alwaysShowHorizontal; g.ApplyOptions(options); break; default: break; } return GUI.BeginScrollView(g.rect, scrollPosition, new Rect(0, 0, g.clientWidth, g.clientHeight), alwaysShowHorizontal, alwaysShowVertical, horizontalScrollbar, verticalScrollbar, background); } // End a scroll view begun with a call to BeginScrollView. public static void EndScrollView() { EndScrollView(true); } internal static void EndScrollView(bool handleScrollWheel) { GUILayoutUtility.EndLayoutGroup(); GUI.EndScrollView(handleScrollWheel); } public static Rect Window(int id, Rect screenRect, GUI.WindowFunction func, string text, params GUILayoutOption[] options) { return DoWindow(id, screenRect, func, GUIContent.Temp(text), GUI.skin.window, options); } public static Rect Window(int id, Rect screenRect, GUI.WindowFunction func, Texture image, params GUILayoutOption[] options) { return DoWindow(id, screenRect, func, GUIContent.Temp(image), GUI.skin.window, options); } public static Rect Window(int id, Rect screenRect, GUI.WindowFunction func, GUIContent content, params GUILayoutOption[] options) { return DoWindow(id, screenRect, func, content, GUI.skin.window, options); } public static Rect Window(int id, Rect screenRect, GUI.WindowFunction func, string text, GUIStyle style, params GUILayoutOption[] options) { return DoWindow(id, screenRect, func, GUIContent.Temp(text), style, options); } public static Rect Window(int id, Rect screenRect, GUI.WindowFunction func, Texture image, GUIStyle style, params GUILayoutOption[] options) { return DoWindow(id, screenRect, func, GUIContent.Temp(image), style, options); } // Make a popup window that layouts its contents automatically. public static Rect Window(int id, Rect screenRect, GUI.WindowFunction func, GUIContent content, GUIStyle style, params GUILayoutOption[] options) { return DoWindow(id, screenRect, func, content, style, options); } // Make an auto-sized draggable window... static Rect DoWindow(int id, Rect screenRect, GUI.WindowFunction func, GUIContent content, GUIStyle style, GUILayoutOption[] options) { GUIUtility.CheckOnGUI(); LayoutedWindow lw = new LayoutedWindow(func, screenRect, content, options, style); return GUI.Window(id, screenRect, lw.DoWindow, content, style); } private sealed class LayoutedWindow { readonly GUI.WindowFunction m_Func; readonly Rect m_ScreenRect; readonly GUILayoutOption[] m_Options; readonly GUIStyle m_Style; internal LayoutedWindow(GUI.WindowFunction f, Rect screenRect, GUIContent content, GUILayoutOption[] options, GUIStyle style) { m_Func = f; m_ScreenRect = screenRect; m_Options = options; m_Style = style; } public void DoWindow(int windowID) { GUILayoutGroup g = GUILayoutUtility.current.topLevel; switch (Event.current.type) { case EventType.Layout: // TODO: Add layoutoptions // TODO: Take titlebar size into consideration g.resetCoords = true; g.rect = m_ScreenRect; if (m_Options != null) g.ApplyOptions(m_Options); g.isWindow = true; g.windowID = windowID; g.style = m_Style; break; default: g.ResetCursor(); break; } m_Func(windowID); } } // Option passed to a control to give it an absolute width. static public GUILayoutOption Width(float width) { return new GUILayoutOption(GUILayoutOption.Type.fixedWidth, width); } // Option passed to a control to specify a minimum width.\\ static public GUILayoutOption MinWidth(float minWidth) { return new GUILayoutOption(GUILayoutOption.Type.minWidth, minWidth); } // Option passed to a control to specify a maximum width. static public GUILayoutOption MaxWidth(float maxWidth) { return new GUILayoutOption(GUILayoutOption.Type.maxWidth, maxWidth); } // Option passed to a control to give it an absolute height. static public GUILayoutOption Height(float height) { return new GUILayoutOption(GUILayoutOption.Type.fixedHeight, height); } // Option passed to a control to specify a minimum height. static public GUILayoutOption MinHeight(float minHeight) { return new GUILayoutOption(GUILayoutOption.Type.minHeight, minHeight); } // Option passed to a control to specify a maximum height. static public GUILayoutOption MaxHeight(float maxHeight) { return new GUILayoutOption(GUILayoutOption.Type.maxHeight, maxHeight); } // Option passed to a control to allow or disallow horizontal expansion. static public GUILayoutOption ExpandWidth(bool expand) { return new GUILayoutOption(GUILayoutOption.Type.stretchWidth, expand ? 1 : 0); } // Option passed to a control to allow or disallow vertical expansion. static public GUILayoutOption ExpandHeight(bool expand) { return new GUILayoutOption(GUILayoutOption.Type.stretchHeight, expand ? 1 : 0); } public class HorizontalScope : GUI.Scope { public HorizontalScope(params GUILayoutOption[] options) { BeginHorizontal(options); } public HorizontalScope(GUIStyle style, params GUILayoutOption[] options) { BeginHorizontal(style, options); } public HorizontalScope(string text, GUIStyle style, params GUILayoutOption[] options) { BeginHorizontal(text, style, options); } public HorizontalScope(Texture image, GUIStyle style, params GUILayoutOption[] options) { BeginHorizontal(image, style, options); } public HorizontalScope(GUIContent content, GUIStyle style, params GUILayoutOption[] options) { BeginHorizontal(content, style, options); } protected override void CloseScope() { EndHorizontal(); } } public class VerticalScope : GUI.Scope { public VerticalScope(params GUILayoutOption[] options) { BeginVertical(options); } public VerticalScope(GUIStyle style, params GUILayoutOption[] options) { BeginVertical(style, options); } public VerticalScope(string text, GUIStyle style, params GUILayoutOption[] options) { BeginVertical(text, style, options); } public VerticalScope(Texture image, GUIStyle style, params GUILayoutOption[] options) { BeginVertical(image, style, options); } public VerticalScope(GUIContent content, GUIStyle style, params GUILayoutOption[] options) { BeginVertical(content, style, options); } protected override void CloseScope() { EndVertical(); } } public class AreaScope : GUI.Scope { public AreaScope(Rect screenRect) { BeginArea(screenRect); } public AreaScope(Rect screenRect, string text) { BeginArea(screenRect, text); } public AreaScope(Rect screenRect, Texture image) { BeginArea(screenRect, image); } public AreaScope(Rect screenRect, GUIContent content) { BeginArea(screenRect, content); } public AreaScope(Rect screenRect, string text, GUIStyle style) { BeginArea(screenRect, text, style); } public AreaScope(Rect screenRect, Texture image, GUIStyle style) { BeginArea(screenRect, image, style); } public AreaScope(Rect screenRect, GUIContent content, GUIStyle style) { BeginArea(screenRect, content, style); } protected override void CloseScope() { EndArea(); } } public class ScrollViewScope : GUI.Scope { public Vector2 scrollPosition { get; private set; } public bool handleScrollWheel { get; set; } public ScrollViewScope(Vector2 scrollPosition, params GUILayoutOption[] options) { handleScrollWheel = true; this.scrollPosition = BeginScrollView(scrollPosition, options); } public ScrollViewScope(Vector2 scrollPosition, bool alwaysShowHorizontal, bool alwaysShowVertical, params GUILayoutOption[] options) { handleScrollWheel = true; this.scrollPosition = BeginScrollView(scrollPosition, alwaysShowHorizontal, alwaysShowVertical, options); } public ScrollViewScope(Vector2 scrollPosition, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, params GUILayoutOption[] options) { handleScrollWheel = true; this.scrollPosition = BeginScrollView(scrollPosition, horizontalScrollbar, verticalScrollbar, options); } public ScrollViewScope(Vector2 scrollPosition, GUIStyle style, params GUILayoutOption[] options) { handleScrollWheel = true; this.scrollPosition = BeginScrollView(scrollPosition, style, options); } public ScrollViewScope(Vector2 scrollPosition, bool alwaysShowHorizontal, bool alwaysShowVertical, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, params GUILayoutOption[] options) { handleScrollWheel = true; this.scrollPosition = BeginScrollView(scrollPosition, alwaysShowHorizontal, alwaysShowVertical, horizontalScrollbar, verticalScrollbar, options); } public ScrollViewScope(Vector2 scrollPosition, bool alwaysShowHorizontal, bool alwaysShowVertical, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, GUIStyle background, params GUILayoutOption[] options) { handleScrollWheel = true; this.scrollPosition = BeginScrollView(scrollPosition, alwaysShowHorizontal, alwaysShowVertical, horizontalScrollbar, verticalScrollbar, background, options); } protected override void CloseScope() { EndScrollView(handleScrollWheel); } } } }
UnityCsReference/Modules/IMGUI/GUILayout.cs/0
{ "file_path": "UnityCsReference/Modules/IMGUI/GUILayout.cs", "repo_id": "UnityCsReference", "token_count": 16173 }
387
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine.Bindings; namespace UnityEngine { [NativeHeader("Modules/IMGUI/GUIState.h")] [VisibleToOtherModules("UnityEngine.UIElementsModule")] internal class ObjectGUIState : IDisposable { internal IntPtr m_Ptr; public ObjectGUIState() { m_Ptr = Internal_Create(); } public void Dispose() { Destroy(); GC.SuppressFinalize(this); } ~ObjectGUIState() { Destroy(); } void Destroy() { if (m_Ptr != IntPtr.Zero) { Internal_Destroy(m_Ptr); m_Ptr = IntPtr.Zero; } } private static extern IntPtr Internal_Create(); [NativeMethod(IsThreadSafe = true)] private static extern void Internal_Destroy(IntPtr ptr); internal static class BindingsMarshaller { public static IntPtr ConvertToNative(ObjectGUIState objectGUIState) => objectGUIState.m_Ptr; } } }
UnityCsReference/Modules/IMGUI/ObjectGUIState.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/IMGUI/ObjectGUIState.bindings.cs", "repo_id": "UnityCsReference", "token_count": 563 }
388
// 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.Bindings; namespace UnityEngine.InputForUI { /// <summary> /// Use this event to improve text input UX by showing composition string at the end of current text field string, /// but don't append it to the text, as string might change, reduce in side, etc. /// For actual text modification use TextInputEvent. /// </summary> [VisibleToOtherModules("UnityEngine.UIElementsModule")] internal struct IMECompositionEvent : IEventProperties { // TODO most composition strings will be of limited size, like <100 chars, can we avoid a managed object then? // TODO maybe by splitting event into multiple if more string is really big? // TODO same problem in text input event public string compositionString; public DiscreteTime timestamp { get; set; } public EventSource eventSource { get; set; } public uint playerId { get; set; } // TODO probably it doesn't make any sense for splitscreen multiplayer public EventModifiers eventModifiers { get; set; } public override string ToString() { return $"IME '{compositionString}'"; } } }
UnityCsReference/Modules/InputForUI/Events/IMECompositionEvent.cs/0
{ "file_path": "UnityCsReference/Modules/InputForUI/Events/IMECompositionEvent.cs", "repo_id": "UnityCsReference", "token_count": 436 }
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.Bindings; namespace UnityEditor { [NativeHeader("Modules/JSONSerializeEditor/EditorJsonUtility.bindings.h")] public static class EditorJsonUtility { [FreeFunction("ToEditorJsonInternal")] private static extern string ToJsonInternal([NotNull] object obj, bool prettyPrint); public static string ToJson(object obj) { return ToJson(obj, false); } public static string ToJson(object obj, bool prettyPrint) { if (obj == null) return ""; return ToJsonInternal(obj, prettyPrint); } [FreeFunction("FromEditorJsonOverwriteInternal", ThrowsException = true)] private static extern void FromJsonOverwriteInternal([NotNull] string json, [NotNull] object objectToOverwrite); public static void FromJsonOverwrite(string json, object objectToOverwrite) { if (string.IsNullOrEmpty(json)) return; if (objectToOverwrite == null || (objectToOverwrite is UnityEngine.Object && !((UnityEngine.Object)objectToOverwrite))) throw new ArgumentNullException("objectToOverwrite"); FromJsonOverwriteInternal(json, objectToOverwrite); } } }
UnityCsReference/Modules/JSONSerializeEditor/EditorJsonUtility.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/JSONSerializeEditor/EditorJsonUtility.bindings.cs", "repo_id": "UnityCsReference", "token_count": 537 }
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.Events.Text; namespace UnityEditor.Licensing.UI.Events.Buttons; class OpenUnityHubButton : TemplateEventsButton { INativeApiWrapper m_NativeApiWrapper; Action m_CloseAction; public OpenUnityHubButton(Action closeAction, Action additionalClickAction, INativeApiWrapper nativeApiWrapper) : base(LicenseTrStrings.BtnOpenUnityHub, additionalClickAction) { m_NativeApiWrapper = nativeApiWrapper; m_CloseAction = closeAction; } protected override void Click() { m_CloseAction?.Invoke(); m_NativeApiWrapper.InvokeLicenseUpdateCallbacks(); m_NativeApiWrapper.OpenHubLicenseManagementWindow(); } }
UnityCsReference/Modules/Licensing/UI/Events/Buttons/OpenUnityHubButton.cs/0
{ "file_path": "UnityCsReference/Modules/Licensing/UI/Events/Buttons/OpenUnityHubButton.cs", "repo_id": "UnityCsReference", "token_count": 309 }
391
// Unity 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 LicenseExpiredWindowContents : TemplateLicenseEventWindowContents { LicenseExpiredNotification m_Notification; bool m_HasUiEntitlement; public LicenseExpiredWindowContents(bool hasUiEntitlement, LicenseExpiredNotification notification, IEventsButtonFactory eventsButtonFactory, ILicenseLogger licenseLogger) : base(eventsButtonFactory, licenseLogger) { m_HasUiEntitlement = hasUiEntitlement; m_Notification = notification; OnEnable(); } void OnEnable() { m_Description = LicenseExpiredHandler.BuildLicenseExpiredText(m_HasUiEntitlement, m_Notification); m_Buttons.Add(m_HasUiEntitlement ? EventsButtonType.OpenUnityHub : EventsButtonType.SaveAndQuit); m_LogTag = LicenseTrStrings.ExpiredWindowTitle; m_LogType = LogType.Error; CreateContents(); } }
UnityCsReference/Modules/Licensing/UI/Events/Windows/LicenseExpiredWindowContents.cs/0
{ "file_path": "UnityCsReference/Modules/Licensing/UI/Events/Windows/LicenseExpiredWindowContents.cs", "repo_id": "UnityCsReference", "token_count": 456 }
392
// 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.Licensing.UI.Helper; static class Utils { public static string GetOxfordCommaString(IList<string> words) { if (words == null || words.Count == 0) { return ""; } switch (words.Count) { case 1: return words[0]; case 2: return words[0] + " and " + words[1]; default: { var oxfordString = ""; for (var i = 0; i < words.Count - 1; i++) { oxfordString += words[i] + ", "; } oxfordString += "and " + words[^1]; return oxfordString; } } } public static string GetDescriptionMessageForProducts(IList<string> productNames, string singularPhrase, string pluralPhrase) { return string.Format(productNames.Count == 1 ? singularPhrase : pluralPhrase, GetOxfordCommaString(productNames)); } }
UnityCsReference/Modules/Licensing/UI/Helper/Utils.cs/0
{ "file_path": "UnityCsReference/Modules/Licensing/UI/Helper/Utils.cs", "repo_id": "UnityCsReference", "token_count": 566 }
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 UnityEngine; using UnityEngine.Bindings; using UnityEngine.Multiplayer.Internal; using UnityEngine.Scripting; using UnityEngine.UIElements; using UnityEditor.UIElements; using UnityEditor.Toolbars; using UnityEditor.Build; namespace UnityEditor.Multiplayer.Internal { [NativeHeader("Modules/Multiplayer/MultiplayerManager.h")] [StaticAccessor("GetMultiplayerManager()", StaticAccessorType.Dot)] internal static class EditorMultiplayerManager { public static extern bool enableMultiplayerRoles { get; set; } public static extern MultiplayerRoleFlags activeMultiplayerRoleMask { get; set; } public static extern MultiplayerRoleFlags GetMultiplayerRoleMaskForGameObject(GameObject gameObject); public static extern MultiplayerRoleFlags GetMultiplayerRoleMaskForComponent(Component component); public static extern Type[] GetStrippingTypesForRole(MultiplayerRole role); public static extern void SetMultiplayerRoleMaskForGameObject(GameObject gameObject, MultiplayerRoleFlags mask); public static extern void SetMultiplayerRoleMaskForComponent(Component component, MultiplayerRoleFlags mask); public static extern void SetStrippingTypesForRole(MultiplayerRole role, Type[] types); public static extern bool ShouldStripComponentType(MultiplayerRoleFlags activeRoleMask, Component component); public static extern Hash128 ComputeDependencyHash(); public static event Func<Rect, UnityEngine.Object[], bool> drawingMultiplayerRoleField; public static event Action<EditorToolbarDropdown> creatingMultiplayerRoleDropdown; public static event Action activeMultiplayerRoleChanged; public static event Action enableMultiplayerRolesChanged; public static event Action<NamedBuildTarget> drawingMultiplayerBuildOptions { add => BuildPlayerWindow.drawingMultiplayerBuildOptions += value; remove => BuildPlayerWindow.drawingMultiplayerBuildOptions -= value; } public static event Action<VisualElement> creatingPlayModeButtons { add => UnityEditor.Toolbars.PlayModeButtons.onPlayModeButtonsCreated += value; remove => UnityEditor.Toolbars.PlayModeButtons.onPlayModeButtonsCreated -= value; } [EditorHeaderItem(typeof(UnityEngine.Object))] private static bool MultiplayerRoleHeaderItem(Rect rect, UnityEngine.Object[] objects) { if (drawingMultiplayerRoleField == null) return false; return drawingMultiplayerRoleField(rect, objects); } public static void CreateMultiplayerRoleDropdown(EditorToolbarDropdown toolbarButton) { toolbarButton.style.display = DisplayStyle.None; creatingMultiplayerRoleDropdown?.Invoke(toolbarButton); } [RequiredByNativeCode(GenerateProxy = true)] private static void InvokeActiveMultiplayerRoleChangeEvent() { activeMultiplayerRoleChanged?.Invoke(); } [RequiredByNativeCode(GenerateProxy = true)] private static void InvokeEnableMultiplayerRolesChangeEvent() { enableMultiplayerRolesChanged?.Invoke(); } } }
UnityCsReference/Modules/MultiplayerEditor/Managed/EditorMultiplayerManager.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/MultiplayerEditor/Managed/EditorMultiplayerManager.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1151 }
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 System.Runtime.InteropServices; using UnityEngine; using UnityEngine.Bindings; using RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute; namespace UnityEditor.PackageManager { [Serializable] [RequiredByNativeCode] [StructLayout(LayoutKind.Sequential)] [NativeAsStruct] public class GitInfo { [SerializeField] [NativeName("hash")] private string m_Hash; [SerializeField] [NativeName("revision")] private string m_Revision; internal GitInfo() {} internal GitInfo(string hash, string revision) { m_Hash = hash; m_Revision = revision; } public string hash { get { return m_Hash; } } public string revision { get { return m_Revision; } } } }
UnityCsReference/Modules/PackageManager/Editor/Managed/GitInfo.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManager/Editor/Managed/GitInfo.cs", "repo_id": "UnityCsReference", "token_count": 381 }
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.Collections.ObjectModel; namespace UnityEditor.PackageManager { internal class ProgressUpdateEventArgs { public ReadOnlyCollection<PackageProgress> entries; internal ProgressUpdateEventArgs(PackageProgress[] progressUpdates) { entries = Array.AsReadOnly(progressUpdates); } } }
UnityCsReference/Modules/PackageManager/Editor/Managed/ProgressUpdateEventArgs.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManager/Editor/Managed/ProgressUpdateEventArgs.cs", "repo_id": "UnityCsReference", "token_count": 173 }
396
// Unity 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 { [Serializable] public sealed class RemoveRequest : Request { [SerializeField] private string m_PackageIdOrName; /// <summary> /// Id or name of the package to be removed /// </summary> public string PackageIdOrName { get { return m_PackageIdOrName; } } /// <summary> /// Constructor to support serialization /// </summary> private RemoveRequest() { } internal RemoveRequest(long operationId, NativeStatusCode initialStatus, string packageName) : base(operationId, initialStatus) { m_PackageIdOrName = packageName; } } }
UnityCsReference/Modules/PackageManager/Editor/Managed/Requests/RemoveRequest.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManager/Editor/Managed/Requests/RemoveRequest.cs", "repo_id": "UnityCsReference", "token_count": 422 }
397
// 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 { internal enum SignatureStatus { Unchecked, Valid, Invalid, Unsigned, Error } }
UnityCsReference/Modules/PackageManager/Editor/Managed/SignatureStatus.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManager/Editor/Managed/SignatureStatus.cs", "repo_id": "UnityCsReference", "token_count": 126 }
398
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; namespace UnityEditor.PackageManager.UI { internal interface IPackageActionMenu : IExtension { string text { get; set; } Texture2D icon { set; } string tooltip { get; set; } IPackageActionDropdownItem AddDropdownItem(); } }
UnityCsReference/Modules/PackageManagerUI/Editor/Extensions/Interfaces/IPackageActionMenu.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Extensions/Interfaces/IPackageActionMenu.cs", "repo_id": "UnityCsReference", "token_count": 158 }
399