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 Unity.IntegerTime; using UnityEngine.Bindings; namespace UnityEngine.InputForUI { [VisibleToOtherModules("UnityEngine.UIElementsModule")] internal struct CommandEvent : IEventProperties { public enum Type { Validate = 1, Execute = 2 } // based on Modules/IMGUI/EventCommandNames.cs // we really should avoid strings if possible public enum Command { Invalid = 0, Cut = 1, Copy = 2, Paste = 3, SelectAll = 4, DeselectAll = 5, InvertSelection = 6, Duplicate = 7, Rename = 8, Delete = 9, SoftDelete = 10, Find = 11, SelectChildren = 12, SelectPrefabRoot = 13, UndoRedoPerformed = 14, OnLostFocus = 15, NewKeyboardFocus = 16, ModifierKeysChanged = 17, EyeDropperUpdate = 18, EyeDropperClicked = 19, EyeDropperCancelled = 20, ColorPickerChanged = 21, FrameSelected = 22, FrameSelectedWithLock = 23, } public Type type; public Command command; public DiscreteTime timestamp { get; set; } public EventSource eventSource { get; set; } public uint playerId { get; set; } public EventModifiers eventModifiers { get; set; } public override string ToString() { return $"{type} {command}"; } } }
UnityCsReference/Modules/InputForUI/Events/CommandEvent.cs/0
{ "file_path": "UnityCsReference/Modules/InputForUI/Events/CommandEvent.cs", "repo_id": "UnityCsReference", "token_count": 834 }
399
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; namespace UnityEngine.InputForUI { /// <summary> /// Internal method to sanitize the event stream and ensure runtime behaviors. /// Is primarily concerns with event ordering and presence of redundant events. /// </summary> internal struct EventSanitizer { private IEventSanitizer[] _sanitizers; public void Reset() { _sanitizers = new IEventSanitizer[] { // Removed from release builds for the time being as it currently only logs issues rather // than ensuring any runtime behavior (https://jira.unity3d.com/browse/ISX-1388). }; foreach (var sanitizer in _sanitizers) sanitizer.Reset(); } public void BeforeProviderUpdate() { if (_sanitizers == null) Reset(); foreach (var sanitizer in _sanitizers) sanitizer.BeforeProviderUpdate(); } public void AfterProviderUpdate() { if (_sanitizers == null) Reset(); foreach (var sanitizer in _sanitizers) sanitizer.AfterProviderUpdate(); } public void Inspect(in Event ev) { if (_sanitizers == null) Reset(); foreach (var sanitizer in _sanitizers) sanitizer.Inspect(ev); } private interface IEventSanitizer { public void Reset(); public void BeforeProviderUpdate(); public void AfterProviderUpdate(); public void Inspect(in Event ev); } /// <summary> /// Click count sanitizer to ensure click count on button up is equal to click count on button down /// </summary> private struct ClickCountEventSanitizer : IEventSanitizer { private List<PointerEvent> _activeButtons; private int lastPushedIndex; public void Reset() { _activeButtons = new List<PointerEvent>(); lastPushedIndex = 0; } public void BeforeProviderUpdate() { } public void AfterProviderUpdate() { } public void Inspect(in Event ev) { if (ev.type != Event.Type.PointerEvent) return; var pointerEvent = ev.asPointerEvent; switch (pointerEvent.type) { case PointerEvent.Type.ButtonPressed: { lastPushedIndex = _activeButtons.Count; _activeButtons.Add(pointerEvent); break; } case PointerEvent.Type.ButtonReleased: { var releaseEvent = pointerEvent; for(var i = 0; i < _activeButtons.Count; ++i) { var pressEvent = _activeButtons[i]; if (pressEvent.eventSource != releaseEvent.eventSource || pressEvent.pointerIndex != releaseEvent.pointerIndex) continue; if (i == lastPushedIndex) { if (pressEvent.clickCount != releaseEvent.clickCount) { Debug.LogWarning( $"ButtonReleased click count doesn't match ButtonPressed click count, where '{pressEvent}' and '{releaseEvent}'"); } } else if (releaseEvent.clickCount != 1) { Debug.LogWarning( $"ButtonReleased for not the last pressed button should have click count == 1, but got '{releaseEvent}'"); } _activeButtons.RemoveAt(i); return; } Debug.LogWarning($"Can't find corresponding ButtonPressed for '{ev}'"); break; } default: break; } } } /// <summary> /// DefaultEventSystem sanitizer to make sure data comes in to the DefaultEventSystem in the form and order /// that it is expected to. /// </summary> private class DefaultEventSystemSanitizer : IEventSanitizer { private int m_MouseEventCount; private int m_PenOrTouchEventCount; public void Reset() { } public void BeforeProviderUpdate() { m_MouseEventCount = 0; m_PenOrTouchEventCount = 0; } public void AfterProviderUpdate() { if (m_MouseEventCount > 0 && m_PenOrTouchEventCount > 0) { Debug.LogError("PointerEvents of source Mouse and [Pen or Touch] received in the same update. This is likely an error, and Mouse events should be discarded."); } } public void Inspect(in Event ev) { if (ev.type == Event.Type.PointerEvent) { var pointerEvent = ev.asPointerEvent; if (pointerEvent.type == PointerEvent.Type.ButtonPressed && pointerEvent.button == PointerEvent.Button.None) { Debug.LogError("PointerEvent of type ButtonPressed must have button property set to a value other than None."); } if (pointerEvent.type == PointerEvent.Type.ButtonReleased && pointerEvent.button == PointerEvent.Button.None) { Debug.LogError("PointerEvent of type ButtonReleased must have button property set to a value other than None."); } if (pointerEvent.eventSource == EventSource.Mouse) { m_MouseEventCount++; if (!pointerEvent.isPrimaryPointer) { Debug.LogError("PointerEvent of source Mouse is expected to have isPrimaryPointer set to true."); } if (pointerEvent.pointerIndex != 0) { Debug.LogError("PointerEvent of source Mouse is expected to have pointerIndex set to 0."); } } else if (pointerEvent.eventSource == EventSource.Touch) { m_PenOrTouchEventCount++; if (pointerEvent.button != PointerEvent.Button.None && pointerEvent.button != PointerEvent.Button.FingerInTouch) { Debug.LogError("PointerEvent of source Touch is expected to have button set to None or FingerInTouch."); } } else if (pointerEvent.eventSource == EventSource.Pen) { m_PenOrTouchEventCount++; if (pointerEvent.button != PointerEvent.Button.None && pointerEvent.button != PointerEvent.Button.PenTipInTouch && pointerEvent.button != PointerEvent.Button.PenBarrelButton && pointerEvent.button != PointerEvent.Button.PenEraserInTouch) { Debug.LogError("PointerEvent of source Pen is expected to have button set to None, PenTipInTouch, PenBarrelButton, or PenEraserInTouch."); } } } } } } }
UnityCsReference/Modules/InputForUI/Sanitizer/EventSanitizer.cs/0
{ "file_path": "UnityCsReference/Modules/InputForUI/Sanitizer/EventSanitizer.cs", "repo_id": "UnityCsReference", "token_count": 4489 }
400
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine.UIElements; namespace UnityEditor.Licensing.UI.Events.Buttons; class EventsButtonFactory : IEventsButtonFactory { INativeApiWrapper m_NativeApiWrapper; Action m_CloseModalAction; public EventsButtonFactory(INativeApiWrapper nativeApiWrapper, Action closeModalAction) { m_CloseModalAction = closeModalAction; m_NativeApiWrapper = nativeApiWrapper; } public VisualElement Create(EventsButtonType buttonType, Action additionalCustomClickAction) { var visualElement = buttonType switch { EventsButtonType.Ok => new OkButton(m_CloseModalAction, additionalCustomClickAction, m_NativeApiWrapper), EventsButtonType.ManageLicense => new ManageLicenseButton(m_CloseModalAction, additionalCustomClickAction, m_NativeApiWrapper), EventsButtonType.SaveAndQuit => BuildSaveAndCloseBundle(additionalCustomClickAction), EventsButtonType.UpdateLicense => new UpdateLicenseButton(m_CloseModalAction, additionalCustomClickAction, m_NativeApiWrapper), EventsButtonType.OpenUnityHub => new OpenUnityHubButton(m_CloseModalAction, additionalCustomClickAction, m_NativeApiWrapper), _ => throw new ArgumentException($"Unknown button type: {buttonType}") }; return visualElement; } VisualElement BuildSaveAndCloseBundle(Action additionalCustomAction) { VisualElement visualElement = new VisualElement(); visualElement.Add(new CloseProjectButton(additionalCustomAction, m_CloseModalAction, m_NativeApiWrapper)); if (m_NativeApiWrapper.HasUnsavedScenes()) { visualElement.Add(new SaveAndQuitButton(m_CloseModalAction, additionalCustomAction, m_NativeApiWrapper)); } return visualElement; } }
UnityCsReference/Modules/Licensing/UI/Events/Buttons/EventsButtonFactory.cs/0
{ "file_path": "UnityCsReference/Modules/Licensing/UI/Events/Buttons/EventsButtonFactory.cs", "repo_id": "UnityCsReference", "token_count": 705 }
401
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEditor.Licensing.UI.Data.Events.Base; using UnityEditor.Licensing.UI.Helper; using UnityEngine; namespace UnityEditor.Licensing.UI.Events; class LicenseNotificationDispatcher : INotificationDispatcher { ILicenseNotificationHandlerFactory m_NotificationHandlerFactory; ILicenseLogger m_LicenseLogger; readonly INativeApiWrapper m_NativeApiWrapper; public LicenseNotificationDispatcher(ILicenseNotificationHandlerFactory notificationHandlerFactory, ILicenseLogger licenseLogger, INativeApiWrapper nativeApiWrapper) { m_NotificationHandlerFactory = notificationHandlerFactory; m_LicenseLogger = licenseLogger; m_NativeApiWrapper = nativeApiWrapper; } public void Dispatch(string jsonNotification) { var notificationBase = m_NativeApiWrapper.CreateObjectFromJson<Notification>(jsonNotification); if (notificationBase.messageType != "Notification") { m_LicenseLogger.LogError($"Unintended message type: \"{notificationBase.messageType}\" is received!"); return; } try { var notificationHandler = m_NotificationHandlerFactory.GetHandler(notificationBase.NotificationTypeAsEnum, jsonNotification); notificationHandler.Handle(m_NativeApiWrapper.IsHumanControllingUs()); } catch (ArgumentException) { // log that received an unknown notification m_LicenseLogger.DebugLogNoStackTrace($"There is no handler for: " + $"notificationType: \"{notificationBase.notificationType}\", " + $"title: \"{notificationBase.title}\", " + $"message: \"{notificationBase.message}\", " + $"sentDate: \"{notificationBase.sentDate}\"" ); } } }
UnityCsReference/Modules/Licensing/UI/Events/LicenseNotificationDispatcher.cs/0
{ "file_path": "UnityCsReference/Modules/Licensing/UI/Events/LicenseNotificationDispatcher.cs", "repo_id": "UnityCsReference", "token_count": 767 }
402
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor.Licensing.UI.Data.Events.Base; using UnityEditor.Licensing.UI.Helper; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.Licensing.UI.Events.Windows; abstract class TemplateLicenseEventWindow : EditorWindow { protected static INativeApiWrapper s_NativeApiWrapper; protected static ILicenseLogger s_LicenseLogger; protected static Notification s_Notification; protected static TemplateLicenseEventWindowContents s_Root; // UX designer fixes the width to preference const float k_ContentWidth = 334f; protected static void ShowWindow<T>(string txtWindowTitle, bool enableWindowTrapping = false) where T : EditorWindow { // trap user until user clicks on a button and not 'x' in the title bar // trapping is only required if there is no more ui entitlement while (Render<T>(txtWindowTitle) && !s_NativeApiWrapper.HasUiEntitlement()) { if (!enableWindowTrapping) { break; } } } static bool Render<T>(string txtWindowTitle) where T : EditorWindow { var window = CreateInstance<T>(); window.titleContent = new GUIContent(txtWindowTitle); window.ShowModal(); // returns true: if and only if user has clicked on 'x' icon in titlebar return s_Root.UserClosedModalFromTitleBar; } public void OnEnable() { rootVisualElement.RegisterCallback<GeometryChangedEvent>(GeometryChangedCallback); } void GeometryChangedCallback(GeometryChangedEvent evt) { // set the size of the window according to the content description and elements var mainContainer = rootVisualElement.Q<VisualElement>("MainContainer"); if (mainContainer == null) { return; } minSize = new Vector2( k_ContentWidth, mainContainer.resolvedStyle.height + 1 // for some reason this 1 pixel fixes the resizing glitch ); maxSize = minSize; } }
UnityCsReference/Modules/Licensing/UI/Events/Windows/TemplateLicenseEventWindow.cs/0
{ "file_path": "UnityCsReference/Modules/Licensing/UI/Events/Windows/TemplateLicenseEventWindow.cs", "repo_id": "UnityCsReference", "token_count": 800 }
403
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("UnityEditor.Modules.Multiplayer.Tests.MultiplayerRoles")] [assembly: InternalsVisibleTo("UnityEditor.Modules.Multiplayer.Tests.MultiplayerRoles.Performance")] [assembly: InternalsVisibleTo("UnityEditor.CoreModule")] [assembly: InternalsVisibleTo("UnityEditor.MultiplayerModule")] [assembly: InternalsVisibleTo("Unity.DedicatedServer.MultiplayerRoles")] [assembly: InternalsVisibleTo("Unity.DedicatedServer.MultiplayerRoles.Editor")]
UnityCsReference/Modules/Multiplayer/Managed/AssemblyInfo.cs/0
{ "file_path": "UnityCsReference/Modules/Multiplayer/Managed/AssemblyInfo.cs", "repo_id": "UnityCsReference", "token_count": 197 }
404
// 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 EntitlementLicensingModel { None, Public, AssetStore, Enterprise, } }
UnityCsReference/Modules/PackageManager/Editor/Managed/EntitlementLicensingModel.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManager/Editor/Managed/EntitlementLicensingModel.cs", "repo_id": "UnityCsReference", "token_count": 120 }
405
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Runtime.InteropServices; using UnityEngine; using UnityEngine.Bindings; using UnityEngine.Scripting; namespace UnityEditor.PackageManager { [StructLayout(LayoutKind.Sequential)] [RequiredByNativeCode] [NativeAsStruct] internal class PackageProgress { [NativeName("name")] private string m_Name; [NativeName("version")] private string m_Version; [NativeName("state")] private ProgressState m_State; [NativeName("currentBytes")] private ulong m_CurrentBytes; [NativeName("totalBytes")] private ulong m_TotalBytes; public string version { get { return m_Version; } } public string name { get { return m_Name; } } public ProgressState state { get { return m_State; } } public DownloadProgress? download { get { if (m_State == ProgressState.Downloading || m_TotalBytes > 0) { return new DownloadProgress(m_CurrentBytes, m_TotalBytes); } return null; } } } }
UnityCsReference/Modules/PackageManager/Editor/Managed/PackageProgress.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManager/Editor/Managed/PackageProgress.cs", "repo_id": "UnityCsReference", "token_count": 556 }
406
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; namespace UnityEditor.PackageManager.Requests { [Serializable] internal sealed partial class GetRegistriesRequest : Request<RegistryInfo[]> { /// <summary> /// Constructor to support serialization /// </summary> private GetRegistriesRequest() : base() { } internal GetRegistriesRequest(long operationId, NativeStatusCode initialStatus) : base(operationId, initialStatus) { } protected override RegistryInfo[] GetResult() { return GetOperationData(Id); } } }
UnityCsReference/Modules/PackageManager/Editor/Managed/Requests/GetRegistriesRequest.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManager/Editor/Managed/Requests/GetRegistriesRequest.cs", "repo_id": "UnityCsReference", "token_count": 305 }
407
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEditor.PackageManager.UI { internal interface IExtension { int priority { get; set; } bool visible { get; set; } bool enabled { get; set; } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Extensions/Interfaces/IExtension.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Extensions/Interfaces/IExtension.cs", "repo_id": "UnityCsReference", "token_count": 126 }
408
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; namespace UnityEditor.PackageManager.UI.Internal { [Serializable] class ServiceGroupingsWrapper { public string name; public int index; public string id; public List<string> packages; } }
UnityCsReference/Modules/PackageManagerUI/Editor/External/ServicesTab/ServiceGroupingsWrapper.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/External/ServicesTab/ServiceGroupingsWrapper.cs", "repo_id": "UnityCsReference", "token_count": 154 }
409
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Linq; using System.Text; using UnityEngine; namespace UnityEditor.PackageManager.UI.Internal { [Serializable] internal class AssetStoreListOperation : IOperation { private const int k_QueryLimit = 500; private static readonly string k_UserNotLoggedInErrorMessage = L10n.Tr("User not logged in."); public string packageUniqueId => string.Empty; public long productId => 0; [SerializeField] protected long m_Timestamp; public long timestamp => m_Timestamp; public long lastSuccessTimestamp => 0; public bool isOfflineMode => false; [SerializeField] protected bool m_IsInProgress; public virtual bool isInProgress => m_IsInProgress; public bool isProgressVisible => false; public bool isInPause => false; public RefreshOptions refreshOptions => RefreshOptions.Purchased; public bool isProgressTrackable => false; public float progressPercentage => 0; public event Action<IOperation, UIError> onOperationError = delegate {}; public virtual event Action<IOperation> onOperationSuccess = delegate {}; public virtual event Action<IOperation> onOperationFinalized = delegate {}; public event Action<IOperation> onOperationProgress = delegate {}; [SerializeField] private PurchasesQueryArgs m_OriginalQueryArgs; [SerializeField] private PurchasesQueryArgs m_AdjustedQueryArgs; [SerializeField] private AssetStorePurchases m_Result; public virtual AssetStorePurchases result => m_Result; [NonSerialized] private IUnityConnectProxy m_UnityConnect; [NonSerialized] private IAssetStoreRestAPI m_AssetStoreRestAPI; [NonSerialized] private IAssetStoreCache m_AssetStoreCache; public void ResolveDependencies(IUnityConnectProxy unityConnect, IAssetStoreRestAPI assetStoreRestAPI, IAssetStoreCache assetStoreCache) { m_UnityConnect = unityConnect; m_AssetStoreRestAPI = assetStoreRestAPI; m_AssetStoreCache = assetStoreCache; } private AssetStoreListOperation() { } public AssetStoreListOperation(IUnityConnectProxy unityConnect, IAssetStoreRestAPI assetStoreRestAPI, IAssetStoreCache assetStoreCache) { ResolveDependencies(unityConnect, assetStoreRestAPI, assetStoreCache); } public virtual void Start(PurchasesQueryArgs queryArgs) { SetQueryArgs(queryArgs); m_IsInProgress = true; m_Timestamp = DateTime.Now.Ticks; if (!m_UnityConnect.isUserLoggedIn) { OnOperationError(new UIError(UIErrorCode.AssetStoreOperationError, k_UserNotLoggedInErrorMessage)); return; } m_Result = new AssetStorePurchases(m_OriginalQueryArgs); if (m_OriginalQueryArgs.status is PageFilters.Status.Downloaded or PageFilters.Status.Imported or PageFilters.Status.UpdateAvailable && !m_AdjustedQueryArgs.productIds.Any()) { m_Result.total = 0; onOperationSuccess?.Invoke(this); FinalizedOperation(); return; } // We need to keep a local version of the current timestamp to make sure the callback timestamp is still the original one. var localTimestamp = m_Timestamp; m_AssetStoreRestAPI.GetPurchases(m_AdjustedQueryArgs, purchases => GetPurchasesCallback(purchases, localTimestamp), OnOperationError); } public virtual void Stop() { m_Timestamp = DateTime.Now.Ticks; m_AssetStoreRestAPI.AbortGetPurchases(m_AdjustedQueryArgs); FinalizedOperation(); } private void SetQueryArgs(PurchasesQueryArgs queryArgs) { m_OriginalQueryArgs = queryArgs; // The GetPurchases API has a limit of maximum 1000 items (to avoid performance issues) // therefore we do some adjustments to the original query args enforce that limit and split // the original query to multiple batches. We make a clone before when adjusting is needed m_AdjustedQueryArgs = m_OriginalQueryArgs.Clone(); m_AdjustedQueryArgs.limit = Math.Min(m_OriginalQueryArgs.limit, k_QueryLimit); switch (m_OriginalQueryArgs.status) { case PageFilters.Status.Downloaded: m_AdjustedQueryArgs.status = PageFilters.Status.None; m_AdjustedQueryArgs.productIds = m_AssetStoreCache.localInfos.Select(info => info.productId).ToList(); break; case PageFilters.Status.Imported: m_AdjustedQueryArgs.status = PageFilters.Status.None; m_AdjustedQueryArgs.productIds = m_AssetStoreCache.importedPackages.Select(p => p.productId).ToList(); break; case PageFilters.Status.UpdateAvailable: m_AdjustedQueryArgs.status = PageFilters.Status.None; var productIdsToCheck = m_AssetStoreCache.localInfos.Select(i => i.productId) .Concat(m_AssetStoreCache.importedPackages.Select(i => i.productId)).ToHashSet(); m_AdjustedQueryArgs.productIds = productIdsToCheck.Where(id => { var updateInfo = m_AssetStoreCache.GetUpdateInfo(id); if (updateInfo == null) return false; var localInfo = m_AssetStoreCache.GetLocalInfo(id); if (localInfo != null && localInfo.uploadId != updateInfo.recommendedUploadId) return true; var importedPackage = m_AssetStoreCache.GetImportedPackage(id); return importedPackage != null && importedPackage.uploadId != updateInfo.recommendedUploadId; }).ToList(); break; } } private void GetPurchasesCallback(AssetStorePurchases purchases, long operationTimestamp) { if (operationTimestamp != m_Timestamp) return; if (!m_UnityConnect.isUserLoggedIn) { OnOperationError(new UIError(UIErrorCode.AssetStoreOperationError, k_UserNotLoggedInErrorMessage)); return; } m_Result.AppendPurchases(purchases); if (m_OriginalQueryArgs.limit > k_QueryLimit && m_IsInProgress) { var numAssetsToFetch = (int)m_Result.total - m_OriginalQueryArgs.startIndex; var numAlreadyFetched = m_Result.list.Count; var newLimit = Math.Min(k_QueryLimit, Math.Min(numAssetsToFetch, m_OriginalQueryArgs.limit) - numAlreadyFetched); if (newLimit > 0) { m_AdjustedQueryArgs.startIndex = m_OriginalQueryArgs.startIndex + m_Result.list.Count; m_AdjustedQueryArgs.limit = newLimit; m_AssetStoreRestAPI.GetPurchases(m_AdjustedQueryArgs, purchases => GetPurchasesCallback(purchases, operationTimestamp), OnOperationError); return; } } onOperationSuccess?.Invoke(this); FinalizedOperation(); } private void OnOperationError(UIError error) { onOperationError?.Invoke(this, error); FinalizedOperation(); PackageManagerOperationErrorAnalytics.SendEvent(GetType().Name, error); } private void FinalizedOperation() { m_IsInProgress = false; onOperationFinalized?.Invoke(this); onOperationError = delegate {}; onOperationFinalized = delegate {}; onOperationSuccess = delegate {}; onOperationProgress = delegate {}; } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/AssetStore/AssetStoreListOperation.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/AssetStore/AssetStoreListOperation.cs", "repo_id": "UnityCsReference", "token_count": 3645 }
410
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEditor.Scripting.ScriptCompilation; using UnityEditor.Experimental.Licensing; namespace UnityEditor.PackageManager.UI.Internal { [Serializable] internal abstract class BasePackageVersion : IPackageVersion, ISerializationCallbackReceiver { [SerializeField] protected string m_Name; public virtual string name => m_Name ?? string.Empty; [SerializeField] protected string m_DisplayName; public virtual string displayName => m_DisplayName; [SerializeField] protected string m_Description; public string description => m_Description ?? string.Empty; [SerializeField] protected string m_VersionString; protected SemVersion? m_Version; public virtual SemVersion? version => m_Version; public virtual string versionInManifest => null; public virtual bool isInvalidSemVerInManifest => false; [SerializeField] protected long m_PublishedDateTicks; public DateTime? publishedDate => m_PublishedDateTicks == 0 ? null : new DateTime(m_PublishedDateTicks, DateTimeKind.Utc); [SerializeField] protected string m_PublishNotes; public string localReleaseNotes => m_PublishNotes; public virtual DependencyInfo[] dependencies => null; public virtual DependencyInfo[] resolvedDependencies => null; public virtual EntitlementsInfo entitlements => null; public virtual IEnumerable<Asset> importedAssets => null; [NonSerialized] private IPackage m_Package; public UI.IPackage package => m_Package; IPackage IPackageVersion.package { get => m_Package; set { m_Package = value; } } [SerializeField] protected PackageTag m_Tag; public virtual bool HasTag(PackageTag tag) { return (m_Tag & tag) != 0; } // Analytics tags are different from the package tags we use. // We need them to identify different situations that we don't necessarily have tags for public string GetAnalyticsTags() { var tags = new List<string>(); if (m_Tag != PackageTag.None) tags.Add(m_Tag.ToString()); if (m_Package.isDeprecated) tags.Add("PackageDeprecation"); return string.Join(", ", tags); } public virtual RegistryType availableRegistry => RegistryType.None; // Currently we don't consider Upm Packages with EntitlementLicensingModel.AssetStore as having entitlements // and it is only used right now to check if a package is from Asset Store. This is also to be consistent with // other Asset Store packages (as in, if Upm Packages on Asset Store are considered with entitlements, then every // package from Asset Store should be considered to have entitlements). public bool hasEntitlements => entitlements != null && (entitlements.licensingModel == EntitlementLicensingModel.Enterprise || entitlements.status == EntitlementStatus.NotGranted || entitlements.status == EntitlementStatus.Granted); public virtual bool hasEntitlementsError => false; public virtual IEnumerable<UIError> errors => Enumerable.Empty<UIError>(); public virtual IEnumerable<PackageSizeInfo> sizes => Enumerable.Empty<PackageSizeInfo>(); public virtual IEnumerable<SemVersion> supportedVersions => Enumerable.Empty<SemVersion>(); public virtual SemVersion? supportedVersion => null; public virtual string deprecationMessage => null; public abstract string uniqueId { get; } public abstract string packageId { get; } public abstract string category { get; } public abstract string author { get; } public abstract bool isInstalled { get; } public abstract bool isFullyFetched { get; } public abstract bool isDirectDependency { get; } public abstract string localPath { get; } public abstract string versionString { get; } public abstract long uploadId { get; } public bool IsDifferentVersionThanRequested => !string.IsNullOrEmpty(versionInManifest) && !HasTag(PackageTag.Git | PackageTag.Local | PackageTag.Custom) && versionInManifest != versionString; public bool IsRequestedButOverriddenVersion => !string.IsNullOrEmpty(versionString) && !isInstalled && versionString == m_Package?.versions.primary.versionInManifest; public virtual string GetDescriptor(bool isFirstLetterCapitalized = false) { return isFirstLetterCapitalized ? L10n.Tr("Package") : L10n.Tr("package"); } public virtual void OnBeforeSerialize() { // Do nothing } public virtual void OnAfterDeserialize() { SemVersionParser.TryParse(m_VersionString, out m_Version); } public virtual bool MatchesSearchText(string searchText) { if (string.IsNullOrEmpty(searchText)) return true; if (name.IndexOf(searchText, StringComparison.CurrentCultureIgnoreCase) >= 0) return true; if (!string.IsNullOrEmpty(displayName) && displayName.IndexOf(searchText, StringComparison.CurrentCultureIgnoreCase) >= 0) return true; var prerelease = searchText.StartsWith("-") ? searchText.Substring(1) : searchText; if (version != null && ((SemVersion)version).Prerelease.IndexOf(prerelease, StringComparison.CurrentCultureIgnoreCase) >= 0) return true; // searching for pre-release if search text matches with search term 'pre', case insensitive const string prereleaseSearchText = "Pre"; if (HasTag(PackageTag.PreRelease) && prereleaseSearchText.IndexOf(searchText, StringComparison.CurrentCultureIgnoreCase) >= 0) return true; // searching for experimental if search text matches with search term 'experimental', case insensitive const string experimentalSearchText = "Experimental"; if (HasTag(PackageTag.Experimental) && experimentalSearchText.IndexOf(searchText, StringComparison.CurrentCultureIgnoreCase) >= 0) return true; if (HasTag(PackageTag.Release) && PackageTag.Release.ToString().IndexOf(searchText, StringComparison.CurrentCultureIgnoreCase) >= 0) return true; if (version?.StripTag().StartsWith(searchText, StringComparison.CurrentCultureIgnoreCase) == true) return true; if (!string.IsNullOrEmpty(category)) { var words = searchText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); var categories = category.Split('/'); if (words.All(word => word.Length >= 2 && categories.Any(category => category.StartsWith(word, StringComparison.CurrentCultureIgnoreCase)))) return true; } return false; } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Common/BasePackageVersion.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Common/BasePackageVersion.cs", "repo_id": "UnityCsReference", "token_count": 2840 }
411
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEditor.PackageManager.UI.Internal { internal enum UIErrorCode { // we must keep this Core Error Codes section in sync with Core team's ErrorCode.cs // in order for error code casting to work - these values must also precede any new // error codes we add specifically for PackageManagerUI #region Original Core Error Codes UpmError_Unknown = ErrorCode.Unknown, UpmError_NotFound = ErrorCode.NotFound, UpmError_Forbidden = ErrorCode.Forbidden, UpmError_InvalidParameter = ErrorCode.InvalidParameter, UpmError_Conflict = ErrorCode.Conflict, #endregion // These are additional UPM errors that we need but are not returned // by the UPM server. These values might override the original code. UpmError_ServerNotRunning = 100, UpmError_InvalidSignature, UpmError_UnsignedUnityPackage, UpmError_NotSignedIn, UpmError_NotAcquired, AssetStoreAuthorizationError = 500, AssetStoreClientError, AssetStoreRestApiError, AssetStoreOperationError, AssetStorePackageError, UserNotSignedIn = 600 } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Common/UIErrorCode.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Common/UIErrorCode.cs", "repo_id": "UnityCsReference", "token_count": 496 }
412
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEditor.PackageManager.UI.Internal; internal class DownloadNewAction : DownloadActionBase { public DownloadNewAction(IPackageOperationDispatcher operationDispatcher, IAssetStoreDownloadManager assetStoreDownloadManager, IUnityConnectProxy unityConnect, IApplicationProxy application) : base(operationDispatcher, assetStoreDownloadManager, unityConnect, application) { } protected override string analyticEventName => "startDownloadNew"; public override bool isRecommended => true; public override Icon icon => Icon.Download; public override bool IsVisible(IPackageVersion version) { return base.IsVisible(version) && version?.package.versions.importAvailable == null; } public override string GetTooltip(IPackageVersion version, bool isInProgress) { if (isInProgress) return L10n.Tr("The download request has been sent. Please wait for the download to start."); return string.Format(L10n.Tr("Click to download this {0} for later use."), version.GetDescriptor()); } public override string GetText(IPackageVersion version, bool isInProgress) { return L10n.Tr("Download"); } public override bool IsInProgress(IPackageVersion version) { return base.IsInProgress(version) && version?.package.versions.importAvailable == null; } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/Actions/DownloadNewAction.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/Actions/DownloadNewAction.cs", "repo_id": "UnityCsReference", "token_count": 490 }
413
// 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.PackageManager.UI.Internal; internal class UnlockAction : PackageAction { private readonly IPageManager m_PageManager; public UnlockAction(IPageManager pageManager) { m_PageManager = pageManager; } protected override bool TriggerActionImplementation(IList<IPackageVersion> versions) { m_PageManager.activePage.SetPackagesUserUnlockedState(versions.Select(v => v.package.uniqueId), true); PackageManagerWindowAnalytics.SendEvent("unlock", packageIds: versions.Select(v => v.package.uniqueId)); return true; } protected override bool TriggerActionImplementation(IPackageVersion version) { m_PageManager.activePage.SetPackagesUserUnlockedState(new string[1] { version.package.uniqueId }, true); PackageManagerWindowAnalytics.SendEvent("unlock", version.package.uniqueId); return true; } public override bool IsVisible(IPackageVersion version) => m_PageManager.activePage.visualStates.Get(version?.package?.uniqueId)?.isLocked == true; public override string GetTooltip(IPackageVersion version, bool isInProgress) { return L10n.Tr("Unlock to make changes"); } public override string GetText(IPackageVersion version, bool isInProgress) { return L10n.Tr("Unlock"); } public override bool IsInProgress(IPackageVersion version) => false; }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/Actions/UnlockAction.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/Actions/UnlockAction.cs", "repo_id": "UnityCsReference", "token_count": 536 }
414
// 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.PackageManager.UI.Internal { [Flags] internal enum PackageTag : uint { None = 0, InDevelopment = Custom, // Used by UPM develop package InstalledFromPath = Local | Git | Custom, Custom = 1 << 0, Local = 1 << 1, Git = 1 << 2, BuiltIn = 1 << 3, Feature = 1 << 4, Placeholder = 1 << 5, SpecialInstall = 1 << 6, VersionLocked = 1 << 7, LegacyFormat = 1 << 10, // legacy .unitypackage format UpmFormat = 1 << 11, Unity = 1 << 15, Disabled = 1 << 20, Published = 1 << 21, Deprecated = 1 << 22, Release = 1 << 23, Experimental = 1 << 24, PreRelease = 1 << 25, ReleaseCandidate = 1 << 26 } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/PackageTag.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/PackageTag.cs", "repo_id": "UnityCsReference", "token_count": 616 }
415
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Linq; using UnityEngine; namespace UnityEditor.PackageManager.UI.Internal { // A ScopedRegistryPage is basically a special case MyRegistriesPage, where only packages from a specified registry is shown // hence we are using MyRegistriesPage as the parent class and reuse some implementations there. [Serializable] internal class ScopedRegistryPage : MyRegistriesPage { public const string k_IdPrefix = "ScopedRegistry"; public static string GetIdFromRegistry(RegistryInfo registryInfo) => $"{k_IdPrefix}/{registryInfo.id}"; [SerializeField] private RegistryInfo m_RegistryInfo; public RegistryInfo registry => m_RegistryInfo; public override string id => GetIdFromRegistry(m_RegistryInfo); public override string displayName => m_RegistryInfo.name; [NonSerialized] private IUpmCache m_UpmCache; public void ResolveDependencies(IPackageDatabase packageDatabase, IUpmCache upmCache) { ResolveDependencies(packageDatabase); m_UpmCache = upmCache; } public ScopedRegistryPage(IPackageDatabase packageDatabase, IUpmCache upmCache, RegistryInfo registryInfo) : base(packageDatabase) { ResolveDependencies(packageDatabase, upmCache); m_RegistryInfo = registryInfo; } public void UpdateRegistry(RegistryInfo registryInfo) { if (new UpmRegistryClient.RegistryInfoComparer().Equals(m_RegistryInfo, registryInfo)) return; m_RegistryInfo = registryInfo; RebuildVisualStatesAndUpdateVisibilityWithSearchText(); } public override bool ShouldInclude(IPackage package) { return base.ShouldInclude(package) && package.versions.Any(v => { var packageInfo = m_UpmCache.GetBestMatchPackageInfo(v.name, v.isInstalled); return new UpmRegistryClient.RegistryInfoComparer().Equals(m_RegistryInfo, packageInfo.registry); }); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Pages/PageTypes/ScopedRegistryPage.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Pages/PageTypes/ScopedRegistryPage.cs", "repo_id": "UnityCsReference", "token_count": 897 }
416
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Diagnostics.CodeAnalysis; namespace UnityEditor.PackageManager.UI.Internal { internal interface IDateTimeProxy : IService { DateTime utcNow { get; } } [ExcludeFromCodeCoverage] internal class DateTimeProxy : BaseService<IDateTimeProxy>, IDateTimeProxy { public DateTime utcNow => DateTime.UtcNow; } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Proxies/DateTimeProxy.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Proxies/DateTimeProxy.cs", "repo_id": "UnityCsReference", "token_count": 184 }
417
// Unity 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.PackageManager.Requests; using UnityEngine; namespace UnityEditor.PackageManager.UI.Internal { internal interface IUpmClient : IService { event Action<IEnumerable<(string packageIdOrName, PackageProgress progress)>> onPackagesProgressChange; event Action<string, UIError> onPackageOperationError; event Action<IOperation> onListOperation; event Action<IOperation> onSearchAllOperation; event Action<IOperation> onAddOperation; bool isAddOrRemoveInProgress { get; } IEnumerable<string> packageIdsOrNamesInstalling { get; } bool IsAnyExperimentalPackagesInUse(); bool IsRemoveInProgress(string packageName); bool IsAddInProgress(string packageId); void AddById(string packageId); bool AddByPath(string path, out string tempPackageId); void AddByUrl(string url); void AddByIds(IEnumerable<string> versionIds); void RemoveByNames(IEnumerable<string> packagesNames); void AddAndResetDependencies(string packageId, IEnumerable<string> dependencyPackagesNames); void ResetDependencies(string packageId, IEnumerable<string> dependencyPackagesNames); void List(bool offlineMode = false); void RemoveByName(string packageName); void RemoveEmbeddedByName(string packageName); void SearchAll(bool offlineMode = false); void ExtraFetchPackageInfo(string packageIdOrName, long productId = 0, Action<PackageInfo> successCallback = null, Action<UIError> errorCallback = null, Action doneCallback = null); void ClearCache(); void Resolve(); RegistryType GetAvailableRegistryType(PackageInfo packageInfo); bool IsUnityPackage(PackageInfo packageInfo); } [Serializable] internal class UpmClient : BaseService<IUpmClient>, IUpmClient, ISerializationCallbackReceiver { private static readonly string[] k_UnityRegistryUrlsHosts = { ".unity.com", ".unity3d.com" }; public event Action<IEnumerable<(string packageIdOrName, PackageProgress progress)>> onPackagesProgressChange = delegate { }; public event Action<string, UIError> onPackageOperationError = delegate { }; public event Action<IOperation> onListOperation = delegate {}; public event Action<IOperation> onSearchAllOperation = delegate {}; public event Action<IOperation> onAddOperation = delegate {}; [SerializeField] private UpmSearchOperation m_SearchOperation; private UpmSearchOperation searchOperation => CreateOperation(ref m_SearchOperation); [SerializeField] private UpmSearchOperation m_SearchOfflineOperation; private UpmSearchOperation searchOfflineOperation => CreateOperation(ref m_SearchOfflineOperation); [SerializeField] private UpmListOperation m_ListOperation; private UpmListOperation listOperation => CreateOperation(ref m_ListOperation); [SerializeField] private UpmListOperation m_ListOfflineOperation; private UpmListOperation listOfflineOperation => CreateOperation(ref m_ListOfflineOperation); [SerializeField] private UpmAddOperation m_AddOperation; private UpmAddOperation addOperation => CreateOperation(ref m_AddOperation); [SerializeField] private UpmAddAndRemoveOperation m_AddAndRemoveOperation; private UpmAddAndRemoveOperation addAndRemoveOperation => CreateOperation(ref m_AddAndRemoveOperation); [SerializeField] private UpmRemoveOperation m_RemoveOperation; private UpmRemoveOperation removeOperation => CreateOperation(ref m_RemoveOperation); [SerializeField] private UpmSearchOperation[] m_SerializedInProgressExtraFetchOperations = Array.Empty<UpmSearchOperation>(); private readonly Dictionary<string, UpmSearchOperation> m_ExtraFetchOperations = new Dictionary<string, UpmSearchOperation>(); [SerializeField] private string[] m_SerializedRegistryUrlsKeys; [SerializeField] private RegistryType[] m_SerializedRegistryUrlsValues; private Dictionary<string, RegistryType> m_RegistryUrls = new(); private readonly IUpmCache m_UpmCache; private readonly IFetchStatusTracker m_FetchStatusTracker; private readonly IIOProxy m_IOProxy; private readonly IClientProxy m_ClientProxy; private readonly IApplicationProxy m_Application; public UpmClient(IUpmCache upmCache, IFetchStatusTracker fetchStatusTracker, IIOProxy ioProxy, IClientProxy clientProxy, IApplicationProxy applicationProxy) { m_UpmCache = RegisterDependency(upmCache); m_FetchStatusTracker = RegisterDependency(fetchStatusTracker); m_IOProxy = RegisterDependency(ioProxy); m_ClientProxy = RegisterDependency(clientProxy); m_Application = RegisterDependency(applicationProxy); } public bool IsAnyExperimentalPackagesInUse() { return PackageInfo.GetAllRegisteredPackages().Any(info => (info.version.Contains("-preview") || info.version.Contains("-exp.") || info.version.StartsWith("0.")) && IsUnityPackage(info)); } public void OnBeforeSerialize() { m_SerializedRegistryUrlsKeys = m_RegistryUrls?.Keys.ToArray() ?? new string[0]; m_SerializedRegistryUrlsValues = m_RegistryUrls?.Values.ToArray() ?? new RegistryType[0]; m_SerializedInProgressExtraFetchOperations = m_ExtraFetchOperations?.Values.Where(i => i.isInProgress).ToArray() ?? new UpmSearchOperation[0]; } public void OnAfterDeserialize() { for (var i = 0; i < m_SerializedRegistryUrlsKeys.Length; i++) m_RegistryUrls[m_SerializedRegistryUrlsKeys[i]] = m_SerializedRegistryUrlsValues[i]; m_SearchOperation?.ResolveDependencies(m_ClientProxy, m_Application); m_SearchOfflineOperation?.ResolveDependencies(m_ClientProxy, m_Application); m_ListOperation?.ResolveDependencies(m_ClientProxy, m_Application); m_ListOfflineOperation?.ResolveDependencies(m_ClientProxy, m_Application); m_AddOperation?.ResolveDependencies(m_ClientProxy, m_Application); m_RemoveOperation?.ResolveDependencies(m_ClientProxy, m_Application); m_AddAndRemoveOperation?.ResolveDependencies(m_ClientProxy, m_Application); } public bool isAddOrRemoveInProgress => m_AddOperation?.isInProgress == true || m_RemoveOperation?.isInProgress == true || m_AddAndRemoveOperation?.isInProgress == true; public IEnumerable<string> packageIdsOrNamesInstalling { get { if (m_AddOperation?.isInProgress == true) yield return m_AddOperation.packageIdOrName; if (m_AddAndRemoveOperation?.isInProgress == true) foreach (var id in m_AddAndRemoveOperation.packageIdsToAdd) yield return id; } } public bool IsRemoveInProgress(string packageName) { return (m_RemoveOperation?.isInProgress == true && m_RemoveOperation.packageName == packageName) || (m_AddAndRemoveOperation?.isInProgress == true && m_AddAndRemoveOperation.packagesNamesToRemove.Contains(packageName)); } public bool IsAddInProgress(string packageId) { return (m_AddOperation?.isInProgress == true && m_AddOperation.packageIdOrName == packageId) || (m_AddAndRemoveOperation?.isInProgress == true && m_AddAndRemoveOperation.packageIdsToAdd.Contains(packageId)); } public void AddById(string packageId) { if (isAddOrRemoveInProgress) return; addOperation.Add(packageId); SetupAddOperation(); } private void SetupAddOperation() { onPackagesProgressChange?.Invoke(new[] { (addOperation.packageName, PackageProgress.Installing) }); addOperation.onProcessResult += OnProcessAddResult; addOperation.onOperationError += (_, error) => onPackageOperationError?.Invoke(addOperation.packageName, error); addOperation.onOperationFinalized += (_) => onPackagesProgressChange?.Invoke(new[] { (addOperation.packageName, PackageProgress.None) }); addOperation.logErrorInConsole = true; onAddOperation?.Invoke(addOperation); } private void OnProcessAddResult(Request<PackageInfo> request) { var packageInfo = request.Result; var installedInfoUpdated = m_UpmCache.SetInstalledPackageInfo(packageInfo, addOperation.packageName); if (!installedInfoUpdated && packageInfo.source == PackageSource.Git) { Debug.Log(string.Format(L10n.Tr("{0} is already up-to-date."), packageInfo.displayName)); return; } PackageManagerExtensions.ExtensionCallback(() => { foreach (var extension in PackageManagerExtensions.Extensions) extension.OnPackageAddedOrUpdated(packageInfo); }); // do a list offline to refresh all the dependencies List(true); } public bool AddByPath(string path, out string tempPackageId) { tempPackageId = string.Empty; if (isAddOrRemoveInProgress) return false; try { tempPackageId = GetTempPackageIdFromPath(path); addOperation.AddByUrlOrPath(tempPackageId, PackageTag.Local); SetupAddOperation(); return true; } catch (System.IO.IOException e) { Debug.Log($"[Package Manager Window] Cannot add package {path}: {e.Message}"); return false; } } public string GetTempPackageIdFromPath(string path) { path = path.Replace('\\', '/'); var projectPath = m_IOProxy.GetProjectDirectory().Replace('\\', '/') + '/'; if (!path.StartsWith(projectPath)) return $"file:{path}"; const string packageFolderPrefix = "Packages/"; var relativePathToProjectRoot = path.Substring(projectPath.Length); if (relativePathToProjectRoot.StartsWith(packageFolderPrefix, StringComparison.InvariantCultureIgnoreCase)) return $"file:{relativePathToProjectRoot.Substring(packageFolderPrefix.Length)}"; else return $"file:../{relativePathToProjectRoot}"; } public void AddByUrl(string url) { if (isAddOrRemoveInProgress) return; addOperation.AddByUrlOrPath(url, PackageTag.Git); SetupAddOperation(); } public void AddByIds(IEnumerable<string> versionIds) { if (isAddOrRemoveInProgress) return; addAndRemoveOperation.AddByIds(versionIds); SetupAddAndRemoveOperation(); } public void RemoveByNames(IEnumerable<string> packagesNames) { if (isAddOrRemoveInProgress) return; addAndRemoveOperation.RemoveByNames(packagesNames); SetupAddAndRemoveOperation(); } public void AddAndResetDependencies(string packageId, IEnumerable<string> dependencyPackagesNames) { if (isAddOrRemoveInProgress) return; addAndRemoveOperation.AddAndResetDependencies(packageId, dependencyPackagesNames); SetupAddAndRemoveOperation(); } public void ResetDependencies(string packageId, IEnumerable<string> dependencyPackagesNames) { if (isAddOrRemoveInProgress) return; addAndRemoveOperation.ResetDependencies(packageId, dependencyPackagesNames); SetupAddAndRemoveOperation(); } private void SetupAddAndRemoveOperation() { var progressUpdates = addAndRemoveOperation.packageIdsToReset.Select(idOrName => (idOrName, PackageProgress.Resetting)) .Concat(addAndRemoveOperation.packageIdsToAdd.Select(idOrName => (idOrName, PackageProgress.Installing))) .Concat(addAndRemoveOperation.packagesNamesToRemove.Select(name => (name, PackageProgress.Removing))); onPackagesProgressChange?.Invoke(progressUpdates); addAndRemoveOperation.onProcessResult += OnProcessAddAndRemoveResult; addAndRemoveOperation.onOperationError += (_, error) => { // For now we only handle addAndRemove operation error when there's a primary `packageName` for the operation // This indicates that this operation is likely related to resetting a specific package. // For all other cases, since PAK team only provide one error message for all packages, we don't know which package // to attach the operation error to, so we don't do any extra handling other than logging the error in the console. // And we'll need to discuss with the PAK team if we want to properly handle error messaging in the UI. var packageName = addAndRemoveOperation.packageName; if (!string.IsNullOrEmpty(packageName)) onPackageOperationError?.Invoke(packageName, error); }; addAndRemoveOperation.onOperationFinalized += (_) => { var allIdOrNames = addAndRemoveOperation.packageIdsToAdd.Concat(addAndRemoveOperation.packageIdsToReset).Concat(addAndRemoveOperation.packagesNamesToRemove); onPackagesProgressChange?.Invoke(allIdOrNames.Select(idOrName => (idOrName, PackageProgress.None))); }; addAndRemoveOperation.logErrorInConsole = true; } private void OnProcessAddAndRemoveResult(Request<PackageCollection> request) { PackageManagerExtensions.ExtensionCallback(() => { foreach (var packageInfo in addAndRemoveOperation.packagesNamesToRemove.Select(name => m_UpmCache.GetInstalledPackageInfo(name)).Where(p => p != null)) foreach (var extension in PackageManagerExtensions.Extensions) extension.OnPackageRemoved(packageInfo); }); m_UpmCache.SetInstalledPackageInfos(request.Result); PackageManagerExtensions.ExtensionCallback(() => { foreach (var packageInfo in addAndRemoveOperation.packageIdsToAdd.Select(id => m_UpmCache.GetInstalledPackageInfoById(id)).Where(p => p != null)) foreach (var extension in PackageManagerExtensions.Extensions) extension.OnPackageAddedOrUpdated(packageInfo); }); } public void List(bool offlineMode = false) { var operation = offlineMode ? listOfflineOperation : listOperation; if (operation.isInProgress) operation.Cancel(); if (offlineMode) operation.ListOffline(listOperation.lastSuccessTimestamp); else operation.List(); operation.onProcessResult += request => OnProcessListResult(request, offlineMode); operation.logErrorInConsole = true; onListOperation(operation); } private void OnProcessListResult(ListRequest request, bool offlineMode) { // skip operation when the result from the online operation is more up-to-date. if (offlineMode && listOfflineOperation.timestamp < listOperation.lastSuccessTimestamp) return; m_UpmCache.SetInstalledPackageInfos(request.Result, listOperation.lastSuccessTimestamp); } public void RemoveByName(string packageName) { if (isAddOrRemoveInProgress) return; removeOperation.Remove(packageName); SetupRemoveOperation(); } public void RemoveEmbeddedByName(string packageName) { if (isAddOrRemoveInProgress) return; var packageInfo = m_UpmCache.GetInstalledPackageInfo(packageName); var resolvedPath = packageInfo?.resolvedPath; if (string.IsNullOrEmpty(resolvedPath)) return; try { // Fix case 1237777, make files writable first foreach (var file in m_IOProxy.DirectoryGetFiles(resolvedPath, "*", System.IO.SearchOption.AllDirectories)) m_IOProxy.MakeFileWritable(file, true); m_IOProxy.DeleteDirectory(resolvedPath); Resolve(); } catch (System.IO.IOException e) { Debug.Log($"[Package Manager Window] Cannot remove embedded package {packageName}: {e.Message}"); } } private void SetupRemoveOperation() { onPackagesProgressChange?.Invoke(new[] { (removeOperation.packageName, progress: PackageProgress.Removing) }); removeOperation.onProcessResult += OnProcessRemoveResult; removeOperation.onOperationError += (_, error) => onPackageOperationError?.Invoke(removeOperation.packageName, error); removeOperation.onOperationFinalized += (_) => onPackagesProgressChange?.Invoke(new[] { (removeOperation.packageName, progress: PackageProgress.None) }); removeOperation.logErrorInConsole = true; } private void OnProcessRemoveResult(RemoveRequest request) { var installedPackage = m_UpmCache.GetInstalledPackageInfo(request.PackageIdOrName); if (installedPackage == null) return; m_UpmCache.RemoveInstalledPackageInfo(installedPackage.name); PackageManagerExtensions.ExtensionCallback(() => { foreach (var extension in PackageManagerExtensions.Extensions) extension.OnPackageRemoved(installedPackage); }); // do a list offline to refresh all the dependencies List(true); } public void SearchAll(bool offlineMode = false) { var operation = offlineMode ? searchOfflineOperation : searchOperation; if (operation.isInProgress) operation.Cancel(); if (offlineMode) operation.SearchAllOffline(searchOperation.lastSuccessTimestamp); else operation.SearchAll(); operation.onProcessResult += request => OnProcessSearchAllResult(request, offlineMode); operation.logErrorInConsole = true; onSearchAllOperation(operation); } private void OnProcessSearchAllResult(SearchRequest request, bool offlineMode) { // skip operation when the result from the online operation is more up-to-date. if (offlineMode && searchOfflineOperation.timestamp < searchOperation.lastSuccessTimestamp) return; m_UpmCache.SetSearchPackageInfos(request.Result, searchOperation.lastSuccessTimestamp); } public void ExtraFetchPackageInfo(string packageIdOrName, long productId = 0, Action<PackageInfo> successCallback = null, Action<UIError> errorCallback = null, Action doneCallback = null) { if (!m_ExtraFetchOperations.TryGetValue(packageIdOrName, out var operation)) { operation = new UpmSearchOperation(); operation.ResolveDependencies(m_ClientProxy, m_Application); operation.Search(packageIdOrName, productId); operation.onProcessResult += (request) => OnProcessExtraFetchResult(request, productId); operation.onOperationFinalized += (op) => m_ExtraFetchOperations.Remove(packageIdOrName); m_ExtraFetchOperations[packageIdOrName] = operation; if (productId > 0) { operation.onOperationError += (op, error) => m_FetchStatusTracker.SetFetchError(productId, FetchType.ProductSearchInfo, error); m_FetchStatusTracker.SetFetchInProgress(productId, FetchType.ProductSearchInfo); } } if (successCallback != null) operation.onProcessResult += (request) => successCallback.Invoke(request.Result.FirstOrDefault()); if (errorCallback != null) operation.onOperationError += (op, error) => errorCallback.Invoke(error); if (doneCallback != null) operation.onOperationFinalized += (op) => doneCallback.Invoke(); } private void OnProcessExtraFetchResult(SearchRequest request, long productId = 0) { var packageInfo = request.Result.FirstOrDefault(); if (productId > 0) { // This is not really supposed to happen - this happening would mean there's an issue with data from the backend // Right now there isn't any recommended actions we can suggest the users to take, so we'll just add a message here // to expose it if it ever happens (rather than letting it pass silently) if (packageInfo?.assetStore?.productId != productId.ToString()) { var error = new UIError(UIErrorCode.AssetStorePackageError, L10n.Tr("Product Id mismatch between product details and package details.")); m_FetchStatusTracker.SetFetchError(productId, FetchType.ProductSearchInfo, error); return; } m_UpmCache.SetProductSearchPackageInfo(packageInfo); m_FetchStatusTracker.SetFetchSuccess(productId, FetchType.ProductSearchInfo); } else m_UpmCache.AddExtraPackageInfo(packageInfo); } // Restore operations that's interrupted by domain reloads private void RestoreInProgressOperations() { if (m_AddOperation?.isInProgress ?? false) { SetupAddOperation(); m_AddOperation.RestoreProgress(); } if (m_RemoveOperation?.isInProgress ?? false) { SetupRemoveOperation(); m_RemoveOperation.RestoreProgress(); } if (m_AddAndRemoveOperation?.isInProgress ?? false) { SetupAddAndRemoveOperation(); m_AddAndRemoveOperation.RestoreProgress(); } if (m_ListOperation?.isInProgress ?? false) List(); if (m_ListOfflineOperation?.isInProgress ?? false) List(true); if (m_SearchOperation?.isInProgress ?? false) SearchAll(); foreach (var operation in m_SerializedInProgressExtraFetchOperations) ExtraFetchPackageInfo(operation.packageIdOrName, operation.productId); } public override void OnEnable() { RestoreInProgressOperations(); } public override void OnDisable() { } public void ClearCache() { m_ExtraFetchOperations.Clear(); m_UpmCache.ClearCache(); } public void Resolve() { m_ClientProxy.Resolve(); } public RegistryType GetAvailableRegistryType(PackageInfo packageInfo) { // Special handling for packages that's built in/bundled with unity, we always consider them from the Unity registry if (packageInfo?.source == PackageSource.BuiltIn) return RegistryType.UnityRegistry; if (packageInfo?.entitlements?.licensingModel == EntitlementLicensingModel.AssetStore) return RegistryType.AssetStore; // Details from the UPM Core team: // We need to check "versions" because RegistryInfo is never null. // It is always populated with the registry info from which the search was performed (usually the main Unity Registry). // The most accurate way to determine that a package's registry is neither "UnityRegistry" nor "MyRegistries" // is by verifying that there are no versions found in the "versions" list. if (packageInfo?.versions == null || packageInfo.versions.all.Length == 0) return RegistryType.None; if (m_RegistryUrls.TryGetValue(packageInfo.registry.url, out var result)) return result; result = packageInfo.registry.isDefault && IsUnityUrl(packageInfo.registry.url) ? RegistryType.UnityRegistry : RegistryType.MyRegistries; m_RegistryUrls[packageInfo.registry.url] = result; return result; } public bool IsUnityPackage(PackageInfo packageInfo) { return packageInfo is { source: PackageSource.BuiltIn or PackageSource.Registry } && GetAvailableRegistryType(packageInfo) == RegistryType.UnityRegistry; } public static bool IsUnityUrl(string url) { if (string.IsNullOrEmpty(url)) return false; try { var uri = new Uri(url); return !uri.IsLoopback && k_UnityRegistryUrlsHosts.Any(unityHost => uri.Host.EndsWith(unityHost, StringComparison.InvariantCultureIgnoreCase)); } catch (UriFormatException) { return false; } } private T CreateOperation<T>(ref T operation) where T : UpmBaseOperation, new() { if (operation != null) { operation.ResolveDependencies(m_ClientProxy, m_Application); return operation; } operation = new T(); operation.ResolveDependencies(m_ClientProxy, m_Application); return operation; } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Upm/UpmClient.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Upm/UpmClient.cs", "repo_id": "UnityCsReference", "token_count": 11174 }
418
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Linq; using UnityEditor.UIElements; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.PackageManager.UI.Internal { internal class DropdownButton : VisualElement, ITextElement, IToolbarMenuElement { [Serializable] public new class UxmlSerializedData : VisualElement.UxmlSerializedData { public override object CreateInstance() => new DropdownButton(); } private const string k_HasSeparateDropdownClass = "separate-dropdown"; private const string k_HasIconClass = "has-icon"; private const float k_MarginsWidth = 6.0f; private const float k_PaddingWidth = 14.0f; private const float k_SideElementWidth = 18.0f; private const float k_DropdownWidth = 12.0f; private VisualElement m_MainButton; public VisualElement mainButton => m_MainButton; private TextElement m_Label; private VisualElement m_ImageIcon; private Background? m_IconBackground; private VisualElement m_SeparateDropdownArea; private VisualElement m_DropdownIcon; private DropdownMenu m_DropdownMenu; /// <summary> /// Sets a dropdown menu for this button. The dropdown menu icon will only show if there is a non-null menu set. /// </summary> public DropdownMenu menu { get => m_DropdownMenu; set { m_DropdownMenu = value; RefreshDropdownIcon(); } } private bool m_AlwaysShowDropdown; public bool alwaysShowDropdown { get => m_AlwaysShowDropdown; set { if (m_AlwaysShowDropdown == value) return; m_AlwaysShowDropdown = value; RefreshDropdownIcon(); } } private Action m_Clicked; /// <summary> /// If the clicked event is never set, then the default behaviour of the button click is to open the dropdown menu /// </summary> public event Action clicked { add { m_Clicked += value; RefreshDropdownIcon(); } remove { m_Clicked -= value; RefreshDropdownIcon(); } } public string text { get => m_Label.text; set { m_Label.text = value; UIUtils.SetElementDisplay(m_Label, !string.IsNullOrEmpty(value)); } } public event Action onBeforeShowDropdown = delegate {}; private bool showDropdownIcon => m_AlwaysShowDropdown || m_DropdownMenu?.Count > 0; private bool isDropdownIconSeparated => m_Clicked != null; private Clickable m_MainButtonClickable; public Clickable clickable => m_MainButtonClickable; public float estimatedWidth { get { var width = string.IsNullOrEmpty(text) ? 0.0f : m_Label.MeasureTextSize(text, 0, MeasureMode.Undefined, 0, MeasureMode.Undefined).x; if (m_ImageIcon != null && (m_IconBackground != null || m_ImageIcon.classList.Any())) width += k_SideElementWidth; if (showDropdownIcon) width += isDropdownIconSeparated ? k_SideElementWidth : k_DropdownWidth; return width + k_MarginsWidth + k_PaddingWidth; } } public DropdownButton() { m_MainButton = new VisualElement { name = "mainButton" }; m_MainButton.AddToClassList(Button.ussClassName); m_MainButtonClickable = new Clickable(OnMainButtonClicked); m_MainButton.AddManipulator(m_MainButtonClickable); Add(m_MainButton); m_Label = new TextElement { name = "label" }; m_MainButton.Add(m_Label); text = string.Empty; } public DropdownButton(Action clickEvent) : this() { clicked += clickEvent; } private void ShowImageIcon() { if (m_ImageIcon == null) { m_ImageIcon = new VisualElement { name = "imageIcon" }; m_MainButton.Insert(0, m_ImageIcon); } AddToClassList(k_HasIconClass); UIUtils.SetElementDisplay(m_ImageIcon, true); } private void HideImageIcon() { if (m_ImageIcon == null) return; m_ImageIcon.ClearClassList(); RemoveFromClassList(k_HasIconClass); UIUtils.SetElementDisplay(m_ImageIcon, false); } public void SetIcon(Icon icon) { if (m_IconBackground != null) return; if (icon == Icon.None) { HideImageIcon(); } else { ShowImageIcon(); m_ImageIcon.ClearClassList(); m_ImageIcon.AddToClassList(icon.ClassName()); } } public void SetIcon(Texture2D icon) { if (icon == null) { m_IconBackground = null; HideImageIcon(); } else { ShowImageIcon(); m_IconBackground = Background.FromTexture2D(icon); m_ImageIcon.ClearClassList(); m_ImageIcon.style.backgroundImage = new StyleBackground((Background)m_IconBackground); } } private void RefreshDropdownIcon() { if (!showDropdownIcon) { m_DropdownIcon?.RemoveFromHierarchy(); RemoveFromClassList(k_HasSeparateDropdownClass); UIUtils.SetElementDisplay(m_SeparateDropdownArea, false); return; } m_DropdownIcon ??= new VisualElement { name = "dropdownIcon" }; if (isDropdownIconSeparated) { if (m_SeparateDropdownArea == null) { m_SeparateDropdownArea = new VisualElement { name = "dropdownArea" }; m_SeparateDropdownArea.AddToClassList(Button.ussClassName); m_SeparateDropdownArea.AddManipulator(new Clickable(ShowDropdown)); Add(m_SeparateDropdownArea); } m_SeparateDropdownArea.Add(m_DropdownIcon); AddToClassList(k_HasSeparateDropdownClass); UIUtils.SetElementDisplay(m_SeparateDropdownArea, true); } else { m_MainButton.Add(m_DropdownIcon); RemoveFromClassList(k_HasSeparateDropdownClass); UIUtils.SetElementDisplay(m_SeparateDropdownArea, false); } } public void ClearClickedEvents() { if (m_Clicked == null) return; m_Clicked = null; RefreshDropdownIcon(); } private void OnMainButtonClicked() { if (m_Clicked != null) m_Clicked.Invoke(); else ShowDropdown(); } private void ShowDropdown() { onBeforeShowDropdown?.Invoke(); if (menu != null) this.ShowMenu(); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/Common/DropdownButton.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/Common/DropdownButton.cs", "repo_id": "UnityCsReference", "token_count": 3881 }
419
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine.UIElements; namespace UnityEditor.PackageManager.UI.Internal { internal static class VisualElementExtensions { public static void OnLeftClick(this VisualElement element, Action action) { element.RegisterCallback<MouseDownEvent>(e => { if (e.button == 0) action?.Invoke(); }); } /// <summary> /// Utility method when toggling between two classes based on boolean /// </summary> /// <param name="element">Extension element</param> /// <param name="classnameA">Class to set if enabled</param> /// <param name="classnameB">Class to set if disabled</param> /// <param name="enable">State to set classes from</param> public static void EnableClassToggle(this VisualElement element, string classnameA, string classnameB, bool enable) { element.RemoveFromClassList(classnameA); element.RemoveFromClassList(classnameB); if (enable) element.AddToClassList(classnameA); else element.AddToClassList(classnameB); } /// <summary> /// Utility method to add multiple classes at once /// </summary> /// <param name="element">Extension element</param> /// <param name="classnames">Space-separated list of classes to add</param> public static void AddClasses(this VisualElement element, string classnames) { if (!string.IsNullOrEmpty(classnames)) foreach (var classname in classnames.Split(' ')) element.AddToClassList(classname); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/Common/VisualElementExtensions.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/Common/VisualElementExtensions.cs", "repo_id": "UnityCsReference", "token_count": 772 }
420
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Linq; namespace UnityEditor.PackageManager.UI.Internal { internal class InstallFoldoutGroup : MultiSelectFoldoutGroup { public InstallFoldoutGroup(IApplicationProxy applicationProxy, IPackageDatabase packageDatabase, IPackageOperationDispatcher operationDispatcher) : base(new AddAction(operationDispatcher, applicationProxy, packageDatabase)) { } public override void Refresh() { if (mainFoldout.versions.FirstOrDefault()?.HasTag(PackageTag.BuiltIn) == true) mainFoldout.headerTextTemplate = L10n.Tr("Enable {0}"); else mainFoldout.headerTextTemplate = L10n.Tr("Install {0}"); if (inProgressFoldout.versions.FirstOrDefault()?.HasTag(PackageTag.BuiltIn) == true) inProgressFoldout.headerTextTemplate = L10n.Tr("Enabling {0}"); else inProgressFoldout.headerTextTemplate = L10n.Tr("Installing {0}"); base.Refresh(); } public override bool AddPackageVersion(IPackageVersion version) { if (!version.HasTag(PackageTag.UpmFormat)) return false; return base.AddPackageVersion(version); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/MultiSelect/InstallFoldoutGroup.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/MultiSelect/InstallFoldoutGroup.cs", "repo_id": "UnityCsReference", "token_count": 592 }
421
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine.UIElements; namespace UnityEditor.PackageManager.UI.Internal { internal class PackageDetailsDescriptionTab : PackageDetailsTabElement { public const string k_Id = "description"; private const string k_EmptyDescriptionClass = "empty"; private const int k_maxDescriptionCharacters = 10000; private VisualElement m_FoldoutContainer; private Toggle m_OverviewToggle; private PackageDetailsOverviewTabContent m_OverviewContent; public override bool IsValid(IPackageVersion version) { return version?.HasTag(PackageTag.UpmFormat) == true; } private readonly IResourceLoader m_ResourceLoader; private readonly IPackageManagerPrefs m_PackageManagerPrefs; public PackageDetailsDescriptionTab(IUnityConnectProxy unityConnect, IResourceLoader resourceLoader, IPackageManagerPrefs packageManagerPrefs) : base(unityConnect) { m_ResourceLoader = resourceLoader; m_PackageManagerPrefs = packageManagerPrefs; m_Id = k_Id; m_DisplayName = L10n.Tr("Description"); var root = resourceLoader.GetTemplate("DetailsTabs/PackageDetailsDescriptionTab.uxml"); m_ContentContainer.Add(root); m_Cache = new VisualElementCache(root); } protected override void RefreshContent(IPackageVersion version) { packagePlatformList.Refresh(version); RefreshDescription(version); RefreshSourcePath(version); RefreshOverviewFoldout(version); } private void RefreshDescription(IPackageVersion version) { var hasVersionDescription = !string.IsNullOrEmpty(version.description); var desc = hasVersionDescription ? version.description : L10n.Tr("There is no description for this package."); if (desc.Length > k_maxDescriptionCharacters) desc = desc.Substring(0, k_maxDescriptionCharacters); detailDescription.EnableInClassList(k_EmptyDescriptionClass, !hasVersionDescription); detailDescription.style.maxHeight = int.MaxValue; detailDescription.SetValueWithoutNotify(desc); } private void RefreshSourcePath(IPackageVersion version) { var sourcePath = (version as UpmPackageVersion)?.sourcePath; UIUtils.SetElementDisplay(detailSourcePathContainer, !string.IsNullOrEmpty(sourcePath)); if (!string.IsNullOrEmpty(sourcePath)) detailSourcePath.SetValueWithoutNotify(sourcePath.EscapeBackslashes()); } private void RefreshOverviewFoldout(IPackageVersion version) { var showFoldout = version.package.product != null; if (showFoldout && m_OverviewContent == null) { m_FoldoutContainer = new VisualElement(); m_OverviewToggle = new Toggle(L10n.Tr("Overview")); m_OverviewToggle.name = "overviewToggle"; m_OverviewToggle.AddToClassList("expander"); m_OverviewToggle.RegisterValueChangedCallback(OnOverviewToggled); m_OverviewToggle.SetValueWithoutNotify(m_PackageManagerPrefs.overviewFoldoutExpanded); m_FoldoutContainer.Add(m_OverviewToggle); m_OverviewContent = new PackageDetailsOverviewTabContent(m_ResourceLoader); m_OverviewContent.name = "overviewFoldout"; m_FoldoutContainer.Add(m_OverviewContent); m_ContentContainer.Add(m_FoldoutContainer); } if (m_OverviewContent == null) return; UIUtils.SetElementDisplay(m_FoldoutContainer, showFoldout); UIUtils.SetElementDisplay(m_OverviewContent, m_PackageManagerPrefs.overviewFoldoutExpanded); m_OverviewContent.Refresh(version); } private void OnOverviewToggled(ChangeEvent<bool> evt) { var expanded = evt.newValue; m_PackageManagerPrefs.overviewFoldoutExpanded = expanded; UIUtils.SetElementDisplay(m_OverviewContent, expanded); } private readonly VisualElementCache m_Cache; private PackagePlatformList packagePlatformList => m_Cache.Get<PackagePlatformList>("detailPlatformList"); private SelectableLabel detailDescription => m_Cache.Get<SelectableLabel>("detailDescription"); private VisualElement detailSourcePathContainer => m_Cache.Get<VisualElement>("detailSourcePathContainer"); private SelectableLabel detailSourcePath => m_Cache.Get<SelectableLabel>("detailSourcePath"); } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageDetailsTabs/PackageDetailsDescriptionTab.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageDetailsTabs/PackageDetailsDescriptionTab.cs", "repo_id": "UnityCsReference", "token_count": 1931 }
422
// 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.UIElements; namespace UnityEditor.PackageManager.UI.Internal { internal class PackageItem : VisualElement, ISelectableItem { // Note that the height here is only the height of the main item (i.e, version list is not expanded) internal const int k_MainItemHeight = 25; private const string k_SelectedClassName = "selected"; private string m_CurrentStateClass; private string m_CurrentFeatureState; public IPackage package { get; private set; } public VisualState visualState { get; private set; } public IPackageVersion targetVersion => package?.versions.primary; public VisualElement element => this; // Since the layout for Feature and Non-Feature are different, we want to keep track of the current layout // and only call BuildMainItem again when there's a layout change private bool? m_IsFeatureLayout = null; internal PackageGroup packageGroup { get; set; } private IPackageVersion selectedVersion { get { if (package != null && m_PageManager.activePage.GetSelection().TryGetValue(package.uniqueId, out var selection)) { if (string.IsNullOrEmpty(selection.versionUniqueId)) return package.versions.primary; return package.versions.FirstOrDefault(v => v.uniqueId == selection.versionUniqueId); } return null; } } private readonly IPageManager m_PageManager; private readonly IPackageDatabase m_PackageDatabase; public PackageItem(IPageManager pageManager, IPackageDatabase packageDatabase) { m_PageManager = pageManager; m_PackageDatabase = packageDatabase; } public void SetPackageAndVisualState(IPackage package, VisualState state) { var isFeature = package?.versions.primary.HasTag(PackageTag.Feature) == true; if (m_IsFeatureLayout != isFeature) { Clear(); BuildMainItem(isFeature); } SetPackage(package); UpdateVisualState(state); } private void BuildMainItem(bool isFeature) { m_IsFeatureLayout = isFeature; m_MainItem = new VisualElement {name = "mainItem"}; Add(m_MainItem); m_LeftContainer = new VisualElement {name = "leftContainer", classList = {"left"}}; m_MainItem.Add(m_LeftContainer); m_DependencyIcon = new Label { name = "dependencyIcon" }; m_DependencyIcon.tooltip = "Installed as dependency"; m_LeftContainer.Add(m_DependencyIcon); m_LockedIcon = new Label { name = "lockedIcon" }; m_LeftContainer.Add(m_LockedIcon); m_DeprecationIcon = new Label { name = "deprecatedIcon" }; m_DeprecationIcon.tooltip = L10n.Tr("Deprecated"); m_LeftContainer.Add(m_DeprecationIcon); m_ExpanderHidden = new Label {name = "expanderHidden", classList = {"expanderHidden"}}; m_LeftContainer.Add(m_ExpanderHidden); m_NameLabel = new Label {name = "packageName", classList = {"name"}}; if (isFeature) { m_MainItem.AddToClassList("feature"); m_NumPackagesInFeature = new Label() { name = "numPackages" }; var leftMiddleContainer = new VisualElement() { name = "leftMiddleContainer" }; leftMiddleContainer.Add(m_NameLabel); leftMiddleContainer.Add(m_NumPackagesInFeature); m_LeftContainer.Add(leftMiddleContainer); } else { m_LeftContainer.Add(m_NameLabel); } m_EntitlementLabel = new Label {name = "entitlementLabel"}; UIUtils.SetElementDisplay(m_EntitlementLabel, false); m_LeftContainer.Add(m_EntitlementLabel); m_VersionLabel = new Label {name = "versionLabel", classList = {"version", "middle"}}; m_MainItem.Add(m_VersionLabel); m_RightContainer = new VisualElement {name = "rightContainer", classList = {"right"}}; m_MainItem.Add(m_RightContainer); var tagContainer = new VisualElement { name = "tagContainer" }; m_TagLabel = new PackageDynamicTagLabel(); tagContainer.Add(m_TagLabel); m_RightContainer.Add(tagContainer); m_Spinner = null; m_StateContainer = new VisualElement { name = "statesContainer" }; m_MainItem.Add(m_StateContainer); m_StateIcon = new VisualElement { name = "stateIcon", classList = { "status" } }; m_StateContainer.Add(m_StateIcon); if (isFeature) { m_InfoStateIcon = new VisualElement { name = "versionState" }; m_StateContainer.Add(m_InfoStateIcon); } } public void UpdateVisualState(VisualState newVisualState) { if (targetVersion == null) return; Refresh(newVisualState); } public void Refresh(VisualState newVisualState = null) { visualState = newVisualState?.Clone() ?? visualState ?? new VisualState(package?.uniqueId, string.Empty, false); EnableInClassList("invisible", !visualState.visible); m_NameLabel.text = targetVersion?.displayName ?? string.Empty; m_VersionLabel.text = targetVersion.versionString ?? string.Empty; if (m_NumPackagesInFeature != null) m_NumPackagesInFeature.text = string.Format(L10n.Tr("{0} packages"), package.versions.primary?.dependencies?.Length ?? 0); var showVersionLabel = !package.versions.primary.HasTag(PackageTag.BuiltIn | PackageTag.Feature); UIUtils.SetElementDisplay(m_VersionLabel, showVersionLabel); m_TagLabel.Refresh(package.versions.primary); RefreshLeftStateIcons(); RefreshRightStateIcons(); RefreshSelection(); RefreshEntitlement(); } public void SetPackage(IPackage package) { this.package = package; name = package?.displayName ?? package?.uniqueId ?? string.Empty; } private void RefreshLeftStateIcons() { var showLockIcon = visualState.isLocked; var showDeprecationIcon = package.isDeprecated; var targetVersion = this.targetVersion; var showDependencyIcon = targetVersion != null && !showLockIcon && targetVersion.isInstalled && !targetVersion.isDirectDependency && !targetVersion.HasTag(PackageTag.Feature); var showExpanderHidden = !showLockIcon && !showDeprecationIcon && !showDependencyIcon; UIUtils.SetElementDisplay(m_LockedIcon, showLockIcon); UIUtils.SetElementDisplay(m_DeprecationIcon, showDeprecationIcon); UIUtils.SetElementDisplay(m_DependencyIcon, showDependencyIcon); UIUtils.SetElementDisplay(m_ExpanderHidden, showExpanderHidden); } public void RefreshRightStateIcons() { if (RefreshSpinner()) return; var state = package?.state ?? PackageState.None; var stateClass = state != PackageState.None ? state.ToString().ToLower() : null; if (!string.IsNullOrEmpty(m_CurrentStateClass)) m_StateIcon.RemoveFromClassList(m_CurrentStateClass); if (!string.IsNullOrEmpty(stateClass)) m_StateIcon.AddToClassList(stateClass); m_CurrentStateClass = stateClass; m_StateIcon.tooltip = GetTooltipByState(state); if (state == PackageState.Installed && package.versions.primary.HasTag(PackageTag.Feature)) RefreshFeatureState(); } // Returns true if package is in progress and spinner is visible private bool RefreshSpinner() { var progress = package?.progress ?? PackageProgress.None; var isInProgress = progress != PackageProgress.None && package?.state == PackageState.InProgress; if (isInProgress) StartSpinner(); else StopSpinner(); return isInProgress; } private void RefreshFeatureState() { var featureState = FeatureState.None; foreach (var dependency in targetVersion.dependencies) { var packageVersion = m_PackageDatabase.GetLifecycleOrPrimaryVersion(dependency.name); if (packageVersion == null) continue; var installedVersion = packageVersion.package?.versions.installed; if (installedVersion == null) continue; // User manually decide to install a different version else if ((installedVersion.isDirectDependency && package.versions.isNonLifecycleVersionInstalled) || installedVersion.HasTag(PackageTag.InDevelopment)) { featureState = FeatureState.Customized; break; } } if (featureState == FeatureState.Customized) { m_CurrentFeatureState = featureState.ToString().ToLower(); m_InfoStateIcon.AddToClassList(m_CurrentFeatureState); m_InfoStateIcon.tooltip = L10n.Tr("This feature has been manually customized"); } else { m_InfoStateIcon.RemoveFromClassList(m_CurrentFeatureState); m_CurrentFeatureState = null; } } public void RefreshSelection() { var enable = selectedVersion != null; EnableInClassList(k_SelectedClassName, enable); m_MainItem.EnableInClassList(k_SelectedClassName, enable); } private void RefreshEntitlement() { var showEntitlement = package.hasEntitlements; UIUtils.SetElementDisplay(m_EntitlementLabel, showEntitlement); m_EntitlementLabel.text = showEntitlement ? "E" : string.Empty; m_EntitlementLabel.tooltip = showEntitlement ? L10n.Tr("This is an Entitlement package.") : string.Empty; } public void SelectMainItem() { m_PageManager.activePage.SetNewSelection(package, null, true); } public void ToggleSelectMainItem() { m_PageManager.activePage.ToggleSelection(package?.uniqueId, true); } private void StartSpinner() { if (m_Spinner == null) { m_Spinner = new LoadingSpinner {name = "packageSpinner"}; m_StateContainer.Insert(0, m_Spinner); } m_Spinner.Start(); m_Spinner.tooltip = GetTooltipByProgress(package.progress); UIUtils.SetElementDisplay(m_StateIcon, false); } private void StopSpinner() { m_Spinner?.Stop(); UIUtils.SetElementDisplay(m_StateIcon, true); } private Label m_NameLabel; private PackageDynamicTagLabel m_TagLabel; private VisualElement m_MainItem; private VisualElement m_StateIcon; private VisualElement m_InfoStateIcon; private VisualElement m_StateContainer; private Label m_EntitlementLabel; private Label m_VersionLabel; private LoadingSpinner m_Spinner; private Label m_LockedIcon; private Label m_DeprecationIcon; private Label m_DependencyIcon; private Label m_ExpanderHidden; private VisualElement m_LeftContainer; private VisualElement m_RightContainer; private Label m_NumPackagesInFeature; private static readonly string[] k_TooltipsByState = { "", L10n.Tr("This {0} is installed."), // Keep the error message for `installed` and `installedAsDependency` the same for now as requested by the designer L10n.Tr("This {0} is installed."), L10n.Tr("This {0} is available for download."), L10n.Tr("This {0} is available for import."), L10n.Tr("There are assets in your project that are imported from this {0}."), L10n.Tr("This {0} is in development."), L10n.Tr("A newer version of this {0} is available."), "", L10n.Tr("There are errors with this {0}. Read the {0} details for further guidance."), L10n.Tr("There are warnings with this {0}. Read the {0} details for further guidance.") }; public string GetTooltipByState(PackageState state) { return string.Format(k_TooltipsByState[(int)state], package.versions.primary.GetDescriptor()); } private static readonly string[] k_TooltipsByProgress = { "", L10n.Tr("{0} refreshing in progress."), L10n.Tr("{0} downloading in progress."), L10n.Tr("{0} pausing in progress."), L10n.Tr("{0} resuming in progress."), L10n.Tr("{0} installing in progress."), L10n.Tr("{0} resetting in progress."), L10n.Tr("{0} removing in progress.") }; public string GetTooltipByProgress(PackageProgress progress) { return string.Format(k_TooltipsByProgress[(int)progress], package.versions.primary.GetDescriptor(true)); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageItem.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageItem.cs", "repo_id": "UnityCsReference", "token_count": 6313 }
423
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine.UIElements; namespace UnityEditor.PackageManager.UI.Internal { internal class PackageSampleItemLowWidth : VisualElement { private VisualElementCache cache { get; set; } public PackageSampleItemLowWidth(IResourceLoader resourceLoader, IPackageVersion version, Sample sample, ISelectionProxy selection, IAssetDatabaseProxy assetDatabase, IApplicationProxy application, IIOProxy iOProxy) { var root = resourceLoader.GetTemplate("PackageSampleItemLowWidth.uxml"); Add(root); cache = new VisualElementCache(root); var sampleItem = new PackageDetailsSampleItem(version, sample, selection, assetDatabase, application, iOProxy); sampleItem.importButton.SetEnabled(version.isInstalled); var name = sampleItem.nameLabel.text; var size = sampleItem.sizeLabel.text; var description = sampleItem.descriptionLabel.text; itemName.text = name; itemName.tooltip = name; sampleStatus.Add(sampleItem.importStatus); itemSizeOrVersion.value = size; itemSizeOrVersion.tooltip = size; importButtonContainer.Add(sampleItem.importButton); if (!string.IsNullOrEmpty(description)) { UIUtils.SetElementDisplay(sampleDescription, true); sampleDescription.SetValueWithoutNotify(description); } else { UIUtils.SetElementDisplay(sampleDescription, false); } } private VisualElement itemStatusNameContainer { get { return cache.Get<VisualElement>("itemStatusNameContainer"); } } private VisualElement sampleStatus { get { return cache.Get<VisualElement>("sampleStatus"); } } private Label itemName { get { return cache.Get<Label>("itemName"); } } private SelectableLabel itemSizeOrVersion { get { return cache.Get<SelectableLabel>("itemSizeOrVersion"); } } private VisualElement item { get { return cache.Get<VisualElement>("dependencySampleItemLowWidth"); } } private VisualElement importButtonContainer { get { return cache.Get<VisualElement>("importButtonContainer"); } } private SelectableLabel sampleDescription { get { return cache.Get<SelectableLabel>("sampleDescription"); } } } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageSampleItemLowWidth.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageSampleItemLowWidth.cs", "repo_id": "UnityCsReference", "token_count": 915 }
424
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine.UIElements; namespace UnityEditor.PackageManager.UI.Internal; internal class SelectionWindowFooter : VisualElement { public event Action onAllButtonClicked = delegate {}; public event Action onNoneButtonClicked = delegate {}; public event Action onActionButtonClicked = delegate {}; public event Action onCancelButtonClicked = delegate {}; private Button m_ActionButton; public SelectionWindowFooter() { var separator = new VisualElement { name = "separator", classList = { "separator" } }; Add(separator); var footer = new VisualElement { name = "footer", classList = { "footer" } }; Add(footer); var leftSection = new VisualElement { name = "leftSection", classList = { "left-section" } }; footer.Add(leftSection); var allButton = new Button { name = "allButton", text = "All", tabIndex = -1, displayTooltipWhenElided = true }; allButton.clicked += () => onAllButtonClicked?.Invoke(); leftSection.Add(allButton); var noneButton = new Button { name = "noneButton", text = "None", tabIndex = -1, displayTooltipWhenElided = true }; noneButton.clicked += () => onNoneButtonClicked?.Invoke(); leftSection.Add(noneButton); var rightSection = new VisualElement { name = "rightSection", classList = { "right-section" } }; footer.Add(rightSection); m_ActionButton = new Button { name = "actionButton", text = "Action", tabIndex = -1, displayTooltipWhenElided = true }; m_ActionButton.clicked += () => onActionButtonClicked?.Invoke(); rightSection.Add(m_ActionButton); var cancelButton = new Button { name = "cancelButton", text = "Cancel", tabIndex = -1, displayTooltipWhenElided = true }; cancelButton.clicked += () => onCancelButtonClicked?.Invoke(); rightSection.Add(cancelButton); } public void SetData(string actionName) { m_ActionButton.text = actionName; } public void SetActionEnabled(bool isEnabled) { m_ActionButton.SetEnabled(isEnabled); } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/SelectionWindow/SelectionWindowFooter.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/SelectionWindow/SelectionWindowFooter.cs", "repo_id": "UnityCsReference", "token_count": 795 }
425
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using Unity.Jobs.LowLevel.Unsafe; using Unity.Burst; using static Unity.Collections.LowLevel.Unsafe.BurstLike; namespace UnityEngine.ParticleSystemJobs { public struct ParticleSystemNativeArray3 { public NativeArray<float> x; public NativeArray<float> y; public NativeArray<float> z; public Vector3 this[int index] { get { return new Vector3(x[index], y[index], z[index]); } set { x[index] = value.x; y[index] = value.y; z[index] = value.z; } } } public struct ParticleSystemNativeArray4 { public NativeArray<float> x; public NativeArray<float> y; public NativeArray<float> z; public NativeArray<float> w; public Vector4 this[int index] { get { return new Vector4(x[index], y[index], z[index], w[index]); } set { x[index] = value.x; y[index] = value.y; z[index] = value.z; w[index] = value.w; } } } public struct ParticleSystemJobData { public int count { get; } public ParticleSystemNativeArray3 positions { get; } public ParticleSystemNativeArray3 velocities { get; } public ParticleSystemNativeArray3 axisOfRotations { get; } public ParticleSystemNativeArray3 rotations { get; } public ParticleSystemNativeArray3 rotationalSpeeds { get; } public ParticleSystemNativeArray3 sizes { get; } public NativeArray<Color32> startColors { get; } public NativeArray<float> aliveTimePercent { get; } public NativeArray<float> inverseStartLifetimes { get; } public NativeArray<UInt32> randomSeeds { get; } public ParticleSystemNativeArray4 customData1 { get; } public ParticleSystemNativeArray4 customData2 { get; } public NativeArray<int> meshIndices { get; } internal AtomicSafetyHandle m_Safety; unsafe internal ParticleSystemJobData(ref NativeParticleData nativeData) : this() { m_Safety = AtomicSafetyHandle.Create(); count = nativeData.count; positions = CreateNativeArray3(ref nativeData.positions, count); velocities = CreateNativeArray3(ref nativeData.velocities, count); axisOfRotations = CreateNativeArray3(ref nativeData.axisOfRotations, count); rotations = CreateNativeArray3(ref nativeData.rotations, count); rotationalSpeeds = CreateNativeArray3(ref nativeData.rotationalSpeeds, count); sizes = CreateNativeArray3(ref nativeData.sizes, count); startColors = CreateNativeArray<Color32>(nativeData.startColors, count); aliveTimePercent = CreateNativeArray<float>(nativeData.aliveTimePercent, count); inverseStartLifetimes = CreateNativeArray<float>(nativeData.inverseStartLifetimes, count); randomSeeds = CreateNativeArray<UInt32>(nativeData.randomSeeds, count); customData1 = CreateNativeArray4(ref nativeData.customData1, count); customData2 = CreateNativeArray4(ref nativeData.customData2, count); meshIndices = CreateNativeArray<int>(nativeData.meshIndices, count); } unsafe internal NativeArray<T> CreateNativeArray<T>(void* src, int count) where T : struct { var arr = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<T>(src, count, Allocator.Invalid); NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref arr, m_Safety); return arr; } unsafe internal ParticleSystemNativeArray3 CreateNativeArray3(ref NativeParticleData.Array3 ptrs, int count) { return new ParticleSystemNativeArray3 { x = CreateNativeArray<float>(ptrs.x, count), y = CreateNativeArray<float>(ptrs.y, count), z = CreateNativeArray<float>(ptrs.z, count) }; } unsafe internal ParticleSystemNativeArray4 CreateNativeArray4(ref NativeParticleData.Array4 ptrs, int count) { return new ParticleSystemNativeArray4 { x = CreateNativeArray<float>(ptrs.x, count), y = CreateNativeArray<float>(ptrs.y, count), z = CreateNativeArray<float>(ptrs.z, count), w = CreateNativeArray<float>(ptrs.w, count) }; } } unsafe internal struct NativeParticleData { internal struct Array3 { internal float* x; internal float* y; internal float* z; } internal struct Array4 { internal float* x; internal float* y; internal float* z; internal float* w; } internal int count; internal Array3 positions; internal Array3 velocities; internal Array3 axisOfRotations; internal Array3 rotations; internal Array3 rotationalSpeeds; internal Array3 sizes; internal void* startColors; internal void* aliveTimePercent; internal void* inverseStartLifetimes; internal void* randomSeeds; internal Array4 customData1; internal Array4 customData2; internal void* meshIndices; } unsafe struct NativeListData { public void* system; public int length; public int capacity; } internal struct ParticleSystemJobStruct<T> where T : struct, IJobParticleSystem { public static readonly SharedStatic<IntPtr> jobReflectionData = SharedStatic<IntPtr>.GetOrCreate<ParticleSystemJobStruct<T>>(); [BurstDiscard] public static void Initialize() { if (jobReflectionData.Data == IntPtr.Zero) jobReflectionData.Data = JobsUtility.CreateJobReflectionData(typeof(T), (ExecuteJobFunction)Execute); } public delegate void ExecuteJobFunction(ref T data, IntPtr listDataPtr, IntPtr unusedPtr, ref JobRanges ranges, int jobIndex); public static unsafe void Execute(ref T data, IntPtr listDataPtr, IntPtr unusedPtr, ref JobRanges ranges, int jobIndex) { NativeParticleData particleData; var listData = (NativeListData*)listDataPtr; ParticleSystem.CopyManagedJobData(listData->system, out particleData); ParticleSystemJobData jobData = new ParticleSystemJobData(ref particleData); data.Execute(jobData); AtomicSafetyHandle.CheckDeallocateAndThrow(jobData.m_Safety); AtomicSafetyHandle.Release(jobData.m_Safety); } } internal struct ParticleSystemParallelForJobStruct<T> where T : struct, IJobParticleSystemParallelFor { public static readonly SharedStatic<IntPtr> jobReflectionData = SharedStatic<IntPtr>.GetOrCreate<ParticleSystemParallelForJobStruct<T>>(); [BurstDiscard] public static void Initialize() { if (jobReflectionData.Data == IntPtr.Zero) jobReflectionData.Data = JobsUtility.CreateJobReflectionData(typeof(T), (ExecuteJobFunction)Execute); } public delegate void ExecuteJobFunction(ref T data, IntPtr listDataPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); public static unsafe void Execute(ref T data, IntPtr listDataPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) { NativeParticleData particleData; var listData = (NativeListData*)listDataPtr; ParticleSystem.CopyManagedJobData(listData->system, out particleData); ParticleSystemJobData jobData = new ParticleSystemJobData(ref particleData); while (true) { int begin; int end; if (!JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) break; JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref data), begin, end - begin); for (var i = begin; i < end; ++i) data.Execute(jobData, i); } AtomicSafetyHandle.CheckDeallocateAndThrow(jobData.m_Safety); AtomicSafetyHandle.Release(jobData.m_Safety); } } internal struct ParticleSystemParallelForBatchJobStruct<T> where T : struct, IJobParticleSystemParallelForBatch { public static readonly SharedStatic<IntPtr> jobReflectionData = SharedStatic<IntPtr>.GetOrCreate<ParticleSystemParallelForBatchJobStruct<T>>(); [BurstDiscard] public static void Initialize() { if (jobReflectionData.Data == IntPtr.Zero) jobReflectionData.Data = JobsUtility.CreateJobReflectionData(typeof(T), (ExecuteJobFunction)Execute); } public delegate void ExecuteJobFunction(ref T data, IntPtr listDataPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); public static unsafe void Execute(ref T data, IntPtr listDataPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) { NativeParticleData particleData; var listData = (NativeListData*)listDataPtr; ParticleSystem.CopyManagedJobData(listData->system, out particleData); ParticleSystemJobData jobData = new ParticleSystemJobData(ref particleData); while (true) { int begin; int end; if (!JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out begin, out end)) break; JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref data), begin, end - begin); data.Execute(jobData, begin, end - begin); } AtomicSafetyHandle.CheckDeallocateAndThrow(jobData.m_Safety); AtomicSafetyHandle.Release(jobData.m_Safety); } } }
UnityCsReference/Modules/ParticleSystem/Managed/ParticleSystemJobStructs.cs/0
{ "file_path": "UnityCsReference/Modules/ParticleSystem/Managed/ParticleSystemJobStructs.cs", "repo_id": "UnityCsReference", "token_count": 4486 }
426
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEditorInternal; using System.Collections.Generic; namespace UnityEditor { class EmissionModuleUI : ModuleUI { public SerializedMinMaxCurve m_Time; public SerializedMinMaxCurve m_Distance; // Keep in sync with EmissionModule.h const int k_MaxNumBursts = 8; const float k_BurstDragWidth = 15.0f; SerializedProperty m_BurstCount; SerializedProperty m_Bursts; List<SerializedMinMaxCurve> m_BurstCountCurves = new List<SerializedMinMaxCurve>(); ReorderableList m_BurstList; class Texts { public GUIContent rateOverTime = EditorGUIUtility.TrTextContent("Rate over Time", "The number of particles emitted per second."); public GUIContent rateOverDistance = EditorGUIUtility.TrTextContent("Rate over Distance", "The number of particles emitted per distance unit."); public GUIContent burst = EditorGUIUtility.TrTextContent("Bursts", "Emission of extra particles at specific times during the duration of the system."); public GUIContent burstTime = EditorGUIUtility.TrTextContent("Time", "When the burst will trigger."); public GUIContent burstCount = EditorGUIUtility.TrTextContent("Count", "The number of particles to emit."); public GUIContent burstCycleCount = EditorGUIUtility.TrTextContent("Cycles", "How many times to emit the burst. Use the dropdown to repeat infinitely."); public GUIContent burstCycleCountInfinite = EditorGUIUtility.TrTextContent("Infinite"); public GUIContent burstRepeatInterval = EditorGUIUtility.TrTextContent("Interval", "Repeat the burst every N seconds."); public GUIContent burstProbability = EditorGUIUtility.TrTextContent("Probability", "0-1 Chance that the burst will trigger."); } private static Texts s_Texts; public EmissionModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "EmissionModule", displayName) { m_ToolTip = "Emission of the emitter. This controls the rate at which particles are emitted as well as burst emissions."; } protected override void Init() { // Already initialized? if (m_BurstCount != null) return; if (s_Texts == null) s_Texts = new Texts(); m_Time = new SerializedMinMaxCurve(this, s_Texts.rateOverTime, "rateOverTime"); m_Distance = new SerializedMinMaxCurve(this, s_Texts.rateOverDistance, "rateOverDistance"); m_BurstCount = GetProperty("m_BurstCount"); m_Bursts = GetProperty("m_Bursts"); m_BurstList = new ReorderableList(serializedObject, m_Bursts, false, true, true, true); m_BurstList.elementHeight = kReorderableListElementHeight; m_BurstList.onAddCallback = OnBurstListAddCallback; m_BurstList.onCanAddCallback = OnBurstListCanAddCallback; m_BurstList.onRemoveCallback = OnBurstListRemoveCallback; m_BurstList.drawHeaderCallback = DrawBurstListHeaderCallback; m_BurstList.drawElementCallback = DrawBurstListElementCallback; } override public void OnInspectorGUI(InitialModuleUI initial) { GUIMinMaxCurve(s_Texts.rateOverTime, m_Time); GUIMinMaxCurve(s_Texts.rateOverDistance, m_Distance); DoBurstGUI(initial); } private void DoBurstGUI(InitialModuleUI initial) { while (m_BurstList.count > m_BurstCountCurves.Count) { SerializedProperty burst = m_Bursts.GetArrayElementAtIndex(m_BurstCountCurves.Count); m_BurstCountCurves.Add(new SerializedMinMaxCurve(this, s_Texts.burstCount, burst.propertyPath + ".countCurve", false, true)); } EditorGUILayout.Space(); Rect rect = GetControlRect(kSingleLineHeight); GUI.Label(rect, s_Texts.burst, ParticleSystemStyles.Get().label); m_BurstList.displayAdd = (m_Bursts.arraySize < k_MaxNumBursts); m_BurstList.DoLayoutList(); } private void OnBurstListAddCallback(ReorderableList list) { ReorderableList.defaultBehaviours.DoAddButton(list); m_BurstCount.intValue++; SerializedProperty burst = m_Bursts.GetArrayElementAtIndex(list.index); SerializedProperty burstCountState = burst.FindPropertyRelative("countCurve.minMaxState"); SerializedProperty burstCount = burst.FindPropertyRelative("countCurve.scalar"); SerializedProperty burstCycleCount = burst.FindPropertyRelative("cycleCount"); SerializedProperty burstProbability = burst.FindPropertyRelative("probability"); burstCountState.intValue = (int)ParticleSystemCurveMode.Constant; burstCount.floatValue = 30.0f; burstCycleCount.intValue = 1; burstProbability.floatValue = 1.0f; SerializedProperty burstCountMinCurve = burst.FindPropertyRelative("countCurve.minCurve"); SerializedProperty burstCountMaxCurve = burst.FindPropertyRelative("countCurve.maxCurve"); burstCountMinCurve.animationCurveValue = AnimationCurve.Linear(0.0f, 1.0f, 1.0f, 1.0f); burstCountMaxCurve.animationCurveValue = AnimationCurve.Linear(0.0f, 1.0f, 1.0f, 1.0f); m_BurstCountCurves.Add(new SerializedMinMaxCurve(this, s_Texts.burstCount, burst.propertyPath + ".countCurve", false, true)); } private bool OnBurstListCanAddCallback(ReorderableList list) { return !m_ParticleSystemUI.multiEdit; } private void OnBurstListRemoveCallback(ReorderableList list) { // All subsequent curves must be removed from the curve editor, as their indices will change, which means their SerializedProperty paths will also change for (int i = list.index; i < m_BurstCountCurves.Count; i++) m_BurstCountCurves[i].RemoveCurveFromEditor(); m_BurstCountCurves.RemoveRange(list.index, m_BurstCountCurves.Count - list.index); AnimationCurvePreviewCache.ClearCache(); // Default remove behavior ReorderableList.defaultBehaviours.DoRemoveButton(list); m_BurstCount.intValue--; } private void DrawBurstListHeaderCallback(Rect rect) { rect.width -= k_BurstDragWidth; rect.width /= 5; rect.x += k_BurstDragWidth; EditorGUI.LabelField(rect, s_Texts.burstTime, ParticleSystemStyles.Get().label); rect.x += rect.width; EditorGUI.LabelField(rect, s_Texts.burstCount, ParticleSystemStyles.Get().label); rect.x += rect.width; EditorGUI.LabelField(rect, s_Texts.burstCycleCount, ParticleSystemStyles.Get().label); rect.x += rect.width; EditorGUI.LabelField(rect, s_Texts.burstRepeatInterval, ParticleSystemStyles.Get().label); rect.x += rect.width; EditorGUI.LabelField(rect, s_Texts.burstProbability, ParticleSystemStyles.Get().label); rect.x += rect.width; } private void DrawBurstListElementCallback(Rect rect, int index, bool isActive, bool isFocused) { SerializedProperty burst = m_Bursts.GetArrayElementAtIndex(index); SerializedProperty burstTime = burst.FindPropertyRelative("time"); SerializedProperty burstCycleCount = burst.FindPropertyRelative("cycleCount"); SerializedProperty burstRepeatInterval = burst.FindPropertyRelative("repeatInterval"); SerializedProperty burstProbability = burst.FindPropertyRelative("probability"); rect.width -= (k_BurstDragWidth * 4); rect.width /= 5; // Time FloatDraggable(rect, burstTime, 1.0f, k_BurstDragWidth, "n3"); rect.x += rect.width; // Count rect = GUIMinMaxCurveInline(rect, m_BurstCountCurves[index], k_BurstDragWidth); rect.x += rect.width; // Cycle Count rect.width -= k_minMaxToggleWidth; if (!burstCycleCount.hasMultipleDifferentValues && burstCycleCount.intValue == 0) { rect.x += k_BurstDragWidth; rect.width -= k_BurstDragWidth; EditorGUI.LabelField(rect, s_Texts.burstCycleCountInfinite, ParticleSystemStyles.Get().label); } else { IntDraggable(rect, null, burstCycleCount, k_BurstDragWidth); } rect.width += k_minMaxToggleWidth; Rect popupRect = GetPopupRect(rect); GUIMMModePopUp(popupRect, burstCycleCount); rect.x += rect.width; // Repeat Interval FloatDraggable(rect, burstRepeatInterval, 1.0f, k_BurstDragWidth, "n3"); rect.x += rect.width; // Probability FloatDraggable(rect, burstProbability, 1.0f, k_BurstDragWidth, "n2"); rect.x += rect.width; } private class ModeCallbackData { public ModeCallbackData(int i, SerializedProperty p) { modeProp = p; selectedState = i; } public SerializedProperty modeProp; public int selectedState; } private static void SelectModeCallback(object obj) { ModeCallbackData data = (ModeCallbackData)obj; data.modeProp.intValue = (int)data.selectedState; } private static void GUIMMModePopUp(Rect rect, SerializedProperty modeProp) { if (EditorGUI.DropdownButton(rect, GUIContent.none, FocusType.Passive, ParticleSystemStyles.Get().minMaxCurveStateDropDown)) { GUIContent[] texts = { EditorGUIUtility.TrTextContent("Infinite"), EditorGUIUtility.TrTextContent("Count") }; GenericMenu menu = new GenericMenu(); for (int i = 0; i < texts.Length; ++i) { menu.AddItem(texts[i], (modeProp.intValue == i), SelectModeCallback, new ModeCallbackData(i, modeProp)); } menu.ShowAsContext(); Event.current.Use(); } } override public void UpdateCullingSupportedString(ref string text) { Init(); if (m_Distance.scalar.hasMultipleDifferentValues || m_Distance.scalar.floatValue > 0.0f) text += "\nDistance-based emission is being used in the Emission module."; } } } // namespace UnityEditor
UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemModules/EmissionModuleUI.cs/0
{ "file_path": "UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemModules/EmissionModuleUI.cs", "repo_id": "UnityCsReference", "token_count": 4739 }
427
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; namespace UnityEditor { class SizeModuleUI : ModuleUI { SerializedMinMaxCurve m_X; SerializedMinMaxCurve m_Y; SerializedMinMaxCurve m_Z; SerializedProperty m_SeparateAxes; class Texts { public GUIContent size = EditorGUIUtility.TrTextContent("Size", "Controls the size of each particle during its lifetime."); public GUIContent separateAxes = EditorGUIUtility.TrTextContent("Separate Axes", "If enabled, you can control the angular velocity limit separately for each axis."); public GUIContent x = EditorGUIUtility.TextContent("X"); public GUIContent y = EditorGUIUtility.TextContent("Y"); public GUIContent z = EditorGUIUtility.TextContent("Z"); } static Texts s_Texts; public SizeModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "SizeModule", displayName) { m_ToolTip = "Controls the size of each particle during its lifetime."; } protected override void Init() { // Already initialized? if (m_X != null) return; if (s_Texts == null) s_Texts = new Texts(); m_SeparateAxes = GetProperty("separateAxes"); m_X = new SerializedMinMaxCurve(this, s_Texts.x, "curve"); m_Y = new SerializedMinMaxCurve(this, s_Texts.y, "y", false, false, m_SeparateAxes.boolValue); m_Z = new SerializedMinMaxCurve(this, s_Texts.z, "z", false, false, m_SeparateAxes.boolValue); m_X.m_AllowConstant = false; m_Y.m_AllowConstant = false; m_Z.m_AllowConstant = false; } override public void OnInspectorGUI(InitialModuleUI initial) { EditorGUI.BeginChangeCheck(); bool separateAxes = GUIToggle(s_Texts.separateAxes, m_SeparateAxes); if (EditorGUI.EndChangeCheck()) { // Remove old curves from curve editor if (!separateAxes) { m_Y.RemoveCurveFromEditor(); m_Z.RemoveCurveFromEditor(); } } // Keep states in sync if (!m_X.stateHasMultipleDifferentValues) { m_Z.SetMinMaxState(m_X.state, separateAxes); m_Y.SetMinMaxState(m_X.state, separateAxes); } if (separateAxes) { m_X.m_DisplayName = s_Texts.x; GUITripleMinMaxCurve(GUIContent.none, s_Texts.x, m_X, s_Texts.y, m_Y, s_Texts.z, m_Z, null); } else { m_X.m_DisplayName = s_Texts.size; GUIMinMaxCurve(s_Texts.size, m_X); } } } } // namespace UnityEditor
UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemModules/SizeModuleUI.cs/0
{ "file_path": "UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemModules/SizeModuleUI.cs", "repo_id": "UnityCsReference", "token_count": 1517 }
428
// Unity 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.ComponentModel; namespace UnityEngine { public partial class Collision { [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Do not use Collision.GetEnumerator(), enumerate using non-allocating array returned by Collision.GetContacts() or enumerate using Collision.GetContact(index) instead.", false)] public virtual IEnumerator GetEnumerator() { return contacts.GetEnumerator(); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use Collision.relativeVelocity instead. (UnityUpgradable) -> relativeVelocity", false)] public Vector3 impactForceSum { get { return Vector3.zero; } } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Will always return zero.", true)] public Vector3 frictionForceSum { get { return Vector3.zero; } } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Please use Collision.rigidbody, Collision.transform or Collision.collider instead", false)] public Component other { get { return body != null ? body : collider; } } } }
UnityCsReference/Modules/Physics/Managed/Collision.deprecated.cs/0
{ "file_path": "UnityCsReference/Modules/Physics/Managed/Collision.deprecated.cs", "repo_id": "UnityCsReference", "token_count": 457 }
429
// 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(Rigidbody))] [NativeHeader("Modules/Physics/ConstantForce.h")] public class ConstantForce : Behaviour { extern public Vector3 force { get; set; } extern public Vector3 torque { get; set; } extern public Vector3 relativeForce { get; set; } extern public Vector3 relativeTorque { get; set; } } }
UnityCsReference/Modules/Physics/ScriptBindings/ConstantForce.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Physics/ScriptBindings/ConstantForce.bindings.cs", "repo_id": "UnityCsReference", "token_count": 206 }
430
// Unity 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 Unity.Jobs; using Unity.Jobs.LowLevel.Unsafe; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using UnityEngine.Internal; using System.Runtime.InteropServices; using System.Collections.Generic; namespace UnityEngine { [StructLayout(LayoutKind.Sequential)] public struct QueryParameters { public int layerMask; public bool hitMultipleFaces; public QueryTriggerInteraction hitTriggers; public bool hitBackfaces; public QueryParameters(int layerMask = Physics.DefaultRaycastLayers, bool hitMultipleFaces = false, QueryTriggerInteraction hitTriggers = QueryTriggerInteraction.UseGlobal, bool hitBackfaces = false) { this.layerMask = layerMask; this.hitMultipleFaces = hitMultipleFaces; this.hitTriggers = hitTriggers; this.hitBackfaces = hitBackfaces; } public static QueryParameters Default => new QueryParameters(Physics.DefaultRaycastLayers, false, QueryTriggerInteraction.UseGlobal, false); } [StructLayout(LayoutKind.Sequential)] public struct ColliderHit { private int m_ColliderInstanceID; public int instanceID => m_ColliderInstanceID; // note this is a main-thread only API public Collider collider => Object.FindObjectFromInstanceID(instanceID) as Collider; } [NativeHeader("Modules/Physics/BatchCommands/RaycastCommand.h")] [NativeHeader("Runtime/Jobs/ScriptBindings/JobsBindingsTypes.h")] public partial struct RaycastCommand { public RaycastCommand(Vector3 from, Vector3 direction, QueryParameters queryParameters, float distance = float.MaxValue) { this.from = from; this.direction = direction; this.physicsScene = Physics.defaultPhysicsScene; this.distance = distance; this.queryParameters = queryParameters; } public RaycastCommand(PhysicsScene physicsScene, Vector3 from, Vector3 direction, QueryParameters queryParameters, float distance = float.MaxValue) { this.from = from; this.direction = direction; this.physicsScene = physicsScene; this.distance = distance; this.queryParameters = queryParameters; } public Vector3 from { get; set; } public Vector3 direction {get; set; } public PhysicsScene physicsScene { get; set; } public float distance { get; set; } public QueryParameters queryParameters; public unsafe static JobHandle ScheduleBatch(NativeArray<RaycastCommand> commands, NativeArray<RaycastHit> results, int minCommandsPerJob, int maxHits, JobHandle dependsOn = new JobHandle()) { if (maxHits < 1) { Debug.LogWarning("maxHits should be greater than 0."); return new JobHandle(); } else if (results.Length < maxHits * commands.Length) { Debug.LogWarning("The supplied results buffer is too small, there should be at least maxHits space per each command in the batch."); return new JobHandle(); } var jobData = new BatchQueryJob<RaycastCommand, RaycastHit>(commands, results); var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), BatchQueryJobStruct<BatchQueryJob<RaycastCommand, RaycastHit>>.Initialize(), dependsOn, ScheduleMode.Parallel); return ScheduleRaycastBatch(ref scheduleParams, NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(commands), commands.Length, NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(results), results.Length, minCommandsPerJob, maxHits); } public unsafe static JobHandle ScheduleBatch(NativeArray<RaycastCommand> commands, NativeArray<RaycastHit> results, int minCommandsPerJob, JobHandle dependsOn = new JobHandle()) { return ScheduleBatch(commands, results, minCommandsPerJob, 1, dependsOn); } [FreeFunction("ScheduleRaycastCommandBatch", ThrowsException = true)] unsafe extern private static JobHandle ScheduleRaycastBatch(ref JobsUtility.JobScheduleParameters parameters, void* commands, int commandLen, void* result, int resultLen, int minCommandsPerJob, int maxHits); } [NativeHeader("Modules/Physics/BatchCommands/SpherecastCommand.h")] [NativeHeader("Runtime/Jobs/ScriptBindings/JobsBindingsTypes.h")] public partial struct SpherecastCommand { public SpherecastCommand(Vector3 origin, float radius, Vector3 direction, QueryParameters queryParameters, float distance = float.MaxValue) { this.origin = origin; this.direction = direction; this.radius = radius; this.distance = distance; this.physicsScene = Physics.defaultPhysicsScene; this.queryParameters = queryParameters; } public SpherecastCommand(PhysicsScene physicsScene, Vector3 origin, float radius, Vector3 direction, QueryParameters queryParameters, float distance = float.MaxValue) { this.origin = origin; this.direction = direction; this.radius = radius; this.distance = distance; this.physicsScene = physicsScene; this.queryParameters = queryParameters; } public Vector3 origin { get; set; } public float radius { get; set; } public Vector3 direction { get; set; } public float distance { get; set; } public PhysicsScene physicsScene { get; set; } public QueryParameters queryParameters; public unsafe static JobHandle ScheduleBatch(NativeArray<SpherecastCommand> commands, NativeArray<RaycastHit> results, int minCommandsPerJob, int maxHits, JobHandle dependsOn = new JobHandle()) { if (maxHits < 1) { Debug.LogWarning("maxHits should be greater than 0."); return new JobHandle(); } else if (results.Length < maxHits * commands.Length) { Debug.LogWarning("The supplied results buffer is too small, there should be at least maxHits space per each command in the batch."); return new JobHandle(); } var jobData = new BatchQueryJob<SpherecastCommand, RaycastHit>(commands, results); var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), BatchQueryJobStruct<BatchQueryJob<SpherecastCommand, RaycastHit>>.Initialize(), dependsOn, ScheduleMode.Parallel); return ScheduleSpherecastBatch(ref scheduleParams, NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(commands), commands.Length, NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(results), results.Length, minCommandsPerJob, maxHits); } public unsafe static JobHandle ScheduleBatch(NativeArray<SpherecastCommand> commands, NativeArray<RaycastHit> results, int minCommandsPerJob, JobHandle dependsOn = new JobHandle()) { return ScheduleBatch(commands, results, minCommandsPerJob, 1, dependsOn); } [FreeFunction("ScheduleSpherecastCommandBatch", ThrowsException = true)] unsafe extern private static JobHandle ScheduleSpherecastBatch(ref JobsUtility.JobScheduleParameters parameters, void* commands, int commandLen, void* result, int resultLen, int minCommandsPerJob, int maxHits); } [NativeHeader("Modules/Physics/BatchCommands/CapsulecastCommand.h")] [NativeHeader("Runtime/Jobs/ScriptBindings/JobsBindingsTypes.h")] public partial struct CapsulecastCommand { public CapsulecastCommand(Vector3 p1, Vector3 p2, float radius, Vector3 direction, QueryParameters queryParameters, float distance = float.MaxValue) { this.point1 = p1; this.point2 = p2; this.direction = direction; this.radius = radius; this.distance = distance; this.physicsScene = Physics.defaultPhysicsScene; this.queryParameters = queryParameters; } public CapsulecastCommand(PhysicsScene physicsScene, Vector3 p1, Vector3 p2, float radius, Vector3 direction, QueryParameters queryParameters, float distance = float.MaxValue) { this.point1 = p1; this.point2 = p2; this.direction = direction; this.radius = radius; this.distance = distance; this.physicsScene = physicsScene; this.queryParameters = queryParameters; } public Vector3 point1 { get; set; } public Vector3 point2 { get; set; } public float radius {get; set; } public Vector3 direction {get; set; } public float distance { get; set; } public PhysicsScene physicsScene { get; set; } public QueryParameters queryParameters; public unsafe static JobHandle ScheduleBatch(NativeArray<CapsulecastCommand> commands, NativeArray<RaycastHit> results, int minCommandsPerJob, int maxHits, JobHandle dependsOn = new JobHandle()) { if (maxHits < 1) { Debug.LogWarning("maxHits should be greater than 0."); return new JobHandle(); } else if (results.Length < maxHits * commands.Length) { Debug.LogWarning("The supplied results buffer is too small, there should be at least maxHits space per each command in the batch."); return new JobHandle(); } var jobData = new BatchQueryJob<CapsulecastCommand, RaycastHit>(commands, results); var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), BatchQueryJobStruct<BatchQueryJob<CapsulecastCommand, RaycastHit>>.Initialize(), dependsOn, ScheduleMode.Parallel); return ScheduleCapsulecastBatch(ref scheduleParams, NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(commands), commands.Length, NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(results), results.Length, minCommandsPerJob, maxHits); } public unsafe static JobHandle ScheduleBatch(NativeArray<CapsulecastCommand> commands, NativeArray<RaycastHit> results, int minCommandsPerJob, JobHandle dependsOn = new JobHandle()) { return ScheduleBatch(commands, results, minCommandsPerJob, 1, dependsOn); } [FreeFunction("ScheduleCapsulecastCommandBatch", ThrowsException = true)] unsafe extern private static JobHandle ScheduleCapsulecastBatch(ref JobsUtility.JobScheduleParameters parameters, void* commands, int commandLen, void* result, int resultLen, int minCommandsPerJob, int maxHits); } [NativeHeader("Modules/Physics/BatchCommands/BoxcastCommand.h")] [NativeHeader("Runtime/Jobs/ScriptBindings/JobsBindingsTypes.h")] public partial struct BoxcastCommand { public BoxcastCommand(Vector3 center, Vector3 halfExtents, Quaternion orientation, Vector3 direction, QueryParameters queryParameters, float distance = float.MaxValue) { this.center = center; this.halfExtents = halfExtents; this.orientation = orientation; this.direction = direction; this.distance = distance; this.physicsScene = Physics.defaultPhysicsScene; this.queryParameters = queryParameters; } public BoxcastCommand(PhysicsScene physicsScene, Vector3 center, Vector3 halfExtents, Quaternion orientation, Vector3 direction, QueryParameters queryParameters, float distance = float.MaxValue) { this.center = center; this.halfExtents = halfExtents; this.orientation = orientation; this.direction = direction; this.distance = distance; this.physicsScene = physicsScene; this.queryParameters = queryParameters; } public Vector3 center { get; set; } public Vector3 halfExtents {get; set; } public Quaternion orientation {get; set; } public Vector3 direction {get; set; } public float distance { get; set; } public PhysicsScene physicsScene { get; set; } public QueryParameters queryParameters; public unsafe static JobHandle ScheduleBatch(NativeArray<BoxcastCommand> commands, NativeArray<RaycastHit> results, int minCommandsPerJob, int maxHits, JobHandle dependsOn = new JobHandle()) { if (maxHits < 1) { Debug.LogWarning("maxHits should be greater than 0."); return new JobHandle(); } else if (results.Length < maxHits * commands.Length) { Debug.LogWarning("The supplied results buffer is too small, there should be at least maxHits space per each command in the batch."); return new JobHandle(); } var jobData = new BatchQueryJob<BoxcastCommand, RaycastHit>(commands, results); var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), BatchQueryJobStruct<BatchQueryJob<BoxcastCommand, RaycastHit>>.Initialize(), dependsOn, ScheduleMode.Parallel); return ScheduleBoxcastBatch(ref scheduleParams, NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(commands), commands.Length, NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(results), results.Length, minCommandsPerJob, maxHits); } public unsafe static JobHandle ScheduleBatch(NativeArray<BoxcastCommand> commands, NativeArray<RaycastHit> results, int minCommandsPerJob, JobHandle dependsOn = new JobHandle()) { return ScheduleBatch(commands, results, minCommandsPerJob, 1, dependsOn); } [FreeFunction("ScheduleBoxcastCommandBatch", ThrowsException = true)] unsafe extern private static JobHandle ScheduleBoxcastBatch(ref JobsUtility.JobScheduleParameters parameters, void* commands, int commandLen, void* result, int resultLen, int minCommandsPerJob, int maxHits); } [NativeHeader("Modules/Physics/BatchCommands/ClosestPointCommand.h")] [NativeHeader("Runtime/Jobs/ScriptBindings/JobsBindingsTypes.h")] public struct ClosestPointCommand { public ClosestPointCommand(Vector3 point, int colliderInstanceID, Vector3 position, Quaternion rotation, Vector3 scale) { this.point = point; this.colliderInstanceID = colliderInstanceID; this.position = position; this.rotation = rotation; this.scale = scale; } public ClosestPointCommand(Vector3 point, Collider collider, Vector3 position, Quaternion rotation, Vector3 scale) { this.point = point; this.colliderInstanceID = collider.GetInstanceID(); this.position = position; this.rotation = rotation; this.scale = scale; } public Vector3 point { get; set; } public int colliderInstanceID { get; set; } public Vector3 position { get; set; } public Quaternion rotation { get; set; } public Vector3 scale { get; set; } public unsafe static JobHandle ScheduleBatch(NativeArray<ClosestPointCommand> commands, NativeArray<Vector3> results, int minCommandsPerJob, JobHandle dependsOn = new JobHandle()) { var jobData = new BatchQueryJob<ClosestPointCommand, Vector3>(commands, results); var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), BatchQueryJobStruct<BatchQueryJob<ClosestPointCommand, Vector3>>.Initialize(), dependsOn, ScheduleMode.Parallel); return ScheduleClosestPointCommandBatch(ref scheduleParams, NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(commands), commands.Length, NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(results), results.Length, minCommandsPerJob); } [FreeFunction("ScheduleClosestPointCommandBatch", ThrowsException = true)] unsafe extern private static JobHandle ScheduleClosestPointCommandBatch(ref JobsUtility.JobScheduleParameters parameters, void* commands, int commandLen, void* result, int resultLen, int minCommandsPerJob); } [NativeHeader("Modules/Physics/BatchCommands/OverlapSphereCommand.h")] public struct OverlapSphereCommand { public OverlapSphereCommand(Vector3 point, float radius, QueryParameters queryParameters) { this.point = point; this.radius = radius; this.queryParameters = queryParameters; this.physicsScene = Physics.defaultPhysicsScene; } public OverlapSphereCommand(PhysicsScene physicsScene, Vector3 point, float radius, QueryParameters queryParameters) { this.physicsScene = physicsScene; this.point = point; this.radius = radius; this.queryParameters = queryParameters; } public Vector3 point { get; set; } public float radius {get; set; } public PhysicsScene physicsScene { get; set; } public QueryParameters queryParameters; public unsafe static JobHandle ScheduleBatch(NativeArray<OverlapSphereCommand> commands, NativeArray<ColliderHit> results, int minCommandsPerJob, int maxHits, JobHandle dependsOn = new JobHandle()) { if (maxHits < 1) { Debug.LogWarning("maxHits should be greater than 0."); return new JobHandle(); } else if (results.Length < maxHits * commands.Length) { Debug.LogWarning("The supplied results buffer is too small, there should be at least maxHits space per each command in the batch."); return new JobHandle(); } var jobData = new BatchQueryJob<OverlapSphereCommand, ColliderHit>(commands, results); var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), BatchQueryJobStruct<BatchQueryJob<OverlapSphereCommand, ColliderHit>>.Initialize(), dependsOn, ScheduleMode.Parallel); return ScheduleOverlapSphereBatch(ref scheduleParams, NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(commands), commands.Length, NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(results), results.Length, minCommandsPerJob, maxHits); } [FreeFunction("ScheduleOverlapSphereCommandBatch", ThrowsException = true)] unsafe extern private static JobHandle ScheduleOverlapSphereBatch(ref JobsUtility.JobScheduleParameters parameters, void* commands, int commandLen, void* result, int resultLen, int minCommandsPerJob, int maxHits); } [NativeHeader("Modules/Physics/BatchCommands/OverlapBoxCommand.h")] public struct OverlapBoxCommand { public OverlapBoxCommand(Vector3 center, Vector3 halfExtents, Quaternion orientation, QueryParameters queryParameters) { this.center = center; this.halfExtents = halfExtents; this.orientation = orientation; this.queryParameters = queryParameters; this.physicsScene = Physics.defaultPhysicsScene; } public OverlapBoxCommand(PhysicsScene physicsScene, Vector3 center, Vector3 halfExtents, Quaternion orientation, QueryParameters queryParameters) { this.physicsScene = physicsScene; this.center = center; this.halfExtents = halfExtents; this.orientation = orientation; this.queryParameters = queryParameters; } public Vector3 center { get; set; } public Vector3 halfExtents { get; set; } public Quaternion orientation { get; set; } public PhysicsScene physicsScene { get; set; } public QueryParameters queryParameters; public unsafe static JobHandle ScheduleBatch(NativeArray<OverlapBoxCommand> commands, NativeArray<ColliderHit> results, int minCommandsPerJob, int maxHits, JobHandle dependsOn = new JobHandle()) { if (maxHits < 1) { Debug.LogWarning("maxHits should be greater than 0."); return new JobHandle(); } else if (results.Length < maxHits * commands.Length) { Debug.LogWarning("The supplied results buffer is too small, there should be at least maxHits space per each command in the batch."); return new JobHandle(); } var jobData = new BatchQueryJob<OverlapBoxCommand, ColliderHit>(commands, results); var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), BatchQueryJobStruct<BatchQueryJob<OverlapBoxCommand, ColliderHit>>.Initialize(), dependsOn, ScheduleMode.Parallel); return ScheduleOverlapBoxBatch(ref scheduleParams, NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(commands), commands.Length, NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(results), results.Length, minCommandsPerJob, maxHits); } [FreeFunction("ScheduleOverlapBoxCommandBatch", ThrowsException = true)] unsafe extern private static JobHandle ScheduleOverlapBoxBatch(ref JobsUtility.JobScheduleParameters parameters, void* commands, int commandLen, void* result, int resultLen, int minCommandsPerJob, int maxHits); } [NativeHeader("Modules/Physics/BatchCommands/OverlapCapsuleCommand.h")] public struct OverlapCapsuleCommand { public OverlapCapsuleCommand(Vector3 point0, Vector3 point1, float radius, QueryParameters queryParameters) { this.point0 = point0; this.point1 = point1; this.radius = radius; this.queryParameters = queryParameters; this.physicsScene = Physics.defaultPhysicsScene; } public OverlapCapsuleCommand(PhysicsScene physicsScene, Vector3 point0, Vector3 point1, float radius, QueryParameters queryParameters) { this.physicsScene = physicsScene; this.point0 = point0; this.point1 = point1; this.radius = radius; this.queryParameters = queryParameters; } public Vector3 point0 { get; set; } public Vector3 point1 { get; set; } public float radius { get; set; } public PhysicsScene physicsScene { get; set; } public QueryParameters queryParameters; public unsafe static JobHandle ScheduleBatch(NativeArray<OverlapCapsuleCommand> commands, NativeArray<ColliderHit> results, int minCommandsPerJob, int maxHits, JobHandle dependsOn = new JobHandle()) { if (maxHits < 1) { Debug.LogWarning("maxHits should be greater than 0."); return new JobHandle(); } else if (results.Length < maxHits * commands.Length) { Debug.LogWarning("The supplied results buffer is too small, there should be at least maxHits space per each command in the batch."); return new JobHandle(); } var jobData = new BatchQueryJob<OverlapCapsuleCommand, ColliderHit>(commands, results); var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), BatchQueryJobStruct<BatchQueryJob<OverlapCapsuleCommand, ColliderHit>>.Initialize(), dependsOn, ScheduleMode.Parallel); return ScheduleOverlapCapsuleBatch(ref scheduleParams, NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(commands), commands.Length, NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(results), results.Length, minCommandsPerJob, maxHits); } [FreeFunction("ScheduleOverlapCapsuleCommandBatch", ThrowsException = true)] unsafe extern private static JobHandle ScheduleOverlapCapsuleBatch(ref JobsUtility.JobScheduleParameters parameters, void* commands, int commandLen, void* result, int resultLen, int minCommandsPerJob, int maxHits); } }
UnityCsReference/Modules/Physics/ScriptBindings/QueryCommand.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Physics/ScriptBindings/QueryCommand.bindings.cs", "repo_id": "UnityCsReference", "token_count": 9221 }
431
// 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 UnityEditorInternal; using UnityEngine; using UnityEditor.AnimatedValues; namespace UnityEditor { [CanEditMultipleObjects] internal abstract class Collider2DEditorBase : Editor { protected class Styles { public static readonly GUIContent s_ColliderEditDisableHelp = EditorGUIUtility.TrTextContent("Collider cannot be edited because it is driven by SpriteRenderer's tiling properties."); public static readonly GUIContent s_AutoTilingLabel = EditorGUIUtility.TrTextContent("Auto Tiling ", " When enabled, the collider's shape will update automatically based on the SpriteRenderer's tiling properties"); } private SerializedProperty m_Density; private readonly AnimBool m_ShowDensity = new AnimBool(); private readonly AnimBool m_ShowLayerOverrides = new AnimBool(); private readonly AnimBool m_ShowInfo = new AnimBool(); private readonly AnimBool m_ShowContacts = new AnimBool(); Vector2 m_ContactScrollPosition; static ContactPoint2D[] m_Contacts = new ContactPoint2D[100]; private SavedBool m_ShowLayerOverridesFoldout; private SavedBool m_ShowInfoFoldout; private bool m_RequiresConstantRepaint; private SerializedProperty m_Material; private SerializedProperty m_IsTrigger; private SerializedProperty m_UsedByEffector; private SerializedProperty m_CompositeOperation; private SerializedProperty m_CompositeOrder; private SerializedProperty m_Offset; protected SerializedProperty m_AutoTiling; private SerializedProperty m_LayerOverridePriority; private SerializedProperty m_IncludeLayers; private SerializedProperty m_ExcludeLayers; private SerializedProperty m_ForceSendLayers; private SerializedProperty m_ForceReceiveLayers; private SerializedProperty m_ContactCaptureLayers; private SerializedProperty m_CallbackLayers; private readonly AnimBool m_ShowCompositeRedundants = new AnimBool(); public virtual void OnEnable() { EditMode.editModeStarted += OnEditModeStart; EditMode.editModeEnded += OnEditModeEnd; m_Density = serializedObject.FindProperty("m_Density"); m_ShowDensity.value = ShouldShowDensity(); m_ShowDensity.valueChanged.AddListener(Repaint); m_ShowLayerOverrides.valueChanged.AddListener(Repaint); m_ShowLayerOverridesFoldout = new SavedBool($"{target.GetType() }.ShowLayerOverridesFoldout", false); m_ShowLayerOverrides.value = m_ShowLayerOverridesFoldout.value; m_ShowInfo.valueChanged.AddListener(Repaint); m_ShowInfoFoldout = new SavedBool($"{target.GetType()}.ShowInfoFoldout", false); m_ShowInfo.value = m_ShowInfoFoldout.value; m_ShowContacts.valueChanged.AddListener(Repaint); m_ContactScrollPosition = Vector2.zero; m_Material = serializedObject.FindProperty("m_Material"); m_IsTrigger = serializedObject.FindProperty("m_IsTrigger"); m_UsedByEffector = serializedObject.FindProperty("m_UsedByEffector"); m_CompositeOperation = serializedObject.FindProperty("m_CompositeOperation"); m_CompositeOrder = serializedObject.FindProperty("m_CompositeOrder"); m_Offset = serializedObject.FindProperty("m_Offset"); m_AutoTiling = serializedObject.FindProperty("m_AutoTiling"); m_LayerOverridePriority = serializedObject.FindProperty("m_LayerOverridePriority"); m_IncludeLayers = serializedObject.FindProperty("m_IncludeLayers"); m_ExcludeLayers = serializedObject.FindProperty("m_ExcludeLayers"); m_ForceSendLayers = serializedObject.FindProperty("m_ForceSendLayers"); m_ForceReceiveLayers = serializedObject.FindProperty("m_ForceReceiveLayers"); m_ContactCaptureLayers = serializedObject.FindProperty("m_ContactCaptureLayers"); m_CallbackLayers = serializedObject.FindProperty("m_CallbackLayers"); m_ShowCompositeRedundants.value = !isUsedByComposite; m_ShowCompositeRedundants.valueChanged.AddListener(Repaint); m_RequiresConstantRepaint = false; } protected bool isUsedByComposite => ((Collider2D.CompositeOperation)m_CompositeOperation.enumValueIndex) != Collider2D.CompositeOperation.None; public virtual void OnDisable() { m_ShowDensity.valueChanged.RemoveListener(Repaint); m_ShowLayerOverrides.valueChanged.RemoveListener(Repaint); m_ShowInfo.valueChanged.RemoveListener(Repaint); m_ShowContacts.valueChanged.RemoveListener(Repaint); m_ShowCompositeRedundants.valueChanged.RemoveListener(Repaint); EditMode.editModeStarted -= OnEditModeStart; EditMode.editModeEnded -= OnEditModeEnd; } public override void OnInspectorGUI() { m_ShowCompositeRedundants.target = !isUsedByComposite; if (EditorGUILayout.BeginFadeGroup(m_ShowCompositeRedundants.faded)) { // Density property. m_ShowDensity.target = ShouldShowDensity(); if (EditorGUILayout.BeginFadeGroup(m_ShowDensity.faded)) EditorGUILayout.PropertyField(m_Density); EditorGUILayout.EndFadeGroup(); EditorGUILayout.PropertyField(m_Material); EditorGUILayout.PropertyField(m_IsTrigger); EditorGUILayout.PropertyField(m_UsedByEffector); } EditorGUILayout.EndFadeGroup(); if (m_AutoTiling != null) EditorGUILayout.PropertyField(m_AutoTiling, Styles.s_AutoTilingLabel); // Only show 'Composite Operation' if all targets are capable of being composited. if (targets.Count(x => (x as Collider2D).compositeCapable == false) == 0) { EditorGUILayout.PropertyField(m_CompositeOperation); if (isUsedByComposite) { EditorGUILayout.PropertyField(m_CompositeOrder); } } EditorGUILayout.PropertyField(m_Offset); } public void FinalizeInspectorGUI() { ShowLayerOverridesProperties(); ShowColliderInfoProperties(); // Check for collider error state. CheckColliderErrorState(); // If used-by-composite is enabled but there is not composite then show a warning. if (targets.Length == 1) { var collider = target as Collider2D; if (collider.isActiveAndEnabled && collider.composite == null && isUsedByComposite) EditorGUILayout.HelpBox("This collider will not function with a composite until there is a CompositeCollider2D on the GameObject that the attached Rigidbody2D is on.", MessageType.Warning); } // Check for effector warnings. Effector2DEditor.CheckEffectorWarnings(target as Collider2D); EndColliderInspector(); } private void ShowLayerOverridesProperties() { // Show Layer Overrides. m_ShowLayerOverridesFoldout.value = m_ShowLayerOverrides.target = EditorGUILayout.Foldout(m_ShowLayerOverrides.target, "Layer Overrides", true); if (EditorGUILayout.BeginFadeGroup(m_ShowLayerOverrides.faded)) { EditorGUI.indentLevel++; EditorGUILayout.PropertyField(m_LayerOverridePriority); EditorGUILayout.PropertyField(m_IncludeLayers); EditorGUILayout.PropertyField(m_ExcludeLayers); // Only show force send/receive if we're not dealing with triggers. if (targets.Count(x => (x as Collider2D).isTrigger) == 0) { EditorGUILayout.Space(); EditorGUILayout.PropertyField(m_ForceSendLayers); EditorGUILayout.PropertyField(m_ForceReceiveLayers); } EditorGUILayout.Space(); EditorGUILayout.PropertyField(m_ContactCaptureLayers); EditorGUILayout.PropertyField(m_CallbackLayers); EditorGUI.indentLevel--; } EditorGUILayout.EndFadeGroup(); } private void ShowColliderInfoProperties() { m_RequiresConstantRepaint = false; m_ShowInfoFoldout.value = m_ShowInfo.target = EditorGUILayout.Foldout(m_ShowInfo.target, "Info", true); if (EditorGUILayout.BeginFadeGroup(m_ShowInfo.faded)) { if (targets.Length == 1) { var collider = targets[0] as Collider2D; EditorGUI.BeginDisabledGroup(true); EditorGUILayout.ObjectField("Attached Body", collider.attachedRigidbody, typeof(Rigidbody2D), false); EditorGUILayout.FloatField("Friction", collider.friction); EditorGUILayout.FloatField("Bounciness", collider.bounciness); EditorGUILayout.FloatField("Shape Count", collider.shapeCount); if (collider.isActiveAndEnabled) EditorGUILayout.BoundsField("Bounds", collider.bounds); EditorGUI.EndDisabledGroup(); ShowContacts(collider); // We need to repaint as some of the above properties can change without causing a repaint. m_RequiresConstantRepaint = true; } else { EditorGUILayout.HelpBox("Cannot show Info properties when multiple colliders are selected.", MessageType.Info); } } EditorGUILayout.EndFadeGroup(); } bool ShouldShowDensity() { if (targets.Select(x => (x as Collider2D).attachedRigidbody).Distinct().Count() > 1) return false; var rigidbody = (target as Collider2D).attachedRigidbody; return rigidbody && rigidbody.useAutoMass && rigidbody.bodyType == RigidbodyType2D.Dynamic; } void ShowContacts(Collider2D collider) { EditorGUI.indentLevel++; m_ShowContacts.target = EditorGUILayout.Foldout(m_ShowContacts.target, "Contacts", true); if (EditorGUILayout.BeginFadeGroup(m_ShowContacts.faded)) { var contactCount = collider.GetContacts(m_Contacts); if (contactCount > 0) { m_ContactScrollPosition = EditorGUILayout.BeginScrollView(m_ContactScrollPosition, GUILayout.Height(180)); EditorGUI.BeginDisabledGroup(true); EditorGUILayout.IntField("Contact Count", contactCount); EditorGUILayout.Space(); for (var i = 0; i < contactCount; ++i) { var contact = m_Contacts[i]; EditorGUILayout.HelpBox(string.Format("Contact#{0}", i), MessageType.None); EditorGUI.indentLevel++; EditorGUILayout.Vector2Field("Point", contact.point); EditorGUILayout.Vector2Field("Normal", contact.normal); EditorGUILayout.Vector2Field("Relative Velocity", contact.relativeVelocity); EditorGUILayout.FloatField("Normal Impulse", contact.normalImpulse); EditorGUILayout.FloatField("Tangent Impulse", contact.tangentImpulse); EditorGUILayout.ObjectField("Collider", contact.collider, typeof(Collider2D), false); EditorGUILayout.ObjectField("Rigidbody", contact.rigidbody, typeof(Rigidbody2D), false); EditorGUILayout.ObjectField("OtherRigidbody", contact.otherRigidbody, typeof(Rigidbody2D), false); EditorGUI.indentLevel--; EditorGUILayout.Space(); } EditorGUI.EndDisabledGroup(); EditorGUILayout.EndScrollView(); } else { EditorGUILayout.HelpBox("No Contacts", MessageType.Info); } } EditorGUILayout.EndFadeGroup(); EditorGUI.indentLevel--; } internal override void OnForceReloadInspector() { base.OnForceReloadInspector(); // Whenever inspector get reloaded (reset, move up/down), quit the edit mode if was in editing mode. // Not sure why this pattern is used here but not for any other editors that implement edit mode button if (editingCollider) EditMode.QuitEditMode(); } protected void CheckColliderErrorState() { switch ((target as Collider2D).errorState) { case ColliderErrorState2D.NoShapes: // Show warning. EditorGUILayout.HelpBox("The collider did not create any collision shapes as they all failed verification. This could be because they were deemed too small or the vertices were too close. Vertices can also become close under certain rotations or very small scaling.", MessageType.Warning); break; case ColliderErrorState2D.RemovedShapes: // Show warning. EditorGUILayout.HelpBox("The collider created collision shape(s) but some were removed as they failed verification. This could be because they were deemed too small or the vertices were too close. Vertices can also become close under certain rotations or very small scaling.", MessageType.Warning); break; } } protected void BeginEditColliderInspector() { serializedObject.Update(); using (new EditorGUI.DisabledScope(targets.Length > 1)) { EditorGUILayout.EditorToolbarForTarget(EditorGUIUtility.TrTempContent("Edit Collider"), this); } } protected void EndColliderInspector() { serializedObject.ApplyModifiedProperties(); } protected bool CanEditCollider() { var e = targets.FirstOrDefault((x) => { var sr = (x as Component).GetComponent<SpriteRenderer>(); return (sr != null && sr.drawMode != SpriteDrawMode.Simple && m_AutoTiling.boolValue == true); } ); return e == false; } public override bool RequiresConstantRepaint() { return m_RequiresConstantRepaint; } protected virtual void OnEditStart() {} protected virtual void OnEditEnd() {} public bool editingCollider { get { return EditMode.editMode == EditMode.SceneViewEditMode.Collider && EditMode.IsOwner(this); } } protected virtual GUIContent editModeButton { get { return EditorGUIUtility.IconContent("EditCollider"); } } protected void InspectorEditButtonGUI() { EditMode.DoEditModeInspectorModeButton( EditMode.SceneViewEditMode.Collider, "Edit Collider", editModeButton, this ); } internal override Bounds GetWorldBoundsOfTarget(Object targetObject) { if (targetObject is Collider2D) return ((Collider2D)targetObject).bounds; else if (targetObject is Collider) return ((Collider)targetObject).bounds; else return base.GetWorldBoundsOfTarget(targetObject); } protected void OnEditModeStart(IToolModeOwner owner, EditMode.SceneViewEditMode mode) { if (mode == EditMode.SceneViewEditMode.Collider && owner == (IToolModeOwner)this) OnEditStart(); } protected void OnEditModeEnd(IToolModeOwner owner) { if (owner == (IToolModeOwner)this) OnEditEnd(); } } }
UnityCsReference/Modules/Physics2DEditor/Managed/Colliders/Collider2DEditorBase.cs/0
{ "file_path": "UnityCsReference/Modules/Physics2DEditor/Managed/Colliders/Collider2DEditorBase.cs", "repo_id": "UnityCsReference", "token_count": 7590 }
432
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEditor.AnimatedValues; namespace UnityEditor { /// <summary> /// Prompts the end-user to add 2D colliders if non exist for 2D effector to work with. /// </summary> [CustomEditor(typeof(PointEffector2D), true)] [CanEditMultipleObjects] internal class PointEffector2DEditor : Effector2DEditor { readonly AnimBool m_ShowForceRollout = new AnimBool(); SerializedProperty m_ForceMagnitude; SerializedProperty m_ForceVariation; SerializedProperty m_ForceSource; SerializedProperty m_ForceTarget; SerializedProperty m_ForceMode; SerializedProperty m_DistanceScale; static readonly AnimBool m_ShowDampingRollout = new AnimBool(); SerializedProperty m_Drag; SerializedProperty m_AngularDrag; public override void OnEnable() { base.OnEnable(); m_ShowForceRollout.value = true; m_ShowForceRollout.valueChanged.AddListener(Repaint); m_ForceMagnitude = serializedObject.FindProperty("m_ForceMagnitude"); m_ForceVariation = serializedObject.FindProperty("m_ForceVariation"); m_ForceSource = serializedObject.FindProperty("m_ForceSource"); m_ForceTarget = serializedObject.FindProperty("m_ForceTarget"); m_ForceMode = serializedObject.FindProperty("m_ForceMode"); m_DistanceScale = serializedObject.FindProperty("m_DistanceScale"); m_ShowDampingRollout.valueChanged.AddListener(Repaint); m_Drag = serializedObject.FindProperty("m_Drag"); m_AngularDrag = serializedObject.FindProperty("m_AngularDrag"); } public override void OnDisable() { base.OnDisable(); m_ShowForceRollout.valueChanged.RemoveListener(Repaint); m_ShowDampingRollout.valueChanged.RemoveListener(Repaint); } public override void OnInspectorGUI() { base.OnInspectorGUI(); serializedObject.Update(); // Force. m_ShowForceRollout.target = EditorGUILayout.Foldout(m_ShowForceRollout.target, "Force", true); if (EditorGUILayout.BeginFadeGroup(m_ShowForceRollout.faded)) { EditorGUILayout.PropertyField(m_ForceMagnitude); EditorGUILayout.PropertyField(m_ForceVariation); EditorGUILayout.PropertyField(m_DistanceScale); EditorGUILayout.PropertyField(m_ForceSource); EditorGUILayout.PropertyField(m_ForceTarget); EditorGUILayout.PropertyField(m_ForceMode); EditorGUILayout.Space(); } EditorGUILayout.EndFadeGroup(); // Drag. m_ShowDampingRollout.target = EditorGUILayout.Foldout(m_ShowDampingRollout.target, "Damping", true); if (EditorGUILayout.BeginFadeGroup(m_ShowDampingRollout.faded)) { EditorGUILayout.PropertyField(m_Drag); EditorGUILayout.PropertyField(m_AngularDrag); } EditorGUILayout.EndFadeGroup(); serializedObject.ApplyModifiedProperties(); } } }
UnityCsReference/Modules/Physics2DEditor/Managed/Effectors/PointEffector2DEditor.cs/0
{ "file_path": "UnityCsReference/Modules/Physics2DEditor/Managed/Effectors/PointEffector2DEditor.cs", "repo_id": "UnityCsReference", "token_count": 1496 }
433
// 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 { // Object used as a context to handle state changes and undo/redo operations. internal class Physics2DPreferenceState : ScriptableObject { public class SettingsContent { public static readonly GUIContent ColliderAwakeOutlineContent = EditorGUIUtility.TrTextContent("Awake Color (Outline)"); public static readonly GUIContent ColliderAsleepOutlineContent = EditorGUIUtility.TrTextContent("Asleep Color (Outline)"); public static readonly GUIContent ColliderAwakeFilledContent = EditorGUIUtility.TrTextContent("Awake Color (Filled)"); public static readonly GUIContent ColliderAsleepFilledContent = EditorGUIUtility.TrTextContent("Asleep Color (Filled)"); public static readonly GUIContent ColliderBoundsContent = EditorGUIUtility.TrTextContent("Bounds Color"); public static readonly GUIContent CompositedColorContent = EditorGUIUtility.TrTextContent("Composited Color"); public static readonly GUIContent ColliderContactContent = EditorGUIUtility.TrTextContent("Contact Color"); public static readonly GUIContent ContactArrowScaleContent = EditorGUIUtility.TrTextContent("Contact Arrow Scale"); public static readonly GUIContent CollidersLabelContent = EditorGUIUtility.TrTextContent("Colliders"); public static readonly GUIContent ContactsLabelContent = EditorGUIUtility.TrTextContent("Contacts"); } // These must match "GizmoDrawing.cpp" for the Physics2DEditor! const string UniqueSettingsKey = "UnityEditor.U2D.Physics/"; const string ColliderAwakeOutlineColorKey = UniqueSettingsKey + "ColliderAwakeOutlineColor"; const string ColliderAsleepOutlineColorKey = UniqueSettingsKey + "ColliderAsleepOutlineColor"; const string ColliderAwakeFilledColorKey = UniqueSettingsKey + "ColliderAwakeFilledColor"; const string ColliderAsleepFilledColorKey = UniqueSettingsKey + "ColliderAsleepFilledColor"; const string ColliderBoundsColorKey = UniqueSettingsKey + "ColliderBoundsColor"; const string ColliderContactColorKey = UniqueSettingsKey + "ColliderContactColor"; const string CompositedColorKey = UniqueSettingsKey + "CompositedColor"; const string ContactArrowScaleKey = UniqueSettingsKey + "ContactArrowScale"; // These must match "GizmoDrawing.cpp" for the Physics2DEditor! static readonly Color DefaultColliderAwakeOutlineColor = new Color(0.568f, 0.956f, 0.545f, 1.0f); static readonly Color DefaultColliderAsleepOutlineColor = new Color(0.254f, 0.501f, 0.243f, 1.0f); static readonly Color DefaultColliderAwakeFilledColor = new Color(0.568f, 0.956f, 0.545f, 0.2f); static readonly Color DefaultColliderAsleepFilledColor = new Color(0.254f, 0.501f, 0.243f, 0.2f); static readonly Color DefaultColliderBoundsColor = new Color(1.0f, 1.0f, 0.0f, 0.75f); static readonly Color DefaultColliderContactColor = new Color(1.0f, 0.0f, 1.0f, 1.0f); static readonly Color DefaultCompositedColor = new Color(1.0f, 1.0f, 1.0f, 0.1f); static readonly float DefaultContactArrowScale = 0.2f; // Preference state. public Color colliderAwakeOutlineColor; public Color colliderAwakeFilledColor; public Color colliderAsleepOutlineColor; public Color colliderAsleepFilledColor; public Color colliderBoundsColor; public Color colliderContactColor; public Color compositedColor; public float contactArrowScale; void OnEnable() { // We only want it as a undo/redo context associated with nothing else. hideFlags = HideFlags.HideAndDontSave; ReadPreferenceState(); // Register to be notified of undo/redo. Undo.undoRedoEvent += OnUndoRedo; } void OnDisable() { // Remove any undo for the preference state. Undo.ClearUndo(this); // Unregister undo/redo notifications. Undo.undoRedoEvent -= OnUndoRedo; } private void OnUndoRedo(in UndoRedoInfo info) { WritePreferenceState(); } private void ReadPreferenceState() { // Read the preference state. colliderAwakeOutlineColor = GetColor(ColliderAwakeOutlineColorKey, DefaultColliderAwakeOutlineColor); colliderAwakeFilledColor = GetColor(ColliderAwakeFilledColorKey, DefaultColliderAwakeFilledColor); colliderAsleepOutlineColor = GetColor(ColliderAsleepOutlineColorKey, DefaultColliderAsleepOutlineColor); colliderAsleepFilledColor = GetColor(ColliderAsleepFilledColorKey, DefaultColliderAsleepFilledColor); colliderBoundsColor = GetColor(ColliderBoundsColorKey, DefaultColliderBoundsColor); colliderContactColor = GetColor(ColliderContactColorKey, DefaultColliderContactColor); compositedColor = GetColor(CompositedColorKey, DefaultCompositedColor); contactArrowScale = EditorPrefs.GetFloat(ContactArrowScaleKey, DefaultContactArrowScale); } private void WritePreferenceState() { // Wriute the preference state. SetColor(ColliderAwakeOutlineColorKey, colliderAwakeOutlineColor); SetColor(ColliderAwakeFilledColorKey, colliderAwakeFilledColor); SetColor(ColliderAsleepOutlineColorKey, colliderAsleepOutlineColor); SetColor(ColliderAsleepFilledColorKey, colliderAsleepFilledColor); SetColor(ColliderBoundsColorKey, colliderBoundsColor); SetColor(ColliderContactColorKey, colliderContactColor); SetColor(CompositedColorKey, compositedColor); EditorPrefs.SetFloat(ContactArrowScaleKey, contactArrowScale); } // Handle the UI. public void HandleUI(string searchContext) { // Collider Preferences. EditorGUILayout.LabelField(SettingsContent.CollidersLabelContent, EditorStyles.boldLabel); { // Collider Awake Outline Color. { EditorGUI.BeginChangeCheck(); var color = EditorGUILayout.ColorField(SettingsContent.ColliderAwakeOutlineContent, colliderAwakeOutlineColor); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(this, SettingsContent.ColliderAwakeOutlineContent.text); SetColor(ColliderAwakeOutlineColorKey, colliderAwakeOutlineColor = color); } } // Collider Awake Filled Color. { EditorGUI.BeginChangeCheck(); var color = EditorGUILayout.ColorField(SettingsContent.ColliderAwakeFilledContent, colliderAwakeFilledColor); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(this, SettingsContent.ColliderAwakeFilledContent.text); SetColor(ColliderAwakeFilledColorKey, colliderAwakeFilledColor = color); } } // Collider Asleep Outline Color. { EditorGUI.BeginChangeCheck(); var color = EditorGUILayout.ColorField(SettingsContent.ColliderAsleepOutlineContent, colliderAsleepOutlineColor); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(this, SettingsContent.ColliderAsleepOutlineContent.text); SetColor(ColliderAsleepOutlineColorKey, colliderAsleepOutlineColor = color); } } // Collider Asleep Filled Color. { EditorGUI.BeginChangeCheck(); var color = EditorGUILayout.ColorField(SettingsContent.ColliderAsleepFilledContent, colliderAsleepFilledColor); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(this, SettingsContent.ColliderAsleepFilledContent.text); SetColor(ColliderAsleepFilledColorKey, colliderAsleepFilledColor = color); } } // Collider Bounds Color. { EditorGUI.BeginChangeCheck(); var color = EditorGUILayout.ColorField(SettingsContent.ColliderBoundsContent, colliderBoundsColor); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(this, SettingsContent.ColliderBoundsContent.text); SetColor(ColliderBoundsColorKey, colliderBoundsColor = color); } } // Composited Color. { EditorGUI.BeginChangeCheck(); var color = EditorGUILayout.ColorField(SettingsContent.CompositedColorContent, compositedColor); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(this, SettingsContent.CompositedColorContent.text); SetColor(CompositedColorKey, compositedColor = color); } } } EditorGUILayout.Space(); // Show Contact Preferences. EditorGUILayout.LabelField(SettingsContent.ContactsLabelContent, EditorStyles.boldLabel); { // Collider Contact Color. { EditorGUI.BeginChangeCheck(); var color = EditorGUILayout.ColorField(SettingsContent.ColliderContactContent, colliderContactColor); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(this, SettingsContent.ColliderContactContent.text); SetColor(ColliderContactColorKey, colliderContactColor = color); } } // Contact Arrow Scale. { EditorGUI.BeginChangeCheck(); var scale = EditorGUILayout.Slider(SettingsContent.ContactArrowScaleContent, contactArrowScale, 0.1f, 1f); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(this, SettingsContent.ColliderContactContent.text); EditorPrefs.SetFloat(ContactArrowScaleKey, contactArrowScale = scale); } } } GUILayout.FlexibleSpace(); if (GUILayout.Button("Set Defaults")) { Undo.RecordObject(this, "Physics2DPreferences.SetDefaults"); SetColor(ColliderAwakeOutlineColorKey, colliderAwakeOutlineColor = DefaultColliderAwakeOutlineColor); SetColor(ColliderAwakeFilledColorKey, colliderAwakeFilledColor = DefaultColliderAwakeFilledColor); SetColor(ColliderAsleepOutlineColorKey, colliderAsleepOutlineColor = DefaultColliderAsleepOutlineColor); SetColor(ColliderAsleepFilledColorKey, colliderAsleepFilledColor = DefaultColliderAsleepFilledColor); SetColor(ColliderBoundsColorKey, colliderBoundsColor = DefaultColliderBoundsColor); SetColor(ColliderContactColorKey, colliderContactColor = DefaultColliderContactColor); SetColor(CompositedColorKey, compositedColor = DefaultCompositedColor); EditorPrefs.SetFloat(ContactArrowScaleKey, contactArrowScale = DefaultContactArrowScale); } } private Color GetColor(string key, Color defaultColor) { return new Color( EditorPrefs.GetFloat(key + "_r", defaultColor.r), EditorPrefs.GetFloat(key + "_g", defaultColor.g), EditorPrefs.GetFloat(key + "_b", defaultColor.b), EditorPrefs.GetFloat(key + "_a", defaultColor.a)); } private void SetColor(string key, Color color) { EditorPrefs.SetFloat(key + "_r", color.r); EditorPrefs.SetFloat(key + "_g", color.g); EditorPrefs.SetFloat(key + "_b", color.b); EditorPrefs.SetFloat(key + "_a", color.a); } } internal class Physics2DPreferences : SettingsProvider { private Physics2DPreferenceState m_PreferenceState; [SettingsProvider] private static SettingsProvider CreateSettingsProvider() { return new Physics2DPreferences(); } public Physics2DPreferences() : base("Preferences/2D/Physics", SettingsScope.User, GetSearchKeywordsFromGUIContentProperties<Physics2DPreferenceState.SettingsContent>()) {} // Provider activate. public override void OnActivate(string searchContext, VisualElement rootElement) { // Create the preference states. m_PreferenceState = ScriptableObject.CreateInstance<Physics2DPreferenceState>(); // Hook-up the UI handling. guiHandler = searchContext => { using (new SettingsWindow.GUIScope()) m_PreferenceState.HandleUI(searchContext); }; base.OnActivate(searchContext, rootElement); } // Provider deactivate. public override void OnDeactivate() { base.OnDeactivate(); // Remove the preference state. Object.DestroyImmediate(m_PreferenceState); } } }
UnityCsReference/Modules/Physics2DEditor/Managed/Settings/Physics2DPreferences.cs/0
{ "file_path": "UnityCsReference/Modules/Physics2DEditor/Managed/Settings/Physics2DPreferences.cs", "repo_id": "UnityCsReference", "token_count": 6123 }
434
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Net.Mime; using UnityEngine; namespace UnityEditor { [CustomEditor(typeof(MeshCollider))] [CanEditMultipleObjects] internal class MeshColliderEditor : Collider3DEditorBase { private SerializedProperty m_Mesh; private SerializedProperty m_Convex; private SerializedProperty m_CookingOptions; private static class Styles { public static readonly GUIContent isTriggerText = EditorGUIUtility.TrTextContent("Is Trigger", "Is this collider a trigger? Triggers are only supported on convex colliders."); public static readonly GUIContent convexText = EditorGUIUtility.TrTextContent("Convex", "Is this collider convex?"); public static readonly GUIContent cookingOptionsText = EditorGUIUtility.TrTextContent("Cooking Options", "Options affecting the result of the mesh processing by the physics engine."); public static readonly GUIContent meshText = EditorGUIUtility.TrTextContent("Mesh", "Reference to the Mesh to use for collisions."); } public override void OnEnable() { base.OnEnable(); m_Mesh = serializedObject.FindProperty("m_Mesh"); m_Convex = serializedObject.FindProperty("m_Convex"); m_CookingOptions = serializedObject.FindProperty("m_CookingOptions"); } private MeshColliderCookingOptions GetCookingOptions() { return (MeshColliderCookingOptions)m_CookingOptions.intValue; } private void SetCookingOptions(MeshColliderCookingOptions cookingOptions) { m_CookingOptions.intValue = (int)cookingOptions; } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(m_Convex, Styles.convexText); if (EditorGUI.EndChangeCheck() && m_Convex.boolValue == false) { m_IsTrigger.boolValue = false; } EditorGUI.indentLevel++; using (new EditorGUI.DisabledScope(!m_Convex.boolValue)) { EditorGUILayout.PropertyField(m_IsTrigger, Styles.isTriggerText); } EditorGUI.indentLevel--; EditorGUILayout.PropertyField(m_ProvidesContacts, BaseStyles.providesContacts); using (var horizontal = new EditorGUILayout.HorizontalScope()) { using (var propertyScope = new EditorGUI.PropertyScope(horizontal.rect, GUIContent.none, m_CookingOptions)) { EditorGUI.BeginChangeCheck(); var newOptions = (MeshColliderCookingOptions)EditorGUILayout.EnumFlagsField(Styles.cookingOptionsText, GetCookingOptions()); if (EditorGUI.EndChangeCheck()) SetCookingOptions(newOptions); } } EditorGUILayout.PropertyField(m_Material, BaseStyles.materialContent); EditorGUILayout.PropertyField(m_Mesh, Styles.meshText); ShowLayerOverridesProperties(); serializedObject.ApplyModifiedProperties(); } } }
UnityCsReference/Modules/PhysicsEditor/MeshColliderEditor.cs/0
{ "file_path": "UnityCsReference/Modules/PhysicsEditor/MeshColliderEditor.cs", "repo_id": "UnityCsReference", "token_count": 1421 }
435
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor.IMGUI.Controls; using UnityEngine; namespace UnityEditor.Presets { class AddPresetTypeGUI : AdvancedDropdownGUI { private static class Styles { public static GUIStyle itemStyle = "DD LargeItemStyle"; } private Vector2 m_IconSize = new Vector2(16, 16); internal override Vector2 iconSize => m_IconSize; internal override GUIStyle lineStyle => Styles.itemStyle; public AddPresetTypeGUI(AdvancedDropdownDataSource dataSource) : base(dataSource) { } internal override void DrawItem(AdvancedDropdownItem item, string name, Texture2D icon, bool enabled, bool drawArrow, bool selected, bool hasSearch) { if (hasSearch && item is PresetTypeDropdownItem) { name = ((PresetTypeDropdownItem)item).searchableName; } base.DrawItem(item, name, icon, enabled, drawArrow, selected, hasSearch); } internal override string DrawSearchFieldControl(string searchString) { float padding = 8f; m_SearchRect = GUILayoutUtility.GetRect(0, 0); m_SearchRect.x += padding; m_SearchRect.y = 7; m_SearchRect.width -= padding * 2; m_SearchRect.height = 30; var newSearch = EditorGUI.SearchField(m_SearchRect, searchString); return newSearch; } } }
UnityCsReference/Modules/PresetsEditor/AddPresetTypeWindow/AddPresetTypeGUI.cs/0
{ "file_path": "UnityCsReference/Modules/PresetsEditor/AddPresetTypeWindow/AddPresetTypeGUI.cs", "repo_id": "UnityCsReference", "token_count": 667 }
436
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor; namespace Unity.Profiling.Memory.Editor { /// <summary> /// Memory profiler compilation guard to prevent starting of captures during the compilation process. /// </summary> internal static class MemoryProfilerCompilationGuard { [InitializeOnLoadMethod] public static void InjectCompileGuard() { UnityEditor.Compilation.CompilationPipeline.compilationStarted += MemoryProfiler.StartedCompilationCallback; UnityEditor.Compilation.CompilationPipeline.compilationFinished += MemoryProfiler.FinishedCompilationCallback; } } }
UnityCsReference/Modules/ProfilerEditor/MemoryProfiler/MemoryProfilerCompilationGuard.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/MemoryProfiler/MemoryProfilerCompilationGuard.cs", "repo_id": "UnityCsReference", "token_count": 254 }
437
// 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 Unity.Profiling.Editor { interface IProfilerPersistentSettingsService : IDisposable { bool IsBottleneckViewVisible { get; set; } ulong TargetFrameDurationNs { get; set; } int MaximumFrameCount { get; } event Action TargetFrameDurationChanged; event Action MaximumFrameCountChanged; } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/Bottlenecks/Data/IProfilerPersistentSettingsService.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/Bottlenecks/Data/IProfilerPersistentSettingsService.cs", "repo_id": "UnityCsReference", "token_count": 177 }
438
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine.UIElements; namespace UnityEditor.Profiling.ModuleEditor { class DragIndicator : VisualElement { const string k_UssClass_DragIndicatorContainer = "drag-indicator"; const string k_UssClass_DragIndicatorLine = "drag-indicator__line"; const string k_UssClass_DragIndicatorLineSpacer = "drag-indicator__line-spacer"; const int k_DraggableIconLineCount = 3; public DragIndicator() { AddToClassList(k_UssClass_DragIndicatorContainer); for (int i = 0; i < k_DraggableIconLineCount; i++) { var line = new VisualElement(); line.AddToClassList(k_UssClass_DragIndicatorLine); Add(line); if (i < (k_DraggableIconLineCount - 1)) { var lineSpacer = new VisualElement(); lineSpacer.AddToClassList(k_UssClass_DragIndicatorLineSpacer); Add(lineSpacer); } } } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ModuleEditor/Views/DragIndicator.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ModuleEditor/Views/DragIndicator.cs", "repo_id": "UnityCsReference", "token_count": 562 }
439
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using Unity.Profiling; using Unity.Profiling.Editor; using UnityEditor; using UnityEngine; using UnityEngine.Profiling; using System.Collections.Generic; using UnityEditor.Profiling; namespace UnityEditorInternal.Profiling { [Serializable] [ProfilerModuleMetadata("Physics (2D)", typeof(LocalizationResource), IconPath = "Profiler.Physics2D")] internal class Physics2DProfilerModule : ProfilerModuleBase { // Styles used to display the alternating background in the detail view. private static class DefaultStyles { public static GUIStyle backgroundEven = "OL EntryBackEven"; public static GUIStyle backgroundOdd = "OL EntryBackOdd"; } // The profiler view to use. private enum PhysicsProfilerStatsView { Legacy = 0, Current = 1 } private PhysicsProfilerStatsView m_ShowStatsView; private PhysicsProfilerStatsView m_CachedShowStatsView; static Physics2DProfilerModule() { k_CurrentPhysicsAreaCounterNames = new ProfilerCounterData[] { new ProfilerCounterData() { m_Name = "Total Contacts", m_Category = k_Physics2DCategoryName, }, new ProfilerCounterData() { m_Name = "Total Shapes", m_Category = k_Physics2DCategoryName, }, new ProfilerCounterData() { m_Name = "Total Queries", m_Category = k_Physics2DCategoryName, }, new ProfilerCounterData() { m_Name = "Total Callbacks", m_Category = k_Physics2DCategoryName, }, new ProfilerCounterData() { m_Name = "Total Joints", m_Category = k_Physics2DCategoryName, }, new ProfilerCounterData() { m_Name = "Total Bodies", m_Category = k_Physics2DCategoryName, }, new ProfilerCounterData() { m_Name = "Awake Bodies", m_Category = k_Physics2DCategoryName, }, new ProfilerCounterData() { m_Name = "Dynamic Bodies", m_Category = k_Physics2DCategoryName, }, new ProfilerCounterData() { m_Name = "Continuous Bodies", m_Category = k_Physics2DCategoryName, }, new ProfilerCounterData() { m_Name = "Physics Used Memory (2D)", m_Category = k_MemoryCategoryName, } }; k_LegacyPhysicsAreaCounterNames = new ProfilerCounterData[] { new ProfilerCounterData() { m_Name = "Total Bodies", m_Category = k_Physics2DCategoryName, }, new ProfilerCounterData() { m_Name = "Active Bodies", m_Category = k_Physics2DCategoryName, }, new ProfilerCounterData() { m_Name = "Sleeping Bodies", m_Category = k_Physics2DCategoryName, }, new ProfilerCounterData() { m_Name = "Dynamic Bodies", m_Category = k_Physics2DCategoryName, }, new ProfilerCounterData() { m_Name = "Kinematic Bodies", m_Category = k_Physics2DCategoryName, }, new ProfilerCounterData() { m_Name = "Static Bodies", m_Category = k_Physics2DCategoryName, }, new ProfilerCounterData() { m_Name = "Contacts", m_Category = k_Physics2DCategoryName, } }; } // Current Counters to display. static readonly ProfilerCounterData[] k_CurrentPhysicsAreaCounterNames; // Legacy Counters to display. static readonly ProfilerCounterData[] k_LegacyPhysicsAreaCounterNames; const int k_DefaultOrderIndex = 7; private static readonly ushort k_Physics2DCategoryId = ProfilerCategory.Physics2D; private static readonly string k_Physics2DCategoryName = ProfilerCategory.Physics2D.Name; private static readonly string k_MemoryCategoryName = ProfilerCategory.Memory.Name; private static int k_labelWidthTitle = 150; private static int k_labelWidthDetail = 160; // Profiler module overrides. internal override ProfilerArea area => ProfilerArea.Physics2D; public override bool usesCounters => false; private protected override int defaultOrderIndex => k_DefaultOrderIndex; private protected override string legacyPreferenceKey => "ProfilerChartPhysics2D"; private Dictionary<string, int> m_Markers; // Storage for retrieved samples. private struct SampleData { public float timeMs; public int count; public override string ToString() { return string.Format("{0:0.00} ms [{1}]", timeMs, count); } } internal override void OnEnable() { m_ShowStatsView = PhysicsProfilerStatsView.Current; ProfilerDriver.profileLoaded += OnLoadProfileData; LegacyModuleInitialize(); base.OnEnable(); } internal override void OnDisable() { ProfilerDriver.profileLoaded -= OnLoadProfileData; m_Markers = null; base.OnDisable(); } private void OnLoadProfileData() { using (var frameData = ProfilerDriver.GetRawFrameDataView(ProfilerWindow.GetActiveVisibleFrameIndex(), 0)) { if (frameData.valid) { var physicsQueries = GetCounterValue(frameData, "Total Queries"); if (physicsQueries != -1) { m_ShowStatsView = PhysicsProfilerStatsView.Current; } else { m_ShowStatsView = PhysicsProfilerStatsView.Legacy; } } } } private void InitializeMarkers(RawFrameDataView frameData) { // Fetch all the markers. var markerInfo = new List<FrameDataView.MarkerInfo>(); frameData.GetMarkers(markerInfo); // Assign the markers. m_Markers = new Dictionary<string, int>(64); foreach(var marker in markerInfo) { if (marker.category == k_Physics2DCategoryId) m_Markers.Add(marker.name, marker.id); } } private long GetPhysicsCounterValue(RawFrameDataView frameData, string markerName) { // Find the marker. if (m_Markers.TryGetValue(markerName, out int markerId)) return frameData.GetCounterValueAsLong(markerId); // Indicate bad value! return -1; } private SampleData GetPhysicsSampleData(RawFrameDataView frameData, string markerName) { SampleData sampleData = default; // Find the marker. if (m_Markers.TryGetValue(markerName, out int markerId)) { for (var i = 0; i < frameData.sampleCount; ++i) { // Ignore if it's not the marker we want. if (markerId != frameData.GetSampleMarkerId(i)) continue; // Accumulate sample data. sampleData.timeMs += frameData.GetSampleTimeMs(i); sampleData.count++; } } return sampleData; } private void UpdatePhysicsChart() { if (m_ShowStatsView == PhysicsProfilerStatsView.Current) { InternalSetChartCounters(ProfilerCounterDataUtility.ConvertFromLegacyCounterDatas( new List<ProfilerCounterData>(k_CurrentPhysicsAreaCounterNames))); } else { m_ShowStatsView = PhysicsProfilerStatsView.Legacy; InternalSetChartCounters(ProfilerCounterDataUtility.ConvertFromLegacyCounterDatas( new List<ProfilerCounterData>(k_LegacyPhysicsAreaCounterNames))); } RebuildChart(); } private void DrawAlternateBackground(Rect region, Vector2 scrollPosition, int rowCount) { // Only draw if repainting. if (Event.current.rawType != EventType.Repaint) return; // Fetch the label height. var labelHeight = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; // Draw the selected rows. for (int row = 0; row < rowCount; ++row) { // Only draw alternate rows. if (row % 2 == 1) continue; // Calculate and draw the row. var rowRect = new Rect(region.x + scrollPosition.x, region.y + ((row-1) * labelHeight), region.width, labelHeight); DefaultStyles.backgroundEven.Draw(rowRect, false, false, false, false); } } protected override List<ProfilerCounterData> CollectDefaultChartCounters() { if (m_ShowStatsView == PhysicsProfilerStatsView.Current) return new List<ProfilerCounterData>(k_CurrentPhysicsAreaCounterNames); return new List<ProfilerCounterData>(k_LegacyPhysicsAreaCounterNames); } public override void DrawToolbar(Rect position) { EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); m_ShowStatsView = (PhysicsProfilerStatsView)EditorGUILayout.EnumPopup(m_ShowStatsView, EditorStyles.toolbarDropDownLeft, GUILayout.Width(70f)); if (m_CachedShowStatsView != m_ShowStatsView) { m_CachedShowStatsView = m_ShowStatsView; UpdatePhysicsChart(); } GUILayout.Space(5f); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); } public override void DrawDetailsView(Rect position) { m_PaneScroll = GUILayout.BeginScrollView(m_PaneScroll, ProfilerWindow.Styles.background); using (var frameData = ProfilerDriver.GetRawFrameDataView(ProfilerWindow.GetActiveVisibleFrameIndex(), 0)) { if (frameData.valid) { // Initialize the profiler markers. InitializeMarkers(frameData); bool newCountersAvailable = GetPhysicsCounterValue(frameData, "Total Queries") != -1; if (m_ShowStatsView == PhysicsProfilerStatsView.Current) { // Determine if the new counters are available by looking for a counter only available there. if (newCountersAvailable) { // Draw an alternate lined background to make following metrics on the same line easier. DrawAlternateBackground(position, m_PaneScroll, 10); long physicsMemoryUsed = GetCounterValue(frameData, "Physics Used Memory (2D)"); long totalUsedMemory = GetCounterValue(frameData, "Total Used Memory"); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Physics Used Memory", GUILayout.Width(k_labelWidthTitle)); EditorGUILayout.LabelField("| Total: " + GetCounterValueAsBytes(frameData, "Physics Used Memory (2D)"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField(string.Format("| Relative: {0:p2}", (float)physicsMemoryUsed / (float)totalUsedMemory), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Bodies", GUILayout.Width(k_labelWidthTitle)); EditorGUILayout.LabelField("| Total: " + GetPhysicsCounterValue(frameData, "Total Bodies"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Awake: " + GetPhysicsCounterValue(frameData, "Awake Bodies"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Asleep: " + GetPhysicsCounterValue(frameData, "Asleep Bodies"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Dynamic: " + GetPhysicsCounterValue(frameData, "Dynamic Bodies"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Kinematic: " + GetPhysicsCounterValue(frameData, "Kinematic Bodies"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Static: " + GetPhysicsCounterValue(frameData, "Static Bodies"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Discrete: " + GetPhysicsCounterValue(frameData, "Discrete Bodies"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Continuous: " + GetPhysicsCounterValue(frameData, "Continuous Bodies"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Shapes", GUILayout.Width(k_labelWidthTitle)); EditorGUILayout.LabelField("| Total: " + GetPhysicsCounterValue(frameData, "Total Shapes"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Awake: " + GetPhysicsCounterValue(frameData, "Awake Shapes"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Asleep: " + GetPhysicsCounterValue(frameData, "Asleep Shapes"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Dynamic: " + GetPhysicsCounterValue(frameData, "Dynamic Shapes"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Kinematic: " + GetPhysicsCounterValue(frameData, "Kinematic Shapes"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Static: " + GetPhysicsCounterValue(frameData, "Static Shapes"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Queries", GUILayout.Width(k_labelWidthTitle)); EditorGUILayout.LabelField("| Total: " + GetPhysicsCounterValue(frameData, "Total Queries"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Raycast: " + GetPhysicsCounterValue(frameData, "Raycast Queries"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Shapecast: " + GetPhysicsCounterValue(frameData, "Shapecast Queries"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Overlap: " + GetPhysicsCounterValue(frameData, "Overlap Queries"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| IsTouching: " + GetPhysicsCounterValue(frameData, "IsTouching Queries"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| GetContacts: " + GetPhysicsCounterValue(frameData, "GetContacts Queries"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Particle: " + GetPhysicsCounterValue(frameData, "Particle Queries"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Contacts", GUILayout.Width(k_labelWidthTitle)); EditorGUILayout.LabelField("| Total: " + GetPhysicsCounterValue(frameData, "Total Contacts"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Added: " + GetPhysicsCounterValue(frameData, "Added Contacts"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Removed: " + GetPhysicsCounterValue(frameData, "Removed Contacts"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Broadphase Updates: " + GetPhysicsCounterValue(frameData, "Broadphase Updates"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Broadphase Pairs: " + GetPhysicsCounterValue(frameData, "Broadphase Pairs"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Callbacks", GUILayout.Width(k_labelWidthTitle)); EditorGUILayout.LabelField("| Total: " + GetPhysicsCounterValue(frameData, "Total Callbacks"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Collision Enter: " + GetPhysicsCounterValue(frameData, "Collision Enter"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Collision Stay: " + GetPhysicsCounterValue(frameData, "Collision Stay"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Collision Exit: " + GetPhysicsCounterValue(frameData, "Collision Exit"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Trigger Enter: " + GetPhysicsCounterValue(frameData, "Trigger Enter"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Trigger Stay: " + GetPhysicsCounterValue(frameData, "Trigger Stay"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Trigger Exit: " + GetPhysicsCounterValue(frameData, "Trigger Exit"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Solver", GUILayout.Width(k_labelWidthTitle)); EditorGUILayout.LabelField("| World Count: " + GetPhysicsCounterValue(frameData, "Solver World Count"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Simulation Count: " + GetPhysicsCounterValue(frameData, "Solver Simulation Count"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Discrete Islands: " + GetPhysicsCounterValue(frameData, "Solver Discrete Islands"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Continuous Islands: " + GetPhysicsCounterValue(frameData, "Solver Continuous Islands"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Transform Sync", GUILayout.Width(k_labelWidthTitle)); EditorGUILayout.LabelField("| Sync Calls: " + GetPhysicsCounterValue(frameData, "Total Transform Sync Calls"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Sync Bodies: " + GetPhysicsCounterValue(frameData, "Transform Sync Bodies"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Sync Colliders: " + GetPhysicsCounterValue(frameData, "Transform Sync Colliders"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Parent Sync Bodies: " + GetPhysicsCounterValue(frameData, "Transform Parent Sync Bodies"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Parent Sync Colliders: " + GetPhysicsCounterValue(frameData, "Transform Parent Sync Colliders"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Joints", GUILayout.Width(k_labelWidthTitle)); EditorGUILayout.LabelField("| Total: " + GetPhysicsCounterValue(frameData, "Total Joints"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Timings", GUILayout.Width(k_labelWidthTitle)); EditorGUILayout.LabelField("| Sim: " + GetPhysicsSampleData(frameData, "Physics2D.Simulate"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Sync: " + GetPhysicsSampleData(frameData, "Physics2D.SyncTransformChanges"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Step: " + GetPhysicsSampleData(frameData, "Physics2D.Step"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Write: " + GetPhysicsSampleData(frameData, "Physics2D.UpdateTransforms"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.LabelField("| Callbacks: " + GetPhysicsSampleData(frameData, "Physics2D.CompileContactCallbacks"), GUILayout.Width(k_labelWidthDetail)); EditorGUILayout.EndHorizontal(); } else { EditorGUILayout.LabelField("Current Data not Available."); } } else { // Determine if the old counters are available by looking for a counter only available there. if (!newCountersAvailable) { // Old data compatibility. var activeText = ProfilerDriver.GetOverviewText(ProfilerArea.Physics2D, ProfilerWindow.GetActiveVisibleFrameIndex()); var height = EditorStyles.wordWrappedLabel.CalcHeight(GUIContent.Temp(activeText), position.width); EditorGUILayout.SelectableLabel(activeText, EditorStyles.wordWrappedLabel, GUILayout.MinHeight(height)); } else { EditorGUILayout.LabelField("Legacy Data not Available."); } } } } GUILayout.EndScrollView(); } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/Box2D/Physics2DProfilerModule.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/Box2D/Physics2DProfilerModule.cs", "repo_id": "UnityCsReference", "token_count": 11957 }
440
// Unity 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.Profiling.Editor; using UnityEditor; using UnityEngine; using UnityEngine.Profiling; namespace UnityEditorInternal.Profiling { [Serializable] // TODO: refactor: rename to GpuProfilerModule // together with CPUOrGPUProfilerModule and CpuProfilerModule // in a PR that doesn't affect performance so that the sample names can be fixed as well without loosing comparability in Performance tests. [ProfilerModuleMetadata("GPU Usage", typeof(LocalizationResource), IconPath = "Profiler.GPU")] internal class GPUProfilerModule : CPUOrGPUProfilerModule { const string k_SettingsKeyPrefix = "Profiler.GPUProfilerModule."; protected override string SettingsKeyPrefix => k_SettingsKeyPrefix; protected override ProfilerViewType DefaultViewTypeSetting => ProfilerViewType.Hierarchy; static readonly string k_GpuProfilingDisabled = L10n.Tr("GPU Profiling was not enabled so no data was gathered."); static readonly string k_GpuProfilingNotSupportedWithEditorProfilingBefore2021_2 = L10n.Tr("GPU Profiling was not supported when profiling the Editor before 2021.2."); static readonly string k_GpuProfilingNotSupportedWithLegacyGfxJobs = L10n.Tr("GPU Profiling is currently not supported when using Graphics Jobs."); static readonly string k_GpuProfilingNotSupportedWithNativeGfxJobs = L10n.Tr("GPU Profiling is currently not supported when using Graphics Jobs."); static readonly string k_GpuProfilingNotSupportedByDevice = L10n.Tr("GPU Profiling is currently not supported by this device."); static readonly string k_GpuProfilingNotSupportedByGraphicsAPI = L10n.Tr("GPU Profiling is currently not supported by the used graphics API."); static readonly string k_GpuProfilingNotSupportedDueToFrameTimingStatsAndDisjointTimerQuery = L10n.Tr("GPU Profiling is currently not supported on this device when PlayerSettings.enableFrameTimingStats is enabled. (<a playersettingslink=\"Project/Player\" playersettingssearchstring=\"Frame Timing Stats\">Click here to edit</a>)"); static readonly string k_GpuProfilingNotSupportedWithVulkan = L10n.Tr("GPU Profiling is currently not supported when using Vulkan."); static readonly string k_GpuProfilingNotSupportedWithMetal = L10n.Tr("GPU Profiling is currently not supported when using Metal."); static readonly string k_GpuProfilingNotSupportedWithOpenGLGPURecorders = L10n.Tr("GPU Profiling is currently not supported in OpenGL when PlayerSettings.\nenableOpenGLProfilerGPURecorders is enabled. (<a playersettingslink=\"Project/Player\" playersettingssearchstring=\"OpenGL: Profiler GPU Recorders\">Click here to edit</a>)"); static readonly string k_PerformanceWarningMessage = L10n.Tr("Collecting GPU Profiler data disables graphics jobs, causes overhead and reduces the accuracy of the CPU Module. Close this module if you don't need this data.\n\n" + "HDRP and URP Renderers are currently not supported: the profiler won't show most GPU markers if these renderers are enabled."); static readonly Dictionary<GpuProfilingStatisticsAvailabilityStates, string> s_StatisticsAvailabilityStateReason = new Dictionary<GpuProfilingStatisticsAvailabilityStates, string>() { #pragma warning disable CS0618 // Type or member is obsolete {GpuProfilingStatisticsAvailabilityStates.NotSupportedWithEditorProfiling , k_GpuProfilingNotSupportedWithEditorProfilingBefore2021_2}, #pragma warning restore CS0618 // Type or member is obsolete {GpuProfilingStatisticsAvailabilityStates.NotSupportedWithLegacyGfxJobs , k_GpuProfilingNotSupportedWithLegacyGfxJobs}, {GpuProfilingStatisticsAvailabilityStates.NotSupportedWithNativeGfxJobs , k_GpuProfilingNotSupportedWithNativeGfxJobs}, {GpuProfilingStatisticsAvailabilityStates.NotSupportedByDevice , k_GpuProfilingNotSupportedByDevice}, {GpuProfilingStatisticsAvailabilityStates.NotSupportedByGraphicsAPI , k_GpuProfilingNotSupportedByGraphicsAPI}, {GpuProfilingStatisticsAvailabilityStates.NotSupportedDueToFrameTimingStatsAndDisjointTimerQuery , k_GpuProfilingNotSupportedDueToFrameTimingStatsAndDisjointTimerQuery}, {GpuProfilingStatisticsAvailabilityStates.NotSupportedWithVulkan , k_GpuProfilingNotSupportedWithVulkan}, {GpuProfilingStatisticsAvailabilityStates.NotSupportedWithMetal , k_GpuProfilingNotSupportedWithMetal}, {GpuProfilingStatisticsAvailabilityStates.NotSupportedWithOpenGLGPURecorders , k_GpuProfilingNotSupportedWithOpenGLGPURecorders}, }; const int k_DefaultOrderIndex = 1; // ProfilerWindow exposes this as a const value via ProfilerWindow.gpuModuleName, so we need to define it as const. internal const string k_Identifier = "UnityEditorInternal.Profiling.GPUProfilerModule, UnityEditor.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"; internal override ProfilerArea area => ProfilerArea.GPU; public override bool usesCounters => false; private protected override int defaultOrderIndex => k_DefaultOrderIndex; private protected override string legacyPreferenceKey => "ProfilerChartGPU"; public GPUProfilerModule() { WarningMsg = k_PerformanceWarningMessage; } internal override ProfilerViewType ViewType { set { if (value == ProfilerViewType.Timeline) throw new ArgumentException($"{DisplayName} does not implement a {nameof(ProfilerViewType.Timeline)} view."); CPUOrGPUViewTypeChanged(value); } } static string GetStatisticsAvailabilityStateReason(int statisticsAvailabilityState) { GpuProfilingStatisticsAvailabilityStates state = (GpuProfilingStatisticsAvailabilityStates)statisticsAvailabilityState; if ((state & GpuProfilingStatisticsAvailabilityStates.Enabled) == 0) return null; if (!s_StatisticsAvailabilityStateReason.ContainsKey(state)) { string combinedReason = ""; for (int i = 0; i < sizeof(GpuProfilingStatisticsAvailabilityStates) * 8; i++) { if ((statisticsAvailabilityState >> i & 1) != 0) { GpuProfilingStatisticsAvailabilityStates currentBit = (GpuProfilingStatisticsAvailabilityStates)(1 << i); if (currentBit == GpuProfilingStatisticsAvailabilityStates.NotSupportedByGraphicsAPI && ((state & GpuProfilingStatisticsAvailabilityStates.NotSupportedWithMetal) != 0 || (state & GpuProfilingStatisticsAvailabilityStates.NotSupportedWithVulkan) != 0 ) ) continue; // no need to war about the general case, when a more specific reason was given. if (s_StatisticsAvailabilityStateReason.ContainsKey(currentBit)) { if (string.IsNullOrEmpty(combinedReason)) combinedReason = s_StatisticsAvailabilityStateReason[currentBit]; else combinedReason += "\n\n" + s_StatisticsAvailabilityStateReason[currentBit]; } } } s_StatisticsAvailabilityStateReason[state] = combinedReason; } return s_StatisticsAvailabilityStateReason[state]; } internal override void OnEnable() { base.OnEnable(); m_FrameDataHierarchyView.OnEnable(this, ProfilerWindow, true); m_FrameDataHierarchyView.dataAvailabilityMessage = null; if (m_ViewType == ProfilerViewType.Timeline) m_ViewType = ProfilerViewType.Hierarchy; TryRestoringSelection(); } public override void DrawDetailsView(Rect position) { var selectedFrameIndex = (int)ProfilerWindow.selectedFrameIndex; if (selectedFrameIndex >= ProfilerDriver.firstFrameIndex && selectedFrameIndex <= ProfilerDriver.lastFrameIndex) { GpuProfilingStatisticsAvailabilityStates state = (GpuProfilingStatisticsAvailabilityStates)ProfilerDriver.GetGpuStatisticsAvailabilityState(selectedFrameIndex); if ((state & GpuProfilingStatisticsAvailabilityStates.Enabled) == 0) m_FrameDataHierarchyView.dataAvailabilityMessage = k_GpuProfilingDisabled; else if ((state & GpuProfilingStatisticsAvailabilityStates.Gathered) == 0) m_FrameDataHierarchyView.dataAvailabilityMessage = GetStatisticsAvailabilityStateReason((int)state); else m_FrameDataHierarchyView.dataAvailabilityMessage = null; } else m_FrameDataHierarchyView.dataAvailabilityMessage = null; base.DrawDetailsView(position); } private protected override ProfilerChart InstantiateChart(float defaultChartScale, float chartMaximumScaleInterpolationValue) { var chart = base.InstantiateChart(defaultChartScale, chartMaximumScaleInterpolationValue); chart.statisticsAvailabilityMessage = GetStatisticsAvailabilityStateReason; var performanceWarningMsg = new GUIContent("", EditorGUIUtility.LoadIcon("console.warnicon.sml"), k_PerformanceWarningMessage); chart.WarningMsg = performanceWarningMsg; return chart; } private protected override bool ReadActiveState() { return SessionState.GetBool(activeStatePreferenceKey, false); } private protected override void SaveActiveState() { SessionState.SetBool(activeStatePreferenceKey, active); } private protected override void DeleteActiveState() { SessionState.EraseBool(activeStatePreferenceKey); } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/GPU/GPUProfilerModule.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/GPU/GPUProfilerModule.cs", "repo_id": "UnityCsReference", "token_count": 3826 }
441
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using Unity.Profiling; using Unity.Profiling.Editor; using UnityEditor; using UnityEngine; using UnityEngine.Profiling; using System.Text; using System.Collections.Generic; using UnityEditor.Profiling; namespace UnityEditorInternal.Profiling { [Serializable] [ProfilerModuleMetadata("Rendering", typeof(LocalizationResource), IconPath = "Profiler.Rendering")] internal class RenderingProfilerModule : ProfilerModuleBase { internal static class Styles { public static readonly GUIContent frameDebugger = EditorGUIUtility.TrTextContent("Open Frame Debugger", "Frame Debugger for current game view"); public static readonly GUIContent noFrameDebugger = EditorGUIUtility.TrTextContent("Frame Debugger", "Open Frame Debugger (Current frame needs to be selected)"); } const int k_DefaultOrderIndex = 2; static readonly string k_RenderCountersCategoryName = ProfilerCategory.Render.Name; static readonly ProfilerCounterData[] k_DefaultRenderAreaCounterNames = { new ProfilerCounterData() { m_Name = "Batches Count", m_Category = k_RenderCountersCategoryName, }, new ProfilerCounterData() { m_Name = "SetPass Calls Count", m_Category = k_RenderCountersCategoryName, }, new ProfilerCounterData() { m_Name = "Triangles Count", m_Category = k_RenderCountersCategoryName, }, new ProfilerCounterData() { m_Name = "Vertices Count", m_Category = k_RenderCountersCategoryName, }, }; internal override ProfilerArea area => ProfilerArea.Rendering; private protected override int defaultOrderIndex => k_DefaultOrderIndex; private protected override string legacyPreferenceKey => "ProfilerChartRendering"; public override void DrawToolbar(Rect position) { if (UnityEditor.MPE.ProcessService.level != UnityEditor.MPE.ProcessLevel.Main) return; EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); if (GUILayout.Button(GUI.enabled ? Styles.frameDebugger : Styles.noFrameDebugger, EditorStyles.toolbarButtonLeft)) { FrameDebuggerWindow.OpenWindowAndToggleEnabled(); } GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); } public override void DrawDetailsView(Rect position) { string activeText = string.Empty; using (var f = ProfilerDriver.GetRawFrameDataView(ProfilerWindow.GetActiveVisibleFrameIndex(), 0)) { if (f.valid) { var batchesCount = GetCounterValue(f, "Batches Count"); if (batchesCount != -1) { var stringBuilder = new StringBuilder(1024); stringBuilder.Append($"SetPass Calls: {GetCounterValueAsNumber(f, "SetPass Calls Count")} \tDraw Calls: {GetCounterValueAsNumber(f, "Draw Calls Count")} \t\tBatches: {batchesCount} \tTriangles: {GetCounterValueAsNumber(f, "Triangles Count")} \tVertices: {GetCounterValueAsNumber(f, "Vertices Count")}"); stringBuilder.Append($"\n(Dynamic Batching)\tBatched Draw Calls: {GetCounterValueAsNumber(f, "Dynamic Batched Draw Calls Count")} \tBatches: {GetCounterValueAsNumber(f, "Dynamic Batches Count")} \tTriangles: {GetCounterValueAsNumber(f, "Dynamic Batched Triangles Count")} \tVertices: {GetCounterValueAsNumber(f, "Dynamic Batched Vertices Count")} \tTime: {GetCounterValue(f, "Dynamic Batching Time") * 1e-6:0.00}ms"); stringBuilder.Append($"\n(Static Batching)\t\tBatched Draw Calls: {GetCounterValueAsNumber(f, "Static Batched Draw Calls Count")} \tBatches: {GetCounterValueAsNumber(f, "Static Batches Count")} \tTriangles: {GetCounterValueAsNumber(f, "Static Batched Triangles Count")} \tVertices: {GetCounterValueAsNumber(f, "Static Batched Vertices Count")}"); stringBuilder.Append($"\n(Instancing)\t\tBatched Draw Calls: {GetCounterValueAsNumber(f, "Instanced Batched Draw Calls Count")} \tBatches: {GetCounterValueAsNumber(f, "Instanced Batches Count")} \tTriangles: {GetCounterValueAsNumber(f, "Instanced Batched Triangles Count")} \tVertices: {GetCounterValueAsNumber(f, "Instanced Batched Vertices Count")}"); stringBuilder.Append($"\nUsed Textures: {GetCounterValue(f, "Used Textures Count")} / {GetCounterValueAsBytes(f, "Used Textures Bytes")}"); stringBuilder.Append($"\nRender Textures: {GetCounterValue(f, "Render Textures Count")} / {GetCounterValueAsBytes(f, "Render Textures Bytes")}"); stringBuilder.Append($"\nRender Textures Changes: {GetCounterValue(f, "Render Textures Changes Count")}"); stringBuilder.Append($"\nUsed Buffers: {GetCounterValue(f, "Used Buffers Count")} / {GetCounterValueAsBytes(f, "Used Buffers Bytes")}"); stringBuilder.Append($"\nVertex Buffer Upload In Frame: {GetCounterValue(f, "Vertex Buffer Upload In Frame Count")} / {GetCounterValueAsBytes(f, "Vertex Buffer Upload In Frame Bytes")}"); stringBuilder.Append($"\nIndex Buffer Upload In Frame: {GetCounterValue(f, "Index Buffer Upload In Frame Count")} / {GetCounterValueAsBytes(f, "Index Buffer Upload In Frame Bytes")}"); stringBuilder.Append($"\nShadow Casters: {GetCounterValue(f, "Shadow Casters Count")}\n"); activeText = stringBuilder.ToString(); } else { // Old data compatibility. activeText = ProfilerDriver.GetOverviewText(ProfilerArea.Rendering, ProfilerWindow.GetActiveVisibleFrameIndex()); } } } float height = EditorStyles.wordWrappedLabel.CalcHeight(GUIContent.Temp(activeText), position.width); m_PaneScroll = GUILayout.BeginScrollView(m_PaneScroll, ProfilerWindow.Styles.background); EditorGUILayout.SelectableLabel(activeText, EditorStyles.wordWrappedLabel, GUILayout.MinHeight(height)); GUILayout.EndScrollView(); } protected override List<ProfilerCounterData> CollectDefaultChartCounters() { return new List<ProfilerCounterData>(k_DefaultRenderAreaCounterNames); } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/Rendering/RenderingProfilerModule.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/Rendering/RenderingProfilerModule.cs", "repo_id": "UnityCsReference", "token_count": 2896 }
442
// Unity 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; using UnityEngine; using UnityEngine.UIElements; namespace Unity.Profiling.Editor { internal class MemoryUsageBreakdownElement : VisualElement { // adaptation helper. MemoryUsageBreakdownElement is copied over from the memory profiler package which contains this helper static class UIElementsHelper { public static void SetVisibility(VisualElement element, bool visible) { element.visible = visible; element.style.display = visible ? DisplayStyle.Flex : DisplayStyle.None; } } static class Content { public static readonly string SelectedFormatStringPartOfTooltip = L10n.Tr("\nSelected: {0}\n({1:0.0}% of {2})"); public static readonly string Reserved = L10n.Tr("Reserved"); public static readonly string UsedFormatStringPartOfTooltip = L10n.Tr(" Used: {0}\n({1:0.0}% of {2})"); public static readonly string ReservedFormatStringPartOfTooltip = L10n.Tr("{0}: {1}\n({2:0.0}% of {3})"); public static readonly string ReservedClarificationForReservedPartOfTooltip = L10n.Tr("\nReserved"); } public string Text { get; private set;} ulong m_TotalBytes; public long TotalBytes { get { return (long)m_TotalBytes; } private set { m_TotalBytes = (ulong)value; } } ulong m_UsedBytes; public long UsedBytes { get { return (long)m_UsedBytes; } private set { m_UsedBytes = (ulong)value; } } public bool ShowUsed { get; private set; } ulong m_SelectedBytes; public long SelectedBytes { get { return (long)m_SelectedBytes; } private set { m_SelectedBytes = (ulong)value; } } public bool ShowSelected { get; private set; } public float PercentageUsed { get { return m_TotalBytes == 0 ? 100 : m_UsedBytes / (float)m_TotalBytes * 100; } } public float PercentageSelected { get { return m_TotalBytes == 0 ? 100 : m_SelectedBytes / (float)m_TotalBytes * 100; } } public string BackgroundColorClass { get; private set; } VisualElement m_ReservedElement; VisualElement m_BackgroundElement; VisualElement m_UsedElement; VisualElement m_SelectedElement; MemoryUsageBreakdown m_BreakdownParent; MemoryUsageBreakdown.RowElement m_Row; public MemoryUsageBreakdownElement(string text, string backgroundColorClass, bool showUsed = false, bool showSelected = false) : this() { Text = text; BackgroundColorClass = backgroundColorClass; ShowUsed = showUsed; ShowSelected = showSelected; if (!string.IsNullOrEmpty(backgroundColorClass)) AddToClassList(backgroundColorClass); } public MemoryUsageBreakdownElement() : base() { AddToClassList("memory-usage-bar__element"); m_BackgroundElement = new VisualElement(); m_BackgroundElement.AddToClassList("memory-usage-breakdown__memory-usage-bar__background"); hierarchy.Add(m_BackgroundElement); m_ReservedElement = new VisualElement(); m_ReservedElement.AddToClassList("memory-usage-breakdown__memory-usage-bar__reserved"); m_BackgroundElement.Add(m_ReservedElement); m_UsedElement = new VisualElement(); m_UsedElement.AddToClassList("memory-usage-breakdown__memory-usage-bar__used-portion"); m_ReservedElement.Add(m_UsedElement); m_SelectedElement = new VisualElement(); m_SelectedElement.AddToClassList("memory-usage-breakdown__memory-usage-bar__selected-portion"); m_ReservedElement.Add(m_SelectedElement); } void Init(string text, bool showUsed, ulong used, ulong total, bool showSelected, ulong selected, string backgroundColorClass) { Text = text; ShowUsed = showUsed; m_UsedBytes = used; m_TotalBytes = total; ShowSelected = showSelected; m_SelectedBytes = selected; BackgroundColorClass = backgroundColorClass; m_ReservedElement.AddToClassList(backgroundColorClass); m_BackgroundElement.style.backgroundColor = Color.black; UIElementsHelper.SetVisibility(m_UsedElement, ShowUsed); RegisterCallback<GeometryChangedEvent>(OnGeometryChangedEvent); m_UsedElement.style.width = new Length(PercentageUsed, LengthUnit.Percent); m_UsedElement.AddToClassList(BackgroundColorClass); UIElementsHelper.SetVisibility(m_SelectedElement, ShowSelected); m_SelectedElement.style.width = new Length(m_SelectedBytes, LengthUnit.Percent); } void OnGeometryChangedEvent(GeometryChangedEvent e) { var backgroundColor = m_ReservedElement.resolvedStyle.backgroundColor; var outlineColor = backgroundColor; if (ShowUsed) { backgroundColor.a = 0.3f; } m_ReservedElement.style.backgroundColor = backgroundColor; m_ReservedElement.style.borderBottomColor = outlineColor; m_ReservedElement.style.borderTopColor = outlineColor; m_ReservedElement.style.borderLeftColor = outlineColor; m_ReservedElement.style.borderRightColor = outlineColor; UnregisterCallback<GeometryChangedEvent>(OnGeometryChangedEvent); } public void SetValues(ulong totalBytes, ulong usedBytes) { SetValues(totalBytes, usedBytes, 0, false); } public void SetValues(ulong totalBytes, ulong usedBytes, ulong selectedBytes) { SetValues(totalBytes, usedBytes, selectedBytes, true); } public void SetValues(ulong totalBytes, ulong usedBytes, ulong selectedBytes, bool showSelected) { ShowSelected = showSelected; m_SelectedBytes = selectedBytes; m_TotalBytes = totalBytes; m_UsedBytes = usedBytes; var tooltipText = BuildTooltipText(m_BreakdownParent.HeaderText, Text, (ulong)m_BreakdownParent.TotalBytes, m_TotalBytes, ShowUsed, m_UsedBytes, ShowSelected, m_SelectedBytes); tooltip = tooltipText; m_Row.RowSize.text = BuildRowSizeText(totalBytes, usedBytes, ShowUsed, showSelected); m_Row.Root.tooltip = tooltip; SetBarElements(); } public static string BuildTooltipText(string memoryBreakDownName, string elementName, ulong totalBytes, ulong reservedBytes, bool showUsed = false, ulong usedBytes = 0, bool showSelected = false, ulong selectedBytes = 0) { // Unity/Other Used: 27MB // (90% of Reserved) // Reserved: 30 MB // (90% of Total Memory) // Selected: 1MB // (XX% of Unity/Other) // or // Unity/Other: 30 MB // (90% of Total Memory) // Selected: 1MB // (XX% of Unity/Other) var selectedText = showSelected ? string.Format(Content.SelectedFormatStringPartOfTooltip, EditorUtility.FormatBytes((long)selectedBytes), selectedBytes / (float)reservedBytes * 100, showUsed ? Content.Reserved : elementName) : ""; var usedText = showUsed ? string.Format(Content.UsedFormatStringPartOfTooltip, EditorUtility.FormatBytes((long)usedBytes), usedBytes / (float)reservedBytes * 100, showUsed ? Content.Reserved : elementName) : ""; var reservedText = string.Format(Content.ReservedFormatStringPartOfTooltip, showUsed ? Content.ReservedClarificationForReservedPartOfTooltip : "", EditorUtility.FormatBytes((long)reservedBytes), reservedBytes / (float)totalBytes * 100, memoryBreakDownName); return string.Format("{0}{1}{2}{3}", elementName, usedText, reservedText, selectedText); } public static string BuildRowSizeText(ulong totalBytes, ulong usedBytes, bool showUsed, bool showSelected = false, ulong selectedBytes = 0) { if (showUsed) { var total = EditorUtility.FormatBytes((long)totalBytes); var used = EditorUtility.FormatBytes((long)usedBytes); // check if the last two characters are the same (i.e. " B" "KB" ...) so we can drop unnecesary unit qualifiers if (total[total.Length - 1] == used[used.Length - 1] && total[total.Length - 2] == used[used.Length - 2]) { used = used.Substring(0, used.Length - (used[used.Length - 2] == ' ' ? 2 : 3)); } return string.Format("{0} / {1}", used, total); } else { return EditorUtility.FormatBytes((long)totalBytes); } } void SetBarElements() { UIElementsHelper.SetVisibility(m_UsedElement, ShowUsed); m_UsedElement.style.width = new Length(PercentageUsed, LengthUnit.Percent); UIElementsHelper.SetVisibility(m_SelectedElement, ShowSelected); m_SelectedElement.style.width = new Length(PercentageSelected, LengthUnit.Percent); } public void SetupRow(MemoryUsageBreakdown breakdownParent, MemoryUsageBreakdown.RowElement row) { m_Row = row; m_BreakdownParent = breakdownParent; m_Row.Root.tooltip = tooltip; // copy the color if (!string.IsNullOrEmpty(BackgroundColorClass)) m_Row.ColorBox.AddToClassList(BackgroundColorClass); m_Row.RowName.text = Text; m_Row.ShowUsed = ShowUsed; SetValues(m_TotalBytes, m_UsedBytes); } /// <summary> /// Instantiates a <see cref="MemoryUsageBreakdownElement"/> using the data read from a UXML file. /// </summary> [Obsolete("UxmlFactory is deprecated and will be removed. Use UxmlElementAttribute instead.", false)] public new class UxmlFactory : UxmlFactory<MemoryUsageBreakdownElement, UxmlTraits> {} /// <summary> /// Defines <see cref="UxmlTraits"/> for the <see cref="MemoryUsageBreakdownElement"/>. /// </summary> [Obsolete("UxmlTraits is deprecated and will be removed. Use UxmlElementAttribute instead.", false)] public new class UxmlTraits : VisualElement.UxmlTraits { UxmlStringAttributeDescription m_Text = new UxmlStringAttributeDescription { name = "text", defaultValue = "Other" }; UxmlStringAttributeDescription m_ColorClass = new UxmlStringAttributeDescription { name = "background-color-class", defaultValue = "" }; UxmlBoolAttributeDescription m_ShowUsed = new UxmlBoolAttributeDescription { name = "show-used", defaultValue = false }; UxmlLongAttributeDescription m_Used = new UxmlLongAttributeDescription { name = "used-bytes", defaultValue = 50 }; UxmlLongAttributeDescription m_Total = new UxmlLongAttributeDescription { name = "total-bytes", defaultValue = 100 }; UxmlBoolAttributeDescription m_ShowSelected = new UxmlBoolAttributeDescription { name = "show-selected", defaultValue = false }; UxmlLongAttributeDescription m_Selected = new UxmlLongAttributeDescription { name = "selected-bytes", defaultValue = 0}; public override IEnumerable<UxmlChildElementDescription> uxmlChildElementsDescription { get { yield break; } } public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) { base.Init(ve, bag, cc); var text = m_Text.GetValueFromBag(bag, cc); var showUsed = m_ShowUsed.GetValueFromBag(bag, cc); var total = m_Total.GetValueFromBag(bag, cc); var showSelected = m_ShowSelected.GetValueFromBag(bag, cc); var used = Mathf.Clamp(m_Used.GetValueFromBag(bag, cc), 0, total); var selected = Mathf.Clamp(m_Selected.GetValueFromBag(bag, cc), 0, total); var color = m_ColorClass.GetValueFromBag(bag, cc); ((MemoryUsageBreakdownElement)ve).Init(text, showUsed, (ulong)used, (ulong)total, showSelected, (ulong)selected, color); } } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/UIElements/MemoryUsageBreakdownElement.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/UIElements/MemoryUsageBreakdownElement.cs", "repo_id": "UnityCsReference", "token_count": 5415 }
443
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Collections.Generic; using System.Linq; using UnityEditor.Profiling; using UnityEditor.UIElements; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor { class ProgressWindow : EditorWindow { internal const string ussBasePath = "StyleSheets/ProgressWindow"; internal static readonly string ussPath = $"{ussBasePath}/ProgressWindow.uss"; internal static readonly string ussPathDark = $"{ussBasePath}/ProgressWindowDark.uss"; internal static readonly string ussPathLight = $"{ussBasePath}/ProgressWindowLight.uss"; internal const string k_UxmlProgressItemPath = "UXML/ProgressWindow/ProgressElement.uxml"; public const string preferenceKey = "ProgressWindow."; const float k_WindowMinWidth = 100; const float k_WindowMinHeight = 70; const float k_WindowWidth = 400; const float k_WindowHeight = 300; static ProgressWindow s_Window; static readonly string k_CheckWindowKeyName = $"{typeof(ProgressWindow).FullName}h"; internal static bool canHideDetails => s_Window && !s_Window.docked; static ProgressOrderComparer s_ProgressComparer = new ProgressOrderComparer(true); static VisualTreeAsset s_VisualProgressItemTask = null; Button m_DismissAllBtn; TreeView m_TreeView; Dictionary<int, List<int>> m_MissingParents; HashSet<int> m_ContainedItems; HashSet<int> m_ItemsNeedingExpansion; Dictionary<int, bool> m_RemovedItemsExpandedState; // For testing only internal TreeView treeView => m_TreeView; internal Button dismissAllButton => m_DismissAllBtn; [MenuItem("Window/General/Progress", priority = 50)] public static void ShowDetails() { ShowDetails(false); } internal static void ShowDetails(bool shouldReposition) { if (s_Window && s_Window.docked) shouldReposition = false; if (s_Window == null) { var wins = Resources.FindObjectsOfTypeAll<ProgressWindow>(); if (wins.Length > 0) s_Window = wins[0]; } bool newWindowCreated = false; if (!s_Window) { s_Window = CreateInstance<ProgressWindow>(); newWindowCreated = true; // If it is the first time this window is opened, reposition. if (!EditorPrefs.HasKey(k_CheckWindowKeyName)) shouldReposition = true; } s_Window.Show(); s_Window.Focus(); if (newWindowCreated && shouldReposition) { var mainWindowRect = EditorGUIUtility.GetMainWindowPosition(); var size = new Vector2(k_WindowWidth, k_WindowHeight); s_Window.position = new Rect(mainWindowRect.xMax - k_WindowWidth - 6, mainWindowRect.yMax - k_WindowHeight - 50, size.x, size.y); s_Window.minSize = new Vector2(k_WindowMinWidth, k_WindowMinHeight); } } internal static void HideDetails() { if (canHideDetails) { s_Window.Close(); s_Window = null; } } void OnEnable() { s_Window = this; titleContent = EditorGUIUtility.TrTextContent("Background Tasks"); rootVisualElement.AddStyleSheetPath(ussPath); if (EditorGUIUtility.isProSkin) rootVisualElement.AddStyleSheetPath(ussPathDark); else rootVisualElement.AddStyleSheetPath(ussPathLight); var toolbar = new UIElements.Toolbar(); m_DismissAllBtn = new ToolbarButton(ClearInactive) { name = "DismissAllBtn", text = L10n.Tr("Clear Inactive"), }; toolbar.Add(m_DismissAllBtn); // This is our friend the spacer toolbar.Add(new VisualElement() { style = { flexGrow = 1 } }); rootVisualElement.Add(toolbar); s_VisualProgressItemTask = EditorGUIUtility.Load(k_UxmlProgressItemPath) as VisualTreeAsset; m_TreeView = new TreeView(); m_TreeView.makeItem = MakeTreeViewItem; m_TreeView.bindItem = BindTreeViewItem; m_TreeView.unbindItem = UnbindTreeViewItem; m_TreeView.destroyItem = DestroyTreeViewItem; m_TreeView.fixedItemHeight = 50; m_TreeView.SetRootItems(new TreeViewItemData<Progress.Item>[] {}); var scrollView = m_TreeView.Q<ScrollView>(); if (scrollView != null) scrollView.horizontalScrollerVisibility = ScrollerVisibility.Hidden; rootVisualElement.Add(m_TreeView); m_TreeView.Rebuild(); // Update the treeview with the existing items m_MissingParents = new Dictionary<int, List<int>>(); m_ContainedItems = new HashSet<int>(); m_ItemsNeedingExpansion = new HashSet<int>(); m_RemovedItemsExpandedState = new Dictionary<int, bool>(); OperationsAdded(Progress.EnumerateItems().ToArray()); Progress.added += OperationsAdded; Progress.removed += OperationsRemoved; Progress.updated += OperationsUpdated; UpdateDismissAllButton(); } void OnDisable() { Progress.added -= OperationsAdded; Progress.removed -= OperationsRemoved; Progress.updated -= OperationsUpdated; } static VisualElement MakeTreeViewItem() { return new VisualProgressItem(s_VisualProgressItemTask); } void BindTreeViewItem(VisualElement element, int index) { var visualProgressItem = element as VisualProgressItem; if (visualProgressItem == null) return; var progressItem = m_TreeView.GetItemDataForIndex<Progress.Item>(index); visualProgressItem.BindItem(progressItem); var indentLevel = GetIndentationLevel(index); var rootVE = m_TreeView.GetRootElementForIndex(index); var isEven = indentLevel % 2 == 0; rootVE.EnableInClassList("unity-tree-view__item-indent-even", isEven); rootVE.EnableInClassList("unity-tree-view__item-indent-odd", !isEven); } void UnbindTreeViewItem(VisualElement element, int index) { var visualProgressItem = element as VisualProgressItem; visualProgressItem?.UnbindItem(); var rootVE = m_TreeView.GetRootElementForIndex(index); rootVE?.EnableInClassList("unity-tree-view__item-indent-even", false); rootVE?.EnableInClassList("unity-tree-view__item-indent-odd", false); } static void DestroyTreeViewItem(VisualElement element) { var visualProgressItem = element as VisualProgressItem; visualProgressItem?.DestroyItem(); } int GetIndentationLevel(int index) { var level = 0; var parentId = m_TreeView.GetParentIdForIndex(index); while (parentId != -1) { ++level; parentId = m_TreeView.viewController.GetParentId(parentId); } return level; } internal static void ClearInactive() { // When using synchronous progresses, calling remove will alter the progress items immediately. var finishedItems = Progress.EnumerateItems().Where(item => item.finished).ToList(); foreach (var item in finishedItems) { item.Remove(); } } void UpdateDismissAllButton() { m_DismissAllBtn.SetEnabled(Progress.EnumerateItems().Any(item => item.finished)); } void OperationsAdded(Progress.Item[] items) { //using (new EditorPerformanceTracker("ProgressWindow.OperationsAdded")) { foreach (var item in items) { var treeViewItemData = new TreeViewItemData<Progress.Item>(item.id, item); AddTreeViewItemToTree(treeViewItemData); // When setting autoExpand to true, there is a possible race condition // that can happen if the item is added and removed quickly. // AutoExpand triggers a callback to be executed at a later point when makeItem is called. // By the time the callback is called, the item might have been removed. // Therefore, we expand all new items here manually. m_TreeView.viewController.ExpandItem(item.id, true); // Also, if the item has no child, then the expanded state is not set. // Therefore, we need to keep track of this item to expand it when we add a child to it. if (!m_TreeView.viewController.HasChildren(item.id)) m_ItemsNeedingExpansion.Add(item.id); } m_TreeView.RefreshItems(); } } void OperationsRemoved(Progress.Item[] items) { using (new EditorPerformanceTracker("ProgressWindow.OperationsRemoved")) { foreach (var item in items) { RemoveTreeViewItem(item.id); } m_TreeView.Rebuild(); UpdateDismissAllButton(); } } void OperationsUpdated(Progress.Item[] items) { //using (new EditorPerformanceTracker("ProgressWindow.OperationsUpdated")) { var itemsToBeReinserted = items .Where(item => item.lastUpdates.HasAny(Progress.Updates.StatusChanged | Progress.Updates.PriorityChanged)); // The items must me reinserted in a specific order, otherwise we end up // with the wrong insertion order or even with duplicates if not careful. To prevent any // issues, we must reinsert all siblings together, avoiding reinserting with their parents. var needsRebuild = false; var siblingGroups = itemsToBeReinserted.GroupBy(item => item.parentId, item => item.id); foreach (var siblings in siblingGroups) { ReinsertAllItems(siblings); needsRebuild = true; } if (needsRebuild) { m_TreeView.Rebuild(); UpdateDismissAllButton(); } else m_TreeView.RefreshItems(); } } List<Progress.Item> GetSiblingItems(Progress.Item item, out int newParentId) { newParentId = item.parentId; if (item.parentId == -1) { var rootIds = m_TreeView.GetRootIds(); return rootIds?.Select(id => m_TreeView.GetItemDataForId<Progress.Item>(id)).ToList(); } if (!m_ContainedItems.Contains(newParentId)) { // If the parent is missing, the item should be put at the root level for now. List<int> itemIds; if (!m_MissingParents.TryGetValue(item.parentId, out itemIds)) { itemIds = new List<int>(); m_MissingParents.Add(item.parentId, itemIds); } itemIds.Add(item.id); newParentId = -1; return m_TreeView.GetRootIds()?.Select(id => m_TreeView.GetItemDataForId<Progress.Item>(id)).ToList(); } var childrenIds = m_TreeView.viewController.GetChildrenIds(newParentId); return childrenIds?.Select(id => m_TreeView.GetItemDataForId<Progress.Item>(id)).ToList(); } static int GetInsertionIndex(List<Progress.Item> items, Progress.Item itemToInsert) { if (items == null) return -1; var insertionIndex = items.BinarySearch(itemToInsert, s_ProgressComparer); if (insertionIndex < 0) return ~insertionIndex; return insertionIndex; } void ReinsertItem(int itemId) { var treeViewItemWithChildren = GetExistingTreeViewItemFromId(itemId); RemoveTreeViewItem(itemId); AddTreeViewItemToTree(treeViewItemWithChildren); } void ReinsertAllItems(IEnumerable<int> itemIds) { var treeViewItemsWithChildren = itemIds.Select(id => GetExistingTreeViewItemFromId(id)).ToList(); // Remove all items first foreach (var treeViewItem in treeViewItemsWithChildren) { RemoveTreeViewItem(treeViewItem.id); } // Then reinsert them foreach (var treeViewItem in treeViewItemsWithChildren) { AddTreeViewItemToTree(treeViewItem); } } TreeViewItemData<Progress.Item> GetExistingTreeViewItemFromId(int itemId) { if (m_TreeView.viewController is DefaultTreeViewController<Progress.Item> treeViewController) return treeViewController.GetTreeViewItemDataForId(itemId); var progressItem = m_TreeView.GetItemDataForId<Progress.Item>(itemId); var treeViewItem = new TreeViewItemData<Progress.Item>(itemId, progressItem); var childrenIds = m_TreeView.viewController.GetChildrenIds(itemId); if (childrenIds != null) { var childrenItems = childrenIds.Select(id => GetExistingTreeViewItemFromId(id)); treeViewItem.AddChildren(childrenItems.ToList()); } return treeViewItem; } void AddTreeViewItemToTree(TreeViewItemData<Progress.Item> treeViewItem) { var siblings = GetSiblingItems(treeViewItem.data, out var newParentId); var insertionIndex = GetInsertionIndex(siblings, treeViewItem.data); var defaultController = m_TreeView.viewController as DefaultTreeViewController<Progress.Item>; defaultController.AddItem(treeViewItem, newParentId, insertionIndex); m_ContainedItems.Add(treeViewItem.id); if (m_MissingParents.TryGetValue(treeViewItem.id, out var orphans)) { foreach (var orphanId in orphans) { ReinsertItem(orphanId); } m_MissingParents.Remove(treeViewItem.id); } if (m_ItemsNeedingExpansion.Contains(treeViewItem.data.parentId)) { m_TreeView.viewController.ExpandItem(treeViewItem.data.parentId, true); m_ItemsNeedingExpansion.Remove(treeViewItem.data.parentId); } // We want to restore the previous state of the progress item if applicable. For instance, removing and // re-adding the item should remain expanded if this was previously expanded if (m_RemovedItemsExpandedState.TryGetValue(treeViewItem.id, out var isExpanded) && isExpanded) { m_TreeView.ExpandItem(treeViewItem.id); m_RemovedItemsExpandedState.Remove(treeViewItem.id); } } void RemoveTreeViewItem(int progressId) { // If we are removing a previously expanded item, we just get rid of it, otherwise we store the last expanded state. if (m_RemovedItemsExpandedState.ContainsKey(progressId)) { m_RemovedItemsExpandedState.Remove(progressId); } else { m_RemovedItemsExpandedState.Add(progressId, m_TreeView.IsExpanded(progressId)); } m_TreeView.viewController.TryRemoveItem(progressId); m_ContainedItems.Remove(progressId); } // Internal functions, for testing only internal int GetIndexForProgressId(int progressId) { return m_TreeView.viewController.GetIndexForId(progressId); } internal VisualProgressItem GetVisualProgressItemAtIndex(int index) { var vi = m_TreeView.GetRootElementForIndex(index); return vi.Q<VisualProgressItem>(VisualProgressItem.visualElementName); } internal VisualProgressItem GetVisualProgressItem(int progressId) { var vi = m_TreeView.GetRootElementForId(progressId); return vi.Q<VisualProgressItem>(VisualProgressItem.visualElementName); } internal void ExpandAllItems() { m_TreeView.ExpandAll(); } internal bool IsProgressIdInTree(int progressId) { // Calling ToList is needed here, as GetAllItems uses an internal stacked enumerator that is a member // of the viewController. If the iteration does not complete all the way, it messes with all other calls // to GetAllItems! var allIds = m_TreeView.viewController.GetAllItemIds().ToList(); return allIds.Contains(progressId); } internal bool IsProgressExpanded(int progressId) { return !m_TreeView.viewController.HasChildren(progressId) || m_TreeView.IsExpanded(progressId); } } }
UnityCsReference/Modules/Progress/ProgressWindow.cs/0
{ "file_path": "UnityCsReference/Modules/Progress/ProgressWindow.cs", "repo_id": "UnityCsReference", "token_count": 8289 }
444
// Unity 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.Internal; namespace Unity.Properties { /// <summary> /// Base interface for working with properties. /// </summary> /// <remarks> /// This is used to pass or store properties without knowing the underlying container or value type. /// * <seealso cref="IProperty{TContainer}"/> /// * <seealso cref="Property{TContainer,TValue}"/> /// </remarks> public interface IProperty { /// <summary> /// Gets the name of the property. /// </summary> string Name { get; } /// <summary> /// Gets a value indicating whether the property is read-only or not. /// </summary> bool IsReadOnly { get; } /// <summary> /// Returns the declared value type of the property. /// </summary> /// <returns>The declared value type.</returns> Type DeclaredValueType(); /// <summary> /// Returns true if the property has any attributes of the given type. /// </summary> /// <typeparam name="TAttribute">The attribute type to check for.</typeparam> /// <returns><see langword="true"/> if the property has the given attribute type; otherwise, <see langword="false"/>.</returns> bool HasAttribute<TAttribute>() where TAttribute : Attribute; /// <summary> /// Returns the first attribute of the given type. /// </summary> /// <typeparam name="TAttribute">The attribute type to get.</typeparam> /// <returns>The attribute of the given type for this property.</returns> TAttribute GetAttribute<TAttribute>() where TAttribute : Attribute; /// <summary> /// Returns all attribute of the given type. /// </summary> /// <typeparam name="TAttribute">The attribute type to get.</typeparam> /// <returns>An <see cref="IEnumerable{TAttribute}"/> for all attributes of the given type.</returns> IEnumerable<TAttribute> GetAttributes<TAttribute>() where TAttribute : Attribute; /// <summary> /// Returns all attribute for this property. /// </summary> /// <returns>An <see cref="IEnumerable{Attribute}"/> for all attributes.</returns> IEnumerable<Attribute> GetAttributes(); } /// <summary> /// Base interface for working with properties. /// </summary> /// <remarks> /// This is used to pass or store properties without knowing the underlying value type. /// * <seealso cref="Property{TContainer,TValue}"/> /// </remarks> /// <typeparam name="TContainer">The container type this property operates on.</typeparam> public interface IProperty<TContainer> : IProperty, IPropertyAccept<TContainer> { /// <summary> /// Returns the property value of a specified container. /// </summary> /// <param name="container">The container whose property value will be returned.</param> /// <returns>The property value of the given container.</returns> object GetValue(ref TContainer container); /// <summary> /// Sets the property value of a specified container. /// </summary> /// <param name="container">The container whose property value will be set.</param> /// <param name="value">The new property value.</param> /// <returns><see langword="true"/> if the value was set; otherwise, <see langword="false"/>.</returns> void SetValue(ref TContainer container, object value); } /// <summary> /// Base class for implementing properties. This is an abstract class. /// </summary> /// <remarks> /// A <see cref="IProperty"/> is used as an accessor to the underlying data of a container. /// </remarks> /// <typeparam name="TContainer">The container type this property operates on.</typeparam> /// <typeparam name="TValue">The value type for this property.</typeparam> public abstract class Property<TContainer, TValue> : IProperty<TContainer>, IAttributes { List<Attribute> m_Attributes; /// <summary> /// Collection of attributes for this <see cref="Property{TContainer,TValue}"/>. /// </summary> List<Attribute> IAttributes.Attributes { get => m_Attributes; set => m_Attributes = value; } /// <summary> /// Gets the name of the property. /// </summary> public abstract string Name { get; } /// <summary> /// Gets a value indicating whether the property is read-only or not. /// </summary> public abstract bool IsReadOnly { get; } /// <summary> /// Returns the declared value type of the property. /// </summary> /// <returns>The declared value type.</returns> public Type DeclaredValueType() => typeof(TValue); /// <summary> /// Call this method to invoke <see cref="IPropertyVisitor.Visit{TContainer,TValue}"/> with the strongly typed container and value. /// </summary> /// <param name="visitor">The visitor being run.</param> /// <param name="container">The container being visited.</param> public void Accept(IPropertyVisitor visitor, ref TContainer container) => visitor.Visit(this, ref container); /// <summary> /// Returns the property value of a specified container. /// </summary> /// <param name="container">The container whose property value will be returned.</param> /// <returns>The property value of the given container.</returns> object IProperty<TContainer>.GetValue(ref TContainer container) => GetValue(ref container); /// <summary> /// Sets the property value of a specified container. /// </summary> /// <param name="container">The container whose property value will be set.</param> /// <param name="value">The new property value.</param> /// <returns><see langword="true"/> if the value was set; otherwise, <see langword="false"/>.</returns> void IProperty<TContainer>.SetValue(ref TContainer container, object value) => SetValue(ref container, TypeConversion.Convert<object, TValue>(ref value)); /// <summary> /// Returns the property value of a specified container. /// </summary> /// <param name="container">The container whose property value will be returned.</param> /// <returns>The property value of the given container.</returns> public abstract TValue GetValue(ref TContainer container); /// <summary> /// Sets the property value of a specified container. /// </summary> /// <param name="container">The container whose property value will be set.</param> /// <param name="value">The new property value.</param> public abstract void SetValue(ref TContainer container, TValue value); /// <summary> /// Adds an attribute to the property. /// </summary> /// <param name="attribute">The attribute to add.</param> protected void AddAttribute(Attribute attribute) => ((IAttributes) this).AddAttribute(attribute); /// <summary> /// Adds a set of attributes to the property. /// </summary> /// <param name="attributes">The attributes to add.</param> protected void AddAttributes(IEnumerable<Attribute> attributes) => ((IAttributes) this).AddAttributes(attributes); /// <inheritdoc/> void IAttributes.AddAttribute(Attribute attribute) { if (null == attribute || attribute.GetType() == typeof(CreatePropertyAttribute)) return; if (null == m_Attributes) m_Attributes = new List<Attribute>(); m_Attributes.Add(attribute); } /// <summary> /// Adds a set of attributes to the property. /// </summary> /// <param name="attributes">The attributes to add.</param> void IAttributes.AddAttributes(IEnumerable<Attribute> attributes) { if (null == m_Attributes) m_Attributes = new List<Attribute>(); foreach (var attribute in attributes) { if (null == attribute) continue; m_Attributes.Add(attribute); } } /// <summary> /// Returns true if the property has any attributes of the given type. /// </summary> /// <typeparam name="TAttribute">The attribute type to check for.</typeparam> /// <returns><see langword="true"/> if the property has the given attribute type; otherwise, <see langword="false"/>.</returns> public bool HasAttribute<TAttribute>() where TAttribute : Attribute { for (var i = 0; i < m_Attributes?.Count; i++) { if (m_Attributes[i] is TAttribute) { return true; } } return default; } /// <summary> /// Returns the first attribute of the given type. /// </summary> /// <typeparam name="TAttribute">The attribute type to get.</typeparam> /// <returns>The attribute of the given type for this property.</returns> public TAttribute GetAttribute<TAttribute>() where TAttribute : Attribute { for (var i = 0; i < m_Attributes?.Count; i++) { if (m_Attributes[i] is TAttribute typed) { return typed; } } return default; } /// <summary> /// Returns all attribute of the given type. /// </summary> /// <typeparam name="TAttribute">The attribute type to get.</typeparam> /// <returns>An <see cref="IEnumerable{TAttribute}"/> for all attributes of the given type.</returns> public IEnumerable<TAttribute> GetAttributes<TAttribute>() where TAttribute : Attribute { for (var i = 0; i < m_Attributes?.Count; i++) { if (m_Attributes[i] is TAttribute typed) { yield return typed; } } } /// <summary> /// Returns all attribute for this property. /// </summary> /// <returns>An <see cref="IEnumerable{Attribute}"/> for all attributes.</returns> public IEnumerable<Attribute> GetAttributes() { for (var i = 0; i < m_Attributes?.Count; i++) { yield return m_Attributes[i]; } } /// <inheritdoc/> AttributesScope IAttributes.CreateAttributesScope(IAttributes attributes) => new AttributesScope(this, attributes?.Attributes); } }
UnityCsReference/Modules/Properties/Runtime/Properties/Property.cs/0
{ "file_path": "UnityCsReference/Modules/Properties/Runtime/Properties/Property.cs", "repo_id": "UnityCsReference", "token_count": 4229 }
445
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using Unity.Properties.Internal; namespace Unity.Properties { static partial class PropertyBag { /// <summary> /// Constructs a new instance of the given <see cref="TContainer"/> type. /// </summary> /// <typeparam name="TContainer">The container type to construct.</typeparam> /// <returns>A new instance of <see cref="TContainer"/>.</returns> public static TContainer CreateInstance<TContainer>() { var propertyBag = PropertyBagStore.GetPropertyBag<TContainer>(); if (null == propertyBag) throw new MissingPropertyBagException(typeof(TContainer)); return propertyBag.CreateInstance(); } } }
UnityCsReference/Modules/Properties/Runtime/PropertyBags/PropertyBag+TypeConstruction.cs/0
{ "file_path": "UnityCsReference/Modules/Properties/Runtime/PropertyBags/PropertyBag+TypeConstruction.cs", "repo_id": "UnityCsReference", "token_count": 330 }
446
// Unity 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.Scripting; namespace Unity.Properties.Internal { class ReflectedPropertyBagProvider { readonly MethodInfo m_CreatePropertyMethod; readonly MethodInfo m_CreatePropertyBagMethod; readonly MethodInfo m_CreateIndexedCollectionPropertyBagMethod; readonly MethodInfo m_CreateSetPropertyBagMethod; readonly MethodInfo m_CreateKeyValueCollectionPropertyBagMethod; readonly MethodInfo m_CreateKeyValuePairPropertyBagMethod; readonly MethodInfo m_CreateArrayPropertyBagMethod; readonly MethodInfo m_CreateListPropertyBagMethod; readonly MethodInfo m_CreateHashSetPropertyBagMethod; readonly MethodInfo m_CreateDictionaryPropertyBagMethod; public ReflectedPropertyBagProvider() { m_CreatePropertyMethod = typeof(ReflectedPropertyBagProvider).GetMethod(nameof(CreateProperty), BindingFlags.Instance | BindingFlags.NonPublic); m_CreatePropertyBagMethod = typeof(ReflectedPropertyBagProvider).GetMethods(BindingFlags.Instance | BindingFlags.Public).First(x => x.Name == nameof(CreatePropertyBag) && x.IsGenericMethod); // Generic interface property bag types (e.g. IList<T>, ISet<T>, IDictionary<K, V>) m_CreateIndexedCollectionPropertyBagMethod = typeof(ReflectedPropertyBagProvider).GetMethod(nameof(CreateIndexedCollectionPropertyBag), BindingFlags.Instance | BindingFlags.NonPublic); m_CreateSetPropertyBagMethod = typeof(ReflectedPropertyBagProvider).GetMethod(nameof(CreateSetPropertyBag), BindingFlags.Instance | BindingFlags.NonPublic); m_CreateKeyValueCollectionPropertyBagMethod = typeof(ReflectedPropertyBagProvider).GetMethod(nameof(CreateKeyValueCollectionPropertyBag), BindingFlags.Instance | BindingFlags.NonPublic); m_CreateKeyValuePairPropertyBagMethod = typeof(ReflectedPropertyBagProvider).GetMethod(nameof(CreateKeyValuePairPropertyBag), BindingFlags.Instance | BindingFlags.NonPublic); // Concrete collection property bag types (e.g. List<T>, HashSet<T>, Dictionary<K, V> m_CreateArrayPropertyBagMethod = typeof(ReflectedPropertyBagProvider).GetMethod(nameof(CreateArrayPropertyBag), BindingFlags.Instance | BindingFlags.NonPublic); m_CreateListPropertyBagMethod = typeof(ReflectedPropertyBagProvider).GetMethod(nameof(CreateListPropertyBag), BindingFlags.Instance | BindingFlags.NonPublic); m_CreateHashSetPropertyBagMethod = typeof(ReflectedPropertyBagProvider).GetMethod(nameof(CreateHashSetPropertyBag), BindingFlags.Instance | BindingFlags.NonPublic); m_CreateDictionaryPropertyBagMethod = typeof(ReflectedPropertyBagProvider).GetMethod(nameof(CreateDictionaryPropertyBag), BindingFlags.Instance | BindingFlags.NonPublic); } public IPropertyBag CreatePropertyBag(Type type) { if (type.IsGenericTypeDefinition) return null; return (IPropertyBag) m_CreatePropertyBagMethod.MakeGenericMethod(type).Invoke(this, null); } public IPropertyBag<TContainer> CreatePropertyBag<TContainer>() { if (!TypeTraits<TContainer>.IsContainer || TypeTraits<TContainer>.IsObject) { throw new InvalidOperationException("Invalid container type."); } if (typeof(TContainer).IsArray) { if (typeof(TContainer).GetArrayRank() != 1) { throw new InvalidOperationException("Properties does not support multidimensional arrays."); } return (IPropertyBag<TContainer>) m_CreateArrayPropertyBagMethod.MakeGenericMethod(typeof(TContainer).GetElementType()).Invoke(this, new object[0]); } if (typeof(TContainer).IsGenericType && typeof(TContainer).GetGenericTypeDefinition().IsAssignableFrom(typeof(List<>))) return (IPropertyBag<TContainer>) m_CreateListPropertyBagMethod.MakeGenericMethod(typeof(TContainer).GetGenericArguments().First()).Invoke(this, new object[0]); if (typeof(TContainer).IsGenericType && typeof(TContainer).GetGenericTypeDefinition().IsAssignableFrom(typeof(HashSet<>))) return (IPropertyBag<TContainer>) m_CreateHashSetPropertyBagMethod.MakeGenericMethod(typeof(TContainer).GetGenericArguments().First()).Invoke(this, new object[0]); if (typeof(TContainer).IsGenericType && typeof(TContainer).GetGenericTypeDefinition().IsAssignableFrom(typeof(Dictionary<,>))) return (IPropertyBag<TContainer>) m_CreateDictionaryPropertyBagMethod.MakeGenericMethod(typeof(TContainer).GetGenericArguments().First(), typeof(TContainer).GetGenericArguments().ElementAt(1)).Invoke(this, new object[0]); if (typeof(TContainer).IsGenericType && typeof(TContainer).GetGenericTypeDefinition().IsAssignableFrom(typeof(IList<>))) return (IPropertyBag<TContainer>) m_CreateIndexedCollectionPropertyBagMethod.MakeGenericMethod(typeof(TContainer), typeof(TContainer).GetGenericArguments().First()).Invoke(this, new object[0]); if (typeof(TContainer).IsGenericType && typeof(TContainer).GetGenericTypeDefinition().IsAssignableFrom(typeof(ISet<>))) return (IPropertyBag<TContainer>) m_CreateSetPropertyBagMethod.MakeGenericMethod(typeof(TContainer), typeof(TContainer).GetGenericArguments().First()).Invoke(this, new object[0]); if (typeof(TContainer).IsGenericType && typeof(TContainer).GetGenericTypeDefinition().IsAssignableFrom(typeof(IDictionary<,>))) return (IPropertyBag<TContainer>) m_CreateKeyValueCollectionPropertyBagMethod.MakeGenericMethod(typeof(TContainer), typeof(TContainer).GetGenericArguments().First(), typeof(TContainer).GetGenericArguments().ElementAt(1)).Invoke(this, new object[0]); if (typeof(TContainer).IsGenericType && typeof(TContainer).GetGenericTypeDefinition().IsAssignableFrom(typeof(KeyValuePair<,>))) { var types = typeof(TContainer).GetGenericArguments().ToArray(); return (IPropertyBag<TContainer>) m_CreateKeyValuePairPropertyBagMethod.MakeGenericMethod(types[0], types[1]).Invoke(this, new object[0]); } var propertyBag = new ReflectedPropertyBag<TContainer>(); foreach (var member in GetPropertyMembers(typeof(TContainer))) { IMemberInfo info; switch (member) { case FieldInfo field: info = new FieldMember(field); break; case PropertyInfo property: info = new PropertyMember(property); break; default: throw new InvalidOperationException(); } m_CreatePropertyMethod.MakeGenericMethod(typeof(TContainer), info.ValueType).Invoke(this, new object[] { info, propertyBag }); } return propertyBag; } [Preserve] void CreateProperty<TContainer, TValue>(IMemberInfo member, ReflectedPropertyBag<TContainer> propertyBag) { if (typeof(TValue).IsPointer) { return; } propertyBag.AddProperty(new ReflectedMemberProperty<TContainer, TValue>(member, member.Name)); } [Preserve] IPropertyBag<TList> CreateIndexedCollectionPropertyBag<TList, TElement>() where TList : IList<TElement> => new IndexedCollectionPropertyBag<TList, TElement>(); [Preserve] IPropertyBag<TSet> CreateSetPropertyBag<TSet, TValue>() where TSet : ISet<TValue> => new SetPropertyBagBase<TSet, TValue>(); [Preserve] IPropertyBag<TDictionary> CreateKeyValueCollectionPropertyBag<TDictionary, TKey, TValue>() where TDictionary : IDictionary<TKey, TValue> => new KeyValueCollectionPropertyBag<TDictionary, TKey, TValue>(); [Preserve] IPropertyBag<KeyValuePair<TKey, TValue>> CreateKeyValuePairPropertyBag<TKey, TValue>() => new KeyValuePairPropertyBag<TKey, TValue>(); [Preserve] IPropertyBag<TElement[]> CreateArrayPropertyBag<TElement>() => new ArrayPropertyBag<TElement>(); [Preserve] IPropertyBag<List<TElement>> CreateListPropertyBag<TElement>() => new ListPropertyBag<TElement>(); [Preserve] IPropertyBag<HashSet<TElement>> CreateHashSetPropertyBag<TElement>() => new HashSetPropertyBag<TElement>(); [Preserve] IPropertyBag<Dictionary<TKey, TValue>> CreateDictionaryPropertyBag<TKey, TValue>() => new DictionaryPropertyBag<TKey, TValue>(); static IEnumerable<MemberInfo> GetPropertyMembers(Type type) { do { var members = type.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic).OrderBy(x => x.MetadataToken); foreach (var member in members) { if (member.MemberType != MemberTypes.Field && member.MemberType != MemberTypes.Property) { continue; } if (member.DeclaringType != type) { continue; } if (!IsValidMember(member)) { continue; } // Gather all possible attributes we care about. var hasDontCreatePropertyAttribute = member.GetCustomAttribute<DontCreatePropertyAttribute>() != null; var hasCreatePropertyAttribute = member.GetCustomAttribute<CreatePropertyAttribute>() != null; var hasNonSerializedAttribute = member.GetCustomAttribute<NonSerializedAttribute>() != null; var hasSerializedFieldAttribute = member.GetCustomAttribute<SerializeField>() != null; var hasSerializeReferenceAttribute = member.GetCustomAttribute<SerializeReference>() != null; if (hasDontCreatePropertyAttribute) { // This attribute trumps all others. No matter what a property should NOT be generated. continue; } if (hasCreatePropertyAttribute) { // The user explicitly requests an attribute, one will be generated, regardless of serialization attributes. yield return member; continue; } if (hasNonSerializedAttribute) { // If property generation was not explicitly specified lets keep behaviour consistent with Unity. continue; } if (hasSerializedFieldAttribute) { // If property generation was not explicitly specified lets keep behaviour consistent with Unity. yield return member; continue; } if (hasSerializeReferenceAttribute) { // If property generation was not explicitly specified lets keep behaviour consistent with Unity. yield return member; continue; } // No attributes were specified, if this is a public field we will generate one by implicitly. if (member is FieldInfo field && field.IsPublic) { yield return member; } } type = type.BaseType; } while (type != null && type != typeof(object)); } static bool IsValidMember(MemberInfo memberInfo) { switch (memberInfo) { case FieldInfo fieldInfo: return !fieldInfo.IsStatic && IsValidPropertyType(fieldInfo.FieldType); case PropertyInfo propertyInfo: return null != propertyInfo.GetMethod && !propertyInfo.GetMethod.IsStatic && IsValidPropertyType(propertyInfo.PropertyType); } return false; } static bool IsValidPropertyType(Type type) { if (type.IsPointer) return false; return !type.IsGenericType || type.GetGenericArguments().All(IsValidPropertyType); } } }
UnityCsReference/Modules/Properties/Runtime/Reflection/Internal/ReflectedPropertyBagProvider.cs/0
{ "file_path": "UnityCsReference/Modules/Properties/Runtime/Reflection/Internal/ReflectedPropertyBagProvider.cs", "repo_id": "UnityCsReference", "token_count": 5615 }
447
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; namespace UnityEditor.Search { internal enum SearchIndexOperator { Contains, Equal, NotEqual, Greater, GreaterOrEqual, Less, LessOrEqual, DoNotCompareScore, None } class SearchIndexComparer : IComparer<SearchIndexEntry>, IEqualityComparer<SearchIndexEntry> { public SearchIndexOperator op { get; private set; } public SearchIndexComparer(SearchIndexOperator op = SearchIndexOperator.Contains) { this.op = op; } public int Compare(SearchIndexEntry item1, SearchIndexEntry item2) { var c = item1.type.CompareTo(item2.type); if (c != 0) return c; c = item1.crc.CompareTo(item2.crc); if (c != 0) return c; if (item1.type == SearchIndexEntry.Type.Number) { double eps = 0.0; if (op == SearchIndexOperator.Less) eps = -Utils.DOUBLE_EPSILON; else if (op == SearchIndexOperator.Greater) eps = Utils.DOUBLE_EPSILON; else if (op == SearchIndexOperator.Equal || op == SearchIndexOperator.Contains || op == SearchIndexOperator.GreaterOrEqual || op == SearchIndexOperator.LessOrEqual) { if (Utils.Approximately(item1.number, item2.number)) return 0; } c = item1.number.CompareTo(item2.number + eps); } else c = item1.key.CompareTo(item2.key); if (c != 0 || op == SearchIndexOperator.DoNotCompareScore) return c; if (item2.score == int.MaxValue) return 0; return item1.score.CompareTo(item2.score); } public bool Equals(SearchIndexEntry x, SearchIndexEntry y) { return x.Equals(y); } public int GetHashCode(SearchIndexEntry obj) { return obj.GetHashCode(); } } }
UnityCsReference/Modules/QuickSearch/Editor/Indexing/SearchIndexComparer.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/Indexing/SearchIndexComparer.cs", "repo_id": "UnityCsReference", "token_count": 1165 }
448
// Unity 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 UnityEditor; namespace UnityEditor.Search { namespace Providers { static class Calculator { internal static string type = "calculator"; internal static string displayName = "Calculator"; [SearchItemProvider] internal static SearchProvider CreateProvider() { return new SearchProvider(type, displayName) { priority = 10, filterId = "=", isExplicitProvider = true, fetchItems = (context, items, provider) => Compute(context, provider), fetchThumbnail = (item, context) => Icons.settings }; } internal static IEnumerable<SearchItem> Compute(SearchContext context, SearchProvider provider) { var expression = context.searchQuery; if (Evaluate(context.searchQuery, out var result)) expression += " = " + result; var calcItem = provider.CreateItem(context, result.ToString(), "compute", expression, null, null); calcItem.value = result; yield return calcItem; } [SearchActionsProvider] internal static IEnumerable<SearchAction> ActionHandlers() { return new[] { new SearchAction(type, "exec", null, "Compute") { handler = (item) => { if (Evaluate(item.context.searchQuery, out var result)) { UnityEngine.Debug.Log(result); EditorGUIUtility.systemCopyBuffer = result.ToString(CultureInfo.InvariantCulture); } } } }; } internal static bool Evaluate(string expression, out double result) { try { return UnityEngine.ExpressionEvaluator.Evaluate(expression, out result); } catch (Exception) { result = 0.0; UnityEngine.Debug.LogError("Error while parsing: " + expression); return false; } } } } }
UnityCsReference/Modules/QuickSearch/Editor/Providers/Calculator.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/Providers/Calculator.cs", "repo_id": "UnityCsReference", "token_count": 1410 }
449
// 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 UnityEngine.UIElements; namespace UnityEditor.Search { interface IQueryExpressionBlock { QueryBuilder builder { get; } IQuerySource source { get; } IBlockEditor editor { get; } void CloseEditor(); void ApplyExpression(string searchText); void ApplyChanges(); } static class ExpressionBlock { public static QueryBuilder Create(in string expression) { var embeddedBuilder = new QueryBuilder(expression) { @readonly = true }; foreach (var b in embeddedBuilder.blocks) { b.@readonly = true; b.disableHovering = true; } return embeddedBuilder; } } class QueryExpressionBlock : QueryBlock { private SearchExpression m_Expression; private List<QueryBuilder> m_ArgumentBuilders; internal override bool canDisable => false; internal override bool canExclude => false; internal override bool wantsEvents => true; public QueryExpressionBlock(IQuerySource source, SearchExpression expression) : base(source) { name = ObjectNames.NicifyVariableName(expression.name); value = expression.outerText.ToString(); m_Expression = expression; m_ArgumentBuilders = expression.parameters.Select(p => ExpressionBlock.Create(p.outerText.ToString())).ToList(); } public override string ToString() => m_Expression.outerText.ToString(); internal override IBlockEditor OpenEditor(in Rect rect) { return null; } internal override Color GetBackgroundColor() => QueryColors.expression; internal override void CreateBlockElement(VisualElement container) { AddLabel(container, name); AddSeparator(container); foreach (var builder in m_ArgumentBuilders) { foreach(var b in builder.EnumerateBlocks()) container.Add(b.CreateGUI()); AddSeparator(container); } } } class QueryExpressionBlockEditor : SearchWindow, IBlockEditor { public EditorWindow window => this; public IQueryExpressionBlock block { get; protected set; } public static IBlockEditor Open(in Rect rect, IQueryExpressionBlock block) { var qb = block.builder; var searchFlags = SearchFlags.None; var searchContext = SearchService.CreateContext(qb.searchText, searchFlags); var viewState = new SearchViewState(searchContext, UnityEngine.Search.SearchViewFlags.OpenInBuilderMode | UnityEngine.Search.SearchViewFlags.DisableSavedSearchQuery | UnityEngine.Search.SearchViewFlags.Borderless | UnityEngine.Search.SearchViewFlags.DisableInspectorPreview) { ignoreSaveSearches = true }; var w = Create<QueryExpressionBlockEditor>(viewState) as QueryExpressionBlockEditor; w.block = block; w.minSize = Vector2.zero; w.maxSize = new Vector2(600, 300); var popupRect = new Rect(rect.x, rect.yMax, rect.width, rect.height); var windowRect = new Rect(rect.x, rect.yMax + rect.height, rect.width, rect.height); w.ShowAsDropDown(popupRect, w.maxSize); w.position = windowRect; w.m_Parent.window.m_DontSaveToLayout = true; return w; } internal new void OnDisable() { Apply(); block.CloseEditor(); base.OnDisable(); } protected override void UpdateAsyncResults() { base.UpdateAsyncResults(); Apply(); } void Apply() { block.ApplyExpression(context.searchText); block.ApplyChanges(); } } }
UnityCsReference/Modules/QuickSearch/Editor/QueryBuilder/Blocks/QueryExpressionBlock.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/QueryBuilder/Blocks/QueryExpressionBlock.cs", "repo_id": "UnityCsReference", "token_count": 1832 }
450
// 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.Search { class DefaultQueryHandlerFactory<TData> : IQueryHandlerFactory<TData, DefaultQueryHandler<TData>, IEnumerable<TData>> { QueryEngine<TData> m_Engine; bool m_FastYielding; public DefaultQueryHandlerFactory(QueryEngine<TData> engine, bool fastYielding = false) { m_Engine = engine; m_FastYielding = fastYielding; } public DefaultQueryHandler<TData> Create(QueryGraph graph, ICollection<QueryError> errors) { if (errors.Count > 0) return null; var dataWalker = new DefaultQueryHandler<TData>(); dataWalker.Initialize(m_Engine, graph, errors, m_FastYielding); return dataWalker; } } class DefaultQueryHandler<TData> : IQueryHandler<TData, IEnumerable<TData>> { IQueryEnumerable<TData> m_QueryEnumerable; public void Initialize(QueryEngine<TData> engine, QueryGraph graph, ICollection<QueryError> errors, bool fastYielding) { if (graph != null && !graph.empty) m_QueryEnumerable = EnumerableCreator.Create(graph.root, engine, errors, fastYielding); } public IEnumerable<TData> Eval(IEnumerable<TData> payload) { if (payload == null || m_QueryEnumerable == null) return new TData[] {}; m_QueryEnumerable.SetPayload(payload); return m_QueryEnumerable; } public bool Eval(TData element) { if (element == null || !(m_QueryEnumerable is WhereEnumerable<TData> we)) return false; return we.predicate != null && we.predicate(element); } } }
UnityCsReference/Modules/QuickSearch/Editor/QueryEngine/DefaultQueryHandler.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/QueryEngine/DefaultQueryHandler.cs", "repo_id": "UnityCsReference", "token_count": 825 }
451
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEditor.Search { /// <summary> /// Structure containing the different options used to optimize a query graph. /// </summary> public struct QueryGraphOptimizationOptions { /// <summary> /// Propagate "Not" operations to leaves, so only leaves can have "Not" operations as parents. /// </summary> public bool propagateNotToLeaves; /// <summary> /// Swaps "Not" operations to the right hand side of combining operations (i.e. "And", "Or"). Useful if a "Not" operation is slow. /// </summary> public bool swapNotToRightHandSide; /// <summary> /// Swaps filter functions to the right hand side of combining operations (i.e. "And", "Or"). Useful if those filter operations are slow. /// </summary> public bool swapFilterFunctionsToRightHandSide; } /// <summary> /// Class that represents a query graph. /// </summary> public class QueryGraph { /// <summary> /// Root node of the graph. Can be null. /// </summary> public IQueryNode root { get; private set; } /// <summary> /// Returns true if the graph is empty. /// </summary> public bool empty => root == null; /// <summary> /// Constructor. Creates a new query graph. /// </summary> /// <param name="root">Root node of the graph.</param> public QueryGraph(IQueryNode root) { this.root = root; } /// <summary> /// Optimize the graph. /// </summary> /// <param name="propagateNotToLeaves">Propagate "Not" operations to leaves, so only leaves can have "Not" operations as parents.</param> /// <param name="swapNotToRightHandSide">Swaps "Not" operations to the right hand side of combining operations (i.e. "And", "Or"). Useful if a "Not" operation is slow.</param> public void Optimize(bool propagateNotToLeaves, bool swapNotToRightHandSide) { if (empty) return; Optimize(root, new QueryGraphOptimizationOptions {propagateNotToLeaves = propagateNotToLeaves, swapNotToRightHandSide = swapNotToRightHandSide, swapFilterFunctionsToRightHandSide = false}); } /// <summary> /// Optimize the graph. /// </summary> /// <param name="options">Optimization options.</param> public void Optimize(QueryGraphOptimizationOptions options) { if (empty) return; Optimize(root, options); } void Optimize(IQueryNode rootNode, QueryGraphOptimizationOptions options) { if (rootNode.leaf) return; if (options.propagateNotToLeaves) { PropagateNotToLeaves(ref rootNode); } if (options.swapNotToRightHandSide) { SwapNotToRightHandSide(rootNode); } if (options.swapFilterFunctionsToRightHandSide) { SwapFilterFunctionsToRightHandSide(rootNode); } // ReSharper disable once ForCanBeConvertedToForeach for (var i = 0; i < rootNode.children.Count; ++i) { Optimize(rootNode.children[i], options); } // Reduce Not depth (do this as last step) ReduceNotDepth(rootNode); } static void SwapChild(IQueryNode parent, IQueryNode oldChild, IQueryNode newChild) { if (parent?.children == null || parent.children.Count == 0) return; var oldIndex = parent.children.IndexOf(oldChild); parent.children[oldIndex] = newChild; oldChild.parent = null; newChild.parent = parent; } void PropagateNotToLeaves(ref IQueryNode rootNode) { if (rootNode.leaf || !(rootNode is CombinedNode cn)) return; if (rootNode.type != QueryNodeType.Not) return; var parent = rootNode.parent; var oldNode = rootNode.children[0]; if (!(oldNode is CombinedNode oldCombinedNode) || (oldCombinedNode.type != QueryNodeType.And && oldCombinedNode.type != QueryNodeType.Or)) return; CombinedNode newCombinedNode; if (oldNode.type == QueryNodeType.And) newCombinedNode = new OrNode(); else newCombinedNode = new AndNode(); cn.RemoveNode(oldNode); foreach (var child in oldNode.children) { var propagatedNotNode = new NotNode(); propagatedNotNode.AddNode(child); newCombinedNode.AddNode(propagatedNotNode); } oldCombinedNode.Clear(); // If the old not is the root of the evaluationGraph, then the new combined node // becomes the new root. if (parent == null) this.root = newCombinedNode; else { // In order to not change the parent's enumeration, swap directly the old // children with the new one SwapChild(parent, rootNode, newCombinedNode); } // Set the current tree root to the new combined node. rootNode = newCombinedNode; } static void SwapNotToRightHandSide(IQueryNode rootNode) { if (rootNode.leaf || !(rootNode.children[0] is NotNode) || !(rootNode is CombinedNode cn)) return; cn.SwapChildNodes(); } static void SwapFilterFunctionsToRightHandSide(IQueryNode rootNode) { if (rootNode.leaf || !(rootNode is CombinedNode cn) || !(rootNode.children[0] is FilterNode fn) || !fn.filter.usesParameter) return; cn.SwapChildNodes(); } void ReduceNotDepth(IQueryNode rootNode) { if (rootNode.leaf) return; if (rootNode.type != QueryNodeType.Not || rootNode.children[0].type != QueryNodeType.Not) return; var parent = rootNode.parent; if (!(rootNode is NotNode notNode) || !(rootNode.children[0] is NotNode childNotNode)) return; var descendant = childNotNode.children[0]; childNotNode.RemoveNode(descendant); notNode.RemoveNode(childNotNode); if (parent == null) this.root = descendant; else { SwapChild(parent, rootNode, descendant); } } } }
UnityCsReference/Modules/QuickSearch/Editor/QueryEngine/QueryGraph.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/QueryEngine/QueryGraph.cs", "repo_id": "UnityCsReference", "token_count": 3136 }
452
// 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.Collections; using System.Collections.Generic; using System; using System.ComponentModel; namespace UnityEditor.Search { static partial class Evaluators { private static int DefaultComparer(object a, object b) { if (Utils.TryGetNumber(a, out var da) && Utils.TryGetNumber(b, out var db)) return Comparer.DefaultInvariant.Compare(da, db); return Comparer.DefaultInvariant.Compare(a, b); } public static IEnumerable<SearchItem> Compare(SearchExpressionContext c, Func<object, object, bool> comparer) { if (c.args.Length < 2 || c.args.Length > 3) c.ThrowError($"Invalid arguments"); if (c.args.Length == 3 && !IsSelectorLiteral(c.args[1])) c.ThrowError($"Invalid selector"); var setExpr = c.args[0]; if (!setExpr.types.IsIterable()) c.ThrowError("Primary set is not iterable", setExpr.outerText); string valueSelector = null; var compareExprIndex = 1; if (c.args.Length == 3) { valueSelector = c.args[1].innerText.ToString(); compareExprIndex++; } var compareExpr = c.args[compareExprIndex]; var compareValueItr = compareExpr.Execute(c).FirstOrDefault(e => e != null); if (compareValueItr == null) c.ThrowError("Invalid comparer value", compareExpr.outerText); var compareValue = compareValueItr.value; if (valueSelector == null) { return setExpr.Execute(c).Where(item => item != null && comparer(item.GetValue(valueSelector), compareValue)); } return TaskEvaluatorManager.EvaluateMainThread(setExpr.Execute(c), item => { var value = SelectorManager.SelectValue(item, c.search, valueSelector); if (value != null && comparer(value, compareValue)) return item; return null; }, 25); } [Description("Keep search results that have a greater value."), Category("Comparers")] [SearchExpressionEvaluator(SearchExpressionType.Iterable, SearchExpressionType.Literal | SearchExpressionType.QueryString)] [SearchExpressionEvaluatorSignatureOverload(SearchExpressionType.Iterable, SearchExpressionType.Selector, SearchExpressionType.Literal | SearchExpressionType.QueryString)] static IEnumerable<SearchItem> gt(SearchExpressionContext c) => Compare(c, (a, b) => DefaultComparer(a, b) > 0); [Description("Keep search results that have a greater or equal value."), Category("Comparers")] [SearchExpressionEvaluator(SearchExpressionType.Iterable, SearchExpressionType.Literal | SearchExpressionType.QueryString)] [SearchExpressionEvaluatorSignatureOverload(SearchExpressionType.Iterable, SearchExpressionType.Selector, SearchExpressionType.Literal | SearchExpressionType.QueryString)] static IEnumerable<SearchItem> gte(SearchExpressionContext c) => Compare(c, (a, b) => DefaultComparer(a, b) >= 0); [Description("Keep search results that have a lower value."), Category("Comparers")] [SearchExpressionEvaluator(SearchExpressionType.Iterable, SearchExpressionType.Literal | SearchExpressionType.QueryString)] [SearchExpressionEvaluatorSignatureOverload(SearchExpressionType.Iterable, SearchExpressionType.Selector, SearchExpressionType.Literal | SearchExpressionType.QueryString)] static IEnumerable<SearchItem> lw(SearchExpressionContext c) => Compare(c, (a, b) => DefaultComparer(a, b) < 0); [Description("Keep search results that have a lower or equal value."), Category("Comparers")] [SearchExpressionEvaluator(SearchExpressionType.Iterable, SearchExpressionType.Literal | SearchExpressionType.QueryString)] [SearchExpressionEvaluatorSignatureOverload(SearchExpressionType.Iterable, SearchExpressionType.Selector, SearchExpressionType.Literal | SearchExpressionType.QueryString)] static IEnumerable<SearchItem> lwe(SearchExpressionContext c) => Compare(c, (a, b) => DefaultComparer(a, b) <= 0); [Description("Keep search results that have an equal value."), Category("Comparers")] [SearchExpressionEvaluator(SearchExpressionType.Iterable, SearchExpressionType.Literal | SearchExpressionType.QueryString)] [SearchExpressionEvaluatorSignatureOverload(SearchExpressionType.Iterable, SearchExpressionType.Selector, SearchExpressionType.Literal | SearchExpressionType.QueryString)] static IEnumerable<SearchItem> eq(SearchExpressionContext c) => Compare(c, (a, b) => DefaultComparer(a, b) == 0); [Description("Keep search results that have a different value."), Category("Comparers")] [SearchExpressionEvaluator(SearchExpressionType.Iterable, SearchExpressionType.Literal | SearchExpressionType.QueryString)] [SearchExpressionEvaluatorSignatureOverload(SearchExpressionType.Iterable, SearchExpressionType.Selector, SearchExpressionType.Literal | SearchExpressionType.QueryString)] static IEnumerable<SearchItem> neq(SearchExpressionContext c) => Compare(c, (a, b) => DefaultComparer(a, b) != 0); [Description("Exclude search results for which the expression is not valid."), Category("Comparers")] [SearchExpressionEvaluatorSignatureOverload(SearchExpressionType.Keyword, SearchExpressionType.Iterable, SearchExpressionType.QueryString)] [SearchExpressionEvaluator(SearchExpressionType.Iterable, SearchExpressionType.Text | SearchExpressionType.QueryString | SearchExpressionType.Selector)] public static IEnumerable<SearchItem> Where(SearchExpressionContext c) { if (c.args.Length == 3) { var keyword = c.args[0].innerText; var setExpr = c.args[1].Execute(c); var whereQuery = c.args[2]; if (keyword == "none") { return WhereNone(c, setExpr, whereQuery); } else if (keyword == "any") { return WhereAny(c, setExpr, whereQuery); } else { c.ThrowError($"Unknown keyword for where evaluator: {keyword}"); return null; } } else { var setExpr = c.args[0]; var whereConditionExpr = c.args[1]; var queryStr = whereConditionExpr.innerText; if (whereConditionExpr.types.HasFlag(SearchExpressionType.Selector)) { queryStr = whereConditionExpr.outerText; } var setResults = setExpr.Execute(c); return EvaluatorManager.itemQueryEngine.WhereMainThread(c, setResults, queryStr.ToString()); } } public static IEnumerable<SearchItem> WhereAny(SearchExpressionContext c, IEnumerable<SearchItem> mapSet, SearchExpression mapQuery) { foreach (var m in mapSet) { if (m == null) yield return null; else { using (c.runtime.Push(m)) { foreach (var e in mapQuery.Execute(c)) { if (e != null) { yield return m; break; } else { yield return null; } } } } } } public static IEnumerable<SearchItem> WhereNone(SearchExpressionContext c, IEnumerable<SearchItem> mapSet, SearchExpression mapQuery) { foreach (var m in mapSet) { if (m == null) yield return null; else { using (c.runtime.Push(m)) { var yieldResults = false; foreach (var e in mapQuery.Execute(c)) { if (e != null) { yieldResults = true; break; } } if (!yieldResults) { yield return m; } } } } } } }
UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Evaluators/CompareEvaluators.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Evaluators/CompareEvaluators.cs", "repo_id": "UnityCsReference", "token_count": 4283 }
453
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.ComponentModel; namespace UnityEditor.Search { static partial class Evaluators { [SearchExpressionEvaluator(SearchExpressionType.AnyExpression | SearchExpressionType.Variadic)] [Description("Produces the unique set union of multiple expression."), Category("Set Manipulation")] public static IEnumerable<SearchItem> Union(SearchExpressionContext c) { if (c.args == null || c.args.Length == 0) c.ThrowError("Nothing to merge"); var set = new HashSet<int>(); foreach (var e in c.args) { foreach (var item in e.Execute(c)) { if (item == null) yield return null; else if (set.Add(item.value.GetHashCode())) yield return item; } } } [SearchExpressionEvaluator(SearchExpressionType.AnyExpression | SearchExpressionType.Variadic)] [Description("Produces the unique set union of multiple expression."), Category("Set Manipulation")] public static IEnumerable<SearchItem> Distinct(SearchExpressionContext c) { return Union(c); } } }
UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Evaluators/UnionEvaluator.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Evaluators/UnionEvaluator.cs", "repo_id": "UnityCsReference", "token_count": 631 }
454
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Linq; using System.Collections.Generic; using UnityEngine; using System.Text.RegularExpressions; namespace UnityEditor.Search { readonly struct PropertyRange { public readonly float min; public readonly float max; public PropertyRange(float min, float max) { this.min = min; this.max = max; } public bool Contains(float f) { if (f >= min && f <= max) return true; return false; } } readonly struct SearchColor : IEquatable<SearchColor>, IComparable<SearchColor> { public readonly byte r; public readonly byte g; public readonly byte b; public readonly byte a; public SearchColor(Color c) { r = (byte)Mathf.RoundToInt(c.r * 255f); g = (byte)Mathf.RoundToInt(c.g * 255f); b = (byte)Mathf.RoundToInt(c.b * 255f); a = (byte)Mathf.RoundToInt(c.a * 255f); } public SearchColor(byte r, byte g, byte b, byte a) { this.r = r; this.g = g; this.b = b; this.a = a; } public byte this[int index] { get { switch (index) { case 0: return r; case 1: return g; case 2: return b; case 3: return a; default: throw new IndexOutOfRangeException("Invalid Color index(" + index + ")!"); } } } public bool Equals(SearchColor other) { for (var i = 0; i < 4; ++i) { if (this[i] != other[i]) return false; } return true; } public override bool Equals(object obj) { if (obj is SearchColor ic) return base.Equals(ic); return false; } public override int GetHashCode() { return r.GetHashCode() ^ (g.GetHashCode() << 2) ^ (b.GetHashCode() >> 2) ^ (a.GetHashCode() >> 1); } public int CompareTo(SearchColor other) { for (var i = 0; i < 4; ++i) { if (this[i] > other[i]) return 1; if (this[i] < other[i]) return -1; } return 0; } public static bool operator==(SearchColor lhs, SearchColor rhs) { return lhs.Equals(rhs); } public static bool operator!=(SearchColor lhs, SearchColor rhs) { return !lhs.Equals(rhs); } public static bool operator>(SearchColor lhs, SearchColor rhs) { return lhs.CompareTo(rhs) > 0; } public static bool operator<(SearchColor lhs, SearchColor rhs) { return lhs.CompareTo(rhs) < 0; } public static bool operator>=(SearchColor lhs, SearchColor rhs) { return lhs.CompareTo(rhs) >= 0; } public static bool operator<=(SearchColor lhs, SearchColor rhs) { return lhs.CompareTo(rhs) <= 0; } public override string ToString() { return $"RGBA({r}, {g}, {b}, {a})"; } } public readonly struct SearchValue { public enum ValueType : byte { Nil = 0, Bool, Number, Text, Color, Enum, Object, Vector2, Vector3, Vector4 } public readonly ValueType type; [Obsolete("Change type to a float. Please use floatNumber instead.", true)] public readonly double number = double.NaN; public readonly float floatNumber; public readonly string text; internal readonly Vector4 v4; internal readonly SearchColor color; public bool boolean => type == ValueType.Bool && floatNumber == 1d; public bool valid => type != ValueType.Nil; public static SearchValue invalid = new SearchValue(); public SearchValue(bool v) { this.type = ValueType.Bool; this.floatNumber = v ? 1f : 0f; this.text = null; this.color = default; this.v4 = Vector4.zero; } public SearchValue(float number) { this.type = ValueType.Number; this.floatNumber = number; this.text = null; this.color = default; this.v4 = Vector4.zero; } public SearchValue(double number) { this.type = ValueType.Number; this.floatNumber = (float)number; this.text = null; this.color = default; this.v4 = Vector4.zero; } public SearchValue(string text) { this.type = ValueType.Text; this.floatNumber = float.NaN; this.text = text; this.color = default; this.v4 = Vector4.zero; } public SearchValue(Color color) { this.type = ValueType.Color; this.floatNumber = float.NaN; this.text = null; this.color = new SearchColor(color); this.v4 = Vector4.zero; } internal SearchValue(SearchColor color) { this.type = ValueType.Color; this.floatNumber = float.NaN; this.text = null; this.color = color; this.v4 = Vector4.zero; } internal SearchValue(Vector4 v, int dim) { this.type = dim == 2 ? ValueType.Vector2 : (dim == 3 ? ValueType.Vector3 : ValueType.Vector4); this.floatNumber = float.NaN; this.text = null; this.color = default; this.v4 = v; } internal SearchValue(UnityEngine.Object obj) { this.type = ValueType.Object; this.text = SearchUtils.GetObjectPath(obj); this.floatNumber = float.NaN; this.color = default; this.v4 = default; } internal SearchValue(UnityEngine.Object obj, in string path) { this.type = ValueType.Object; this.text = obj ? SearchUtils.GetObjectPath(obj) : path; this.floatNumber = float.NaN; this.color = default; this.v4 = default; } internal SearchValue(int enumIntegerValue, string enumStringValue) { this.type = ValueType.Enum; this.floatNumber = enumIntegerValue; this.text = enumStringValue; this.color = default; this.v4 = default; } public SearchValue(object v) { this.type = ValueType.Nil; this.floatNumber = float.NaN; this.text = null; this.color = default; this.v4 = Vector4.zero; if (v is bool b) { this.type = ValueType.Bool; this.floatNumber = b ? 1 : 0; } else if (v is string s) { this.type = ValueType.Text; this.text = s; } else if (v is Color c) { this.type = ValueType.Color; this.color = new SearchColor(c); } else if (Utils.TryGetFloat(v, out var f)) { this.type = ValueType.Number; this.floatNumber = f; } else if (v is Vector2 v2) { this.type = ValueType.Vector2; this.v4 = v2; } else if (v is Vector2 v3) { this.type = ValueType.Vector3; this.v4 = v3; } else if (v is Vector2 v4) { this.type = ValueType.Vector4; this.v4 = v4; } else if (v is UnityEngine.Object obj) { this.type = ValueType.Object; this.text = SearchUtils.GetObjectPath(obj); } else if (v != null) { this.type = ValueType.Text; this.text = v.ToString(); } } public override string ToString() { switch (type) { case ValueType.Bool: return $"{boolean} [{type}]"; case ValueType.Number: return $"{floatNumber} [{type}]"; case ValueType.Text: return $"{text} [{type}]"; case ValueType.Color: return $"{color} [{type}]"; case ValueType.Vector2: case ValueType.Vector3: case ValueType.Vector4: return $"{v4} [{type}]"; case ValueType.Object: return $"{text} [{type}]"; case ValueType.Enum: return $"{floatNumber} ({text}) [{type}]"; } return "nil"; } internal static bool IsSearchableProperty(in SerializedPropertyType type) { switch (type) { case SerializedPropertyType.Generic: case SerializedPropertyType.LayerMask: case SerializedPropertyType.AnimationCurve: case SerializedPropertyType.Gradient: case SerializedPropertyType.ExposedReference: case SerializedPropertyType.FixedBufferSize: case SerializedPropertyType.ManagedReference: return false; default: return true; } } public static SearchValue ConvertPropertyValue(in SerializedProperty sp) { switch (sp.propertyType) { case SerializedPropertyType.ArraySize: case SerializedPropertyType.Integer: case SerializedPropertyType.Character: var managedType = sp.GetManagedType(); if (managedType != null && managedType.IsEnum) return new SearchValue(sp.intValue, PropertySelectors.GetEnumValue(managedType, sp)); return new SearchValue(Convert.ToSingle(sp.intValue)); case SerializedPropertyType.Boolean: return new SearchValue(sp.boolValue); case SerializedPropertyType.Float: return new SearchValue(sp.floatValue); case SerializedPropertyType.String: return new SearchValue(sp.stringValue); case SerializedPropertyType.Enum: managedType = sp.GetManagedType(); if (managedType != null && managedType.IsEnum) return new SearchValue(sp.intValue, PropertySelectors.GetEnumValue(managedType, sp)); return new SearchValue(sp.enumValueIndex, PropertySelectors.GetEnumValue(sp)); case SerializedPropertyType.ObjectReference: return new SearchValue(sp.objectReferenceValue); case SerializedPropertyType.Bounds: return new SearchValue(sp.boundsValue.size.magnitude); case SerializedPropertyType.BoundsInt: return new SearchValue(sp.boundsIntValue.size.magnitude); case SerializedPropertyType.Rect: return new SearchValue(new Vector4(sp.rectValue.x, sp.rectValue.y, sp.rectValue.width, sp.rectValue.height), 4); case SerializedPropertyType.RectInt: return new SearchValue(new Vector4(sp.rectIntValue.x, sp.rectIntValue.y, sp.rectIntValue.width, sp.rectIntValue.height), 4); case SerializedPropertyType.Color: return new SearchValue(sp.colorValue); case SerializedPropertyType.Vector2: return new SearchValue(new Vector4(sp.vector2Value.x, sp.vector2Value.y), 2); case SerializedPropertyType.Vector3: return new SearchValue(new Vector4(sp.vector3Value.x, sp.vector3Value.y, sp.vector3Value.z), 3); case SerializedPropertyType.Vector4: return new SearchValue(new Vector4(sp.vector4Value.x, sp.vector4Value.y, sp.vector4Value.z, sp.vector4Value.w), 4); case SerializedPropertyType.Quaternion: { var euler = sp.quaternionValue.eulerAngles; return new SearchValue(new Vector4(euler.x, euler.y, euler.z), 3); } case SerializedPropertyType.Vector2Int: return new SearchValue(new Vector4(sp.vector2IntValue.x, sp.vector2IntValue.y), 2); case SerializedPropertyType.Vector3Int: return new SearchValue(new Vector4(sp.vector3IntValue.x, sp.vector3IntValue.y, sp.vector3IntValue.z), 3); case SerializedPropertyType.Hash128: return new SearchValue(sp.hash128Value.ToString()); } if (sp.isArray) return new SearchValue(sp.arraySize); return SearchValue.invalid; } public static void SetupEngine<T>(QueryEngine<T> queryEngine) { queryEngine.AddOperatorHandler(":", (SearchValue v, PropertyRange range) => PropertyRangeCompare(SearchIndexOperator.Contains, v, range)); queryEngine.AddOperatorHandler("=", (SearchValue v, PropertyRange range) => PropertyRangeCompare(SearchIndexOperator.Equal, v, range)); queryEngine.AddOperatorHandler("!=", (SearchValue v, PropertyRange range) => PropertyRangeCompare(SearchIndexOperator.NotEqual, v, range)); queryEngine.AddOperatorHandler("<=", (SearchValue v, PropertyRange range) => PropertyRangeCompare(SearchIndexOperator.LessOrEqual, v, range)); queryEngine.AddOperatorHandler("<", (SearchValue v, PropertyRange range) => PropertyRangeCompare(SearchIndexOperator.Less, v, range)); queryEngine.AddOperatorHandler(">", (SearchValue v, PropertyRange range) => PropertyRangeCompare(SearchIndexOperator.Greater, v, range)); queryEngine.AddOperatorHandler(">=", (SearchValue v, PropertyRange range) => PropertyRangeCompare(SearchIndexOperator.GreaterOrEqual, v, range)); queryEngine.AddOperatorHandler(":", (SearchValue v, float number, StringComparison sc) => PropertyFloatCompare(SearchIndexOperator.Contains, v, number)); queryEngine.AddOperatorHandler("=", (SearchValue v, float number) => PropertyFloatCompare(SearchIndexOperator.Equal, v, number)); queryEngine.AddOperatorHandler("!=", (SearchValue v, float number) => PropertyFloatCompare(SearchIndexOperator.NotEqual, v, number)); queryEngine.AddOperatorHandler("<=", (SearchValue v, float number) => PropertyFloatCompare(SearchIndexOperator.LessOrEqual, v, number)); queryEngine.AddOperatorHandler("<", (SearchValue v, float number) => PropertyFloatCompare(SearchIndexOperator.Less, v, number)); queryEngine.AddOperatorHandler(">", (SearchValue v, float number) => PropertyFloatCompare(SearchIndexOperator.Greater, v, number)); queryEngine.AddOperatorHandler(">=", (SearchValue v, float number) => PropertyFloatCompare(SearchIndexOperator.GreaterOrEqual, v, number)); queryEngine.AddOperatorHandler(":", (Vector4 v, Vector4 v4, StringComparison sc) => PropertyVector4Compare(SearchIndexOperator.Contains, v, v4)); queryEngine.AddOperatorHandler("=", (Vector4 v, Vector4 v4) => PropertyVector4Compare(SearchIndexOperator.Equal, v, v4)); queryEngine.AddOperatorHandler("!=", (Vector4 v, Vector4 v4) => PropertyVector4Compare(SearchIndexOperator.NotEqual, v, v4)); queryEngine.AddOperatorHandler("<=", (Vector4 v, Vector4 v4) => PropertyVector4Compare(SearchIndexOperator.LessOrEqual, v, v4)); queryEngine.AddOperatorHandler("<", (Vector4 v, Vector4 v4) => PropertyVector4Compare(SearchIndexOperator.Less, v, v4)); queryEngine.AddOperatorHandler(">", (Vector4 v, Vector4 v4) => PropertyVector4Compare(SearchIndexOperator.Greater, v, v4)); queryEngine.AddOperatorHandler(">=", (Vector4 v, Vector4 v4) => PropertyVector4Compare(SearchIndexOperator.GreaterOrEqual, v, v4)); queryEngine.AddOperatorHandler(":", (SearchValue v, Vector4 v4, StringComparison sc) => PropertyVector4Compare(SearchIndexOperator.Contains, v, v4)); queryEngine.AddOperatorHandler("=", (SearchValue v, Vector4 v4) => PropertyVector4Compare(SearchIndexOperator.Equal, v, v4)); queryEngine.AddOperatorHandler("!=", (SearchValue v, Vector4 v4) => PropertyVector4Compare(SearchIndexOperator.NotEqual, v, v4)); queryEngine.AddOperatorHandler("<=", (SearchValue v, Vector4 v4) => PropertyVector4Compare(SearchIndexOperator.LessOrEqual, v, v4)); queryEngine.AddOperatorHandler("<", (SearchValue v, Vector4 v4) => PropertyVector4Compare(SearchIndexOperator.Less, v, v4)); queryEngine.AddOperatorHandler(">", (SearchValue v, Vector4 v4) => PropertyVector4Compare(SearchIndexOperator.Greater, v, v4)); queryEngine.AddOperatorHandler(">=", (SearchValue v, Vector4 v4) => PropertyVector4Compare(SearchIndexOperator.GreaterOrEqual, v, v4)); queryEngine.AddOperatorHandler("=", (SearchValue v, bool b) => PropertyBoolCompare(v, b, (f, r) => f == r)); queryEngine.AddOperatorHandler(":", (SearchValue v, bool b) => PropertyBoolCompare(v, b, (f, r) => f == r)); queryEngine.AddOperatorHandler("!=", (SearchValue v, bool b) => PropertyBoolCompare(v, b, (f, r) => f != r)); queryEngine.AddOperatorHandler(":", (SearchValue v, string s, StringComparison sc) => PropertyStringCompare(v, s, (f, r) => StringContains(f, r, sc))); queryEngine.AddOperatorHandler("=", (SearchValue v, string s, StringComparison sc) => PropertyStringCompare(v, s, (f, r) => string.Equals(f, r, sc))); queryEngine.AddOperatorHandler("!=", (SearchValue v, string s, StringComparison sc) => PropertyStringCompare(v, s, (f, r) => !string.Equals(f, r, sc))); queryEngine.AddOperatorHandler("<=", (SearchValue v, string s, StringComparison sc) => PropertyStringCompare(v, s, (f, r) => string.Compare(f, r, sc) <= 0)); queryEngine.AddOperatorHandler("<", (SearchValue v, string s, StringComparison sc) => PropertyStringCompare(v, s, (f, r) => string.Compare(f, r, sc) < 0)); queryEngine.AddOperatorHandler(">", (SearchValue v, string s, StringComparison sc) => PropertyStringCompare(v, s, (f, r) => string.Compare(f, r, sc) > 0)); queryEngine.AddOperatorHandler(">=", (SearchValue v, string s, StringComparison sc) => PropertyStringCompare(v, s, (f, r) => string.Compare(f, r, sc) >= 0)); queryEngine.AddOperatorHandler(":", (SearchValue v, SearchColor c) => PropertyColorCompare(v, c, (f, r) => f == r)); queryEngine.AddOperatorHandler("=", (SearchValue v, SearchColor c) => PropertyColorCompare(v, c, (f, r) => f == r)); queryEngine.AddOperatorHandler("!=", (SearchValue v, SearchColor c) => PropertyColorCompare(v, c, (f, r) => f != r)); queryEngine.AddOperatorHandler("<=", (SearchValue v, SearchColor c) => PropertyColorCompare(v, c, (f, r) => f <= r)); queryEngine.AddOperatorHandler("<", (SearchValue v, SearchColor c) => PropertyColorCompare(v, c, (f, r) => f < r)); queryEngine.AddOperatorHandler(">", (SearchValue v, SearchColor c) => PropertyColorCompare(v, c, (f, r) => f > r)); queryEngine.AddOperatorHandler(">=", (SearchValue v, SearchColor c) => PropertyColorCompare(v, c, (f, r) => f >= r)); queryEngine.AddTypeParser(arg => { if (Utils.TryParseRange(arg, out var range)) return new ParseResult<PropertyRange>(true, range); return ParseResult<PropertyRange>.none; }); queryEngine.AddTypeParser(s => { if (!s.StartsWith("#")) return new ParseResult<SearchColor?>(false, null); if (ColorUtility.TryParseHtmlString(s, out var color)) return new ParseResult<SearchColor?>(true, new SearchColor(color)); return new ParseResult<SearchColor?>(false, null); }); queryEngine.AddTypeParser(s => { if (!Utils.TryParseVectorValue(s, out var vec, out _)) return new ParseResult<Vector4>(false, default); return new ParseResult<Vector4>(true, vec); }); } private static bool StringContains(string ev, string fv, StringComparison sc) { if (ev == null || fv == null) return false; return ev.IndexOf(fv, sc) != -1; } private static bool PropertyVector4Compare(in SearchIndexOperator op, in SearchValue v, in Vector4 v4) { if (v.type != ValueType.Vector3 && v.type != ValueType.Vector2 && v.type != ValueType.Vector4) return false; return PropertyVector4Compare(op, v.v4, v4); } private static bool PropertyVector4Compare(in SearchIndexOperator op, in Vector4 v, in Vector4 v4) { bool hx = !float.IsNaN(v4.x), hy = !float.IsNaN(v4.y), hz = !float.IsNaN(v4.z), hw = !float.IsNaN(v4.w); return (hx == false || Utils.NumberCompare(op, v.x, v4.x)) && (hy == false || Utils.NumberCompare(op, v.y, v4.y)) && (hz == false || Utils.NumberCompare(op, v.z, v4.z)) && (hw == false || Utils.NumberCompare(op, v.w, v4.w)); } private static bool PropertyRangeCompare(in SearchIndexOperator op, in SearchValue v, in PropertyRange range) { if (v.type != ValueType.Number) return false; switch(op) { case SearchIndexOperator.Equal: return range.Contains(v.floatNumber); case SearchIndexOperator.Contains: return range.Contains(v.floatNumber); case SearchIndexOperator.NotEqual: return !range.Contains(v.floatNumber); case SearchIndexOperator.Greater: return v.floatNumber > range.max; case SearchIndexOperator.GreaterOrEqual: return v.floatNumber >= range.max; case SearchIndexOperator.Less: return v.floatNumber < range.min; case SearchIndexOperator.LessOrEqual: return v.floatNumber <= range.min; } return false; } private static bool PropertyFloatCompare(in SearchIndexOperator op, in SearchValue v, float value) { if (v.type == ValueType.Enum) return Utils.NumberCompare(op, v.floatNumber, value); if (v.type != ValueType.Number) return false; return Utils.NumberCompare(op, v.floatNumber, value); } private static bool PropertyBoolCompare(in SearchValue v, bool b, Func<bool, bool, bool> comparer) { if (v.type != ValueType.Bool) return false; return comparer(v.floatNumber == 1d, b); } private static bool PropertyStringCompare(in SearchValue v, string s, Func<string, string, bool> comparer) { if (v.type == ValueType.Enum) return comparer(v.text, s); if (v.type == ValueType.Object) { if (string.Equals(s, "none", StringComparison.Ordinal) && string.Equals(v.text, string.Empty, StringComparison.Ordinal)) return comparer(s, "none"); if (string.IsNullOrEmpty(v.text)) return false; // Test with the value as is. if (comparer(v.text, s)) return true; // Could be an asset path, try to resolve it. if (!v.text.StartsWith("/") && AssetDatabase.AssetPathExists(v.text)) { var obj = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(v.text); // Compare with the name of the asset. return obj != null && comparer(obj.name, s); } // Might be a global object id, try to resolve it. // Note: do this last, as it is slow. if (v.text.StartsWith("GlobalObjectId", StringComparison.Ordinal) && GlobalObjectId.TryParse(v.text, out var goid)) { var obj = GlobalObjectId.GlobalObjectIdentifierToObjectSlow(goid); if (obj == null) return false; // Compare name of the object. if (comparer(obj.name, s)) return true; if (obj is Component c) { var tp = SearchUtils.GetTransformPath(c.gameObject.transform); return comparer(tp, s); } var assetPath = AssetDatabase.GetAssetPath(obj); if (!string.IsNullOrEmpty(assetPath) && Utils.IsBuiltInResource(assetPath)) return comparer(assetPath, s); if (obj is GameObject go) { var tp = SearchUtils.GetTransformPath(go.transform); return comparer(tp, s); } } } if (v.type == ValueType.Bool) { if (v.boolean && string.Equals(s, "on", StringComparison.OrdinalIgnoreCase)) return true; if (!v.boolean && string.Equals(s, "off", StringComparison.OrdinalIgnoreCase)) return true; } else if (v.type != ValueType.Text || string.IsNullOrEmpty(v.text)) return false; return comparer(v.text, s); } private static bool PropertyColorCompare(in SearchValue v, SearchColor value, Func<SearchColor, SearchColor, bool> comparer) { if (v.type != ValueType.Color) return false; return comparer(v.color, value); } [PropertyDatabaseSerializer(typeof(SearchValue))] internal static PropertyDatabaseRecordValue SearchValueSerializer(PropertyDatabaseSerializationArgs args) { // TODO: Figure out why vectors use strings instead of saving the data directly in the record value int stringSymbol; var gop = (SearchValue)args.value; switch (gop.type) { case ValueType.Nil: return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.GameObjectProperty, (byte)gop.type); case ValueType.Bool: case ValueType.Number: return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.GameObjectProperty, (byte)gop.type, BitConverter.SingleToInt32Bits(gop.floatNumber)); case ValueType.Text: stringSymbol = args.stringTableView.ToSymbol(gop.text); return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.GameObjectProperty, (byte)gop.type, (int)stringSymbol); case ValueType.Color: return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.GameObjectProperty, (byte)gop.type, (byte)gop.color.r, (byte)gop.color.g, (byte)gop.color.b, (byte)gop.color.a); case ValueType.Vector2: stringSymbol = args.stringTableView.ToSymbol(Utils.ToString(gop.v4, 2)); return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.GameObjectProperty, (byte)gop.type, (int)stringSymbol); case ValueType.Vector3: stringSymbol = args.stringTableView.ToSymbol(Utils.ToString(gop.v4, 3)); return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.GameObjectProperty, (byte)gop.type, (int)stringSymbol); case ValueType.Vector4: stringSymbol = args.stringTableView.ToSymbol(Utils.ToString(gop.v4, 4)); return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.GameObjectProperty, (byte)gop.type, (int)stringSymbol); case ValueType.Object: stringSymbol = args.stringTableView.ToSymbol(gop.text ?? string.Empty); return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.GameObjectProperty, (byte)gop.type, (int)stringSymbol); case ValueType.Enum: stringSymbol = args.stringTableView.ToSymbol(gop.text); return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.GameObjectProperty, (byte)gop.type, (int)stringSymbol, (int)gop.floatNumber); } return PropertyDatabaseRecordValue.invalid; } [PropertyDatabaseDeserializer(PropertyDatabaseType.GameObjectProperty)] internal static object SearchValueDeserializer(PropertyDatabaseDeserializationArgs args) { var gopType = (ValueType)args.value[0]; switch (gopType) { case ValueType.Nil: return new SearchValue(); case ValueType.Bool: return new SearchValue(BitConverter.Int32BitsToSingle(args.value.int32_1) == 1d); case ValueType.Number: return new SearchValue(BitConverter.Int32BitsToSingle(args.value.int32_1)); case ValueType.Text: var symbol = args.value.int32_1; var str = args.stringTableView.GetString(symbol); return new SearchValue(str); case ValueType.Color: return new SearchValue(new SearchColor(args.value[1], args.value[2], args.value[3], args.value[4])); case ValueType.Vector2: case ValueType.Vector3: case ValueType.Vector4: symbol = args.value.int32_1; str = args.stringTableView.GetString(symbol); if (Utils.TryParseVectorValue(str, out var v4, out int dim)) return new SearchValue(v4, dim); break; case ValueType.Object: symbol = args.value.int32_1; str = args.stringTableView.GetString(symbol); return new SearchValue((UnityEngine.Object)null, str); case ValueType.Enum: symbol = args.value.int32_1; str = args.stringTableView.GetString(symbol); return new SearchValue(args.value.int32_2, str); } throw new Exception("Failed to deserialize game object property"); } } class SearchItemQueryEngine : QueryEngine<SearchItem> { static Regex PropertyFilterRx = new Regex(@"[\@\$]([#\w\d\.\[\]]+)"); SearchExpressionContext m_Context; public SearchItemQueryEngine() { Setup(); } public IEnumerable<SearchItem> Where(SearchExpressionContext context, IEnumerable<SearchItem> dataSet, string queryStr) { m_Context = context; var query = ParseQuery(queryStr, true); if (query.errors.Count != 0) { var errorStr = string.Join("\n", query.errors.Select(err => $"Invalid where query expression at {err.index}: {err.reason}")); context.ThrowError(errorStr); } foreach (var item in dataSet) { if (item != null) { if (query.Test(item)) yield return item; } else yield return null; } m_Context = default; } public IEnumerable<SearchItem> WhereMainThread(SearchExpressionContext context, IEnumerable<SearchItem> dataSet, string queryStr) { m_Context = context; var query = ParseQuery(queryStr, true); if (query.errors.Count != 0) { var errorStr = string.Join("\n", query.errors.Select(err => $"Invalid where query expression at {err.index}: {err.reason}")); context.ThrowError(errorStr); } var results = TaskEvaluatorManager.EvaluateMainThread(dataSet, item => { if (query.Test(item)) return item; return null; }, 25); m_Context = default; return results; } private void Setup() { AddFilter(PropertyFilterRx, GetValue); AddFilter("p", GetValue, s => s, StringComparison.OrdinalIgnoreCase); SearchValue.SetupEngine(this); SetSearchDataCallback(GetSearchableData, StringComparison.OrdinalIgnoreCase); } IEnumerable<string> GetSearchableData(SearchItem item) { yield return item.value.ToString(); yield return item.id; if (item.label != null) yield return item.label; } SearchValue GetValue(SearchItem item, string selector) { var v = SelectorManager.SelectValue(item, m_Context.search, selector); return new SearchValue(v); } } }
UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/SearchItemQueryEngine.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/SearchItemQueryEngine.cs", "repo_id": "UnityCsReference", "token_count": 16538 }
455
// Unity 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.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using UnityEngine; namespace UnityEditor.Search { readonly struct SearchSessionContext { public readonly SearchContext searchContext; public readonly StackTrace stackTrace; public readonly Hash128 guid; public SearchSessionContext(SearchContext context, StackTrace stackTrace, Hash128 guid) { this.searchContext = context; this.stackTrace = stackTrace; this.guid = guid; } public SearchSessionContext(SearchContext context, StackTrace stackTrace) : this(context, stackTrace, Hash128.Compute(Guid.NewGuid().ToByteArray())) {} public SearchSessionContext(SearchContext context, Hash128 guid) : this(context, new StackTrace(2, true), guid) {} public SearchSessionContext(SearchContext context) : this(context, new StackTrace(2, true), Hash128.Compute(Guid.NewGuid().ToByteArray())) {} } class BaseAsyncIEnumerableHandler<T> { protected SearchEnumerator<T> m_ItemsEnumerator = new SearchEnumerator<T>(); protected const long k_MaxTimePerUpdate = 10; // milliseconds protected long maxFetchTimePerUpdate { get; set; } = k_MaxTimePerUpdate; public BaseAsyncIEnumerableHandler() { } public BaseAsyncIEnumerableHandler(object itemEnumerator) { Reset(itemEnumerator); } public virtual void OnUpdate() { var newItems = new List<T>(); Update(newItems); } public virtual void Update(List<T> newItems) { var atEnd = !FetchSome(newItems, maxFetchTimePerUpdate); if (newItems.Count > 0) SendItems(newItems); if (atEnd) { Stop(); } } public virtual void SendItems(IEnumerable<T> items) {} internal virtual void Start() {} public virtual void Stop() { Utils.tick -= OnUpdate; lock (this) m_ItemsEnumerator.Dispose(); } public virtual void Reset(object itemEnumerator, long maxFetchTimePerUpdate = k_MaxTimePerUpdate) { // Remove and add the event handler in case it was already removed. Stop(); this.maxFetchTimePerUpdate = maxFetchTimePerUpdate; if (itemEnumerator != null) { lock (this) m_ItemsEnumerator = new SearchEnumerator<T>(itemEnumerator); Utils.tick += OnUpdate; } } /// <summary> /// Request to fetch new async search results. /// </summary> /// <param name="items">The list of items to append new results to.</param> /// <param name="quantity">The maximum amount of items to be added to @items</param> /// <param name="doNotCountNull">Ignore all yield return null results.</param> /// <returns>Returns true if there is still some results to fetch later or false if we've fetched everything remaining.</returns> public bool FetchSome(List<T> items, int quantity, bool doNotCountNull) { if (m_ItemsEnumerator.Count == 0) return false; var atEnd = false; for (var i = 0; i < quantity && !atEnd; ++i) { atEnd = !m_ItemsEnumerator.NextItem(out var item); if (item == null) { if (doNotCountNull) --i; continue; } items.Add(item); } return !atEnd; } /// <summary> /// Request to fetch new async search results. /// </summary> /// <param name="items">The list of items to append new results to.</param> /// <param name="quantity">The maximum amount of items to add to @items</param> /// <param name="doNotCountNull">Ignore all yield return null results.</param> /// <param name="maxFetchTimeMs">The amount of time allowed to yield new results.</param> /// <returns>Returns true if there is still some results to fetch later or false if we've fetched everything remaining.</returns> public bool FetchSome(List<T> items, int quantity, bool doNotCountNull, long maxFetchTimeMs) { if (m_ItemsEnumerator.Count == 0) return false; var atEnd = false; var timeToFetch = Stopwatch.StartNew(); for (var i = 0; i < quantity && !atEnd && timeToFetch.ElapsedMilliseconds < maxFetchTimeMs; ++i) { atEnd = !m_ItemsEnumerator.NextItem(out var item); if (item == null) { if (doNotCountNull) --i; continue; } items.Add(item); } return !atEnd; } /// <summary> /// Request to fetch new async search results. /// </summary> /// <param name="items">The list of items to append new results to.</param> /// <param name="maxFetchTimeMs">The amount of time allowed to yield new results.</param> /// <returns>Returns true if there is still some results to fetch later or false if we've fetched everything remaining.</returns> public bool FetchSome(List<T> items, long maxFetchTimeMs) { if (m_ItemsEnumerator.Count == 0) return false; var atEnd = false; var timeToFetch = Stopwatch.StartNew(); while (!atEnd && timeToFetch.ElapsedMilliseconds < maxFetchTimeMs) { atEnd = !m_ItemsEnumerator.NextItem(out var item); if (!atEnd && item != null) items.Add(item); } return !atEnd; } } /// <summary> /// An async search session tracks all incoming items found by a search provider that weren't returned right away after the search was initiated. /// </summary> class SearchSession : BaseAsyncIEnumerableHandler<SearchItem> { /// <summary> /// This event is used to receive any async search result. /// </summary> public event Action<SearchContext, IEnumerable<SearchItem>> asyncItemReceived; /// <summary> /// This event is used to know when a search has started to fetch new search items. /// </summary> public event Action<SearchContext> sessionStarted; /// <summary> /// This event is used to know when a search has finished fetching items. /// </summary> public event Action<SearchContext> sessionEnded; private SearchSessionContext m_Context; private SearchProvider m_Provider; private Stopwatch m_SessionTimer = new Stopwatch(); private const long k_DefaultSessionTimeOut = 10000; private long m_SessionTimeOut = k_DefaultSessionTimeOut; /// <summary> /// Checks if this async search session is active. /// </summary> public bool searchInProgress { get; set; } = false; public SearchSession(SearchSessionContext context, SearchProvider provider) { m_Context = context; m_Provider = provider; } /// <summary> /// Resolved a batch of items asynchronously. /// </summary> /// <param name="items"></param> public override void SendItems(IEnumerable<SearchItem> items) { asyncItemReceived?.Invoke(m_Context.searchContext, items); } /// <summary> /// Hard reset an async search session. /// </summary> /// <param name="itemEnumerator">The enumerator that will yield new search results. This object can be an IEnumerator or IEnumerable</param> /// <param name="maxFetchTimePerProviderMs">The amount of time allowed to yield new results.</param> /// <remarks>Normally async search sessions are re-used per search provider.</remarks> public void Reset(SearchSessionContext context, object itemEnumerator, long maxFetchTimePerProviderMs = k_MaxTimePerUpdate, long sessionTimeOutMs = k_DefaultSessionTimeOut) { // Remove and add the event handler in case it was already removed. Stop(); searchInProgress = true; m_Context = context; maxFetchTimePerUpdate = maxFetchTimePerProviderMs; m_SessionTimeOut = sessionTimeOutMs; m_SessionTimer.Reset(); if (itemEnumerator != null) { lock (this) m_ItemsEnumerator = new SearchEnumerator<SearchItem>(itemEnumerator); Utils.tick += OnUpdate; } } internal override void Start() { sessionStarted?.Invoke(m_Context.searchContext); m_SessionTimer.Start(); base.Start(); } /// <summary> /// Stop the async search session and discard any new search results. /// </summary> public override void Stop() { if (searchInProgress) sessionEnded?.Invoke(m_Context.searchContext); searchInProgress = false; m_SessionTimer.Stop(); base.Stop(); } public override void Update(List<SearchItem> newItems) { base.Update(newItems); if (!searchInProgress) return; if (newItems.Count > 0) { m_SessionTimer.Restart(); } if (m_SessionTimer.ElapsedMilliseconds > m_SessionTimeOut) { // Do this before stopping to get target IEnumerator var timeOutError = BuildSessionContextTimeOutError(); Stop(); if (m_Context.searchContext.searchView != null) { m_Context.searchContext.AddSearchQueryError(new SearchQueryError(0, m_Context.searchContext.searchText.Length, timeOutError, m_Context.searchContext, m_Provider, false)); } else { UnityEngine.Debug.LogFormat(LogType.Error, LogOption.NoStacktrace, null, timeOutError); } } } private string BuildSessionContextTimeOutError() { var sb = new StringBuilder(); if (string.IsNullOrEmpty(m_Context.searchContext.searchText)) sb.AppendLine($"Search session timeout for provider \"{m_Provider.id}\"."); else sb.AppendLine($"Search session timeout for provider \"{m_Provider.id}\" and query \"{m_Context.searchContext.searchText}\"."); sb.AppendLine("Source:"); for (var i = 0; i < m_Context.stackTrace.FrameCount; ++i) sb.AppendLine($"\t{m_Context.stackTrace.GetFrame(i)}"); if (m_ItemsEnumerator.enumeratorStack.Count > 0) { sb.AppendLine("Target:"); foreach (var enumerator in m_ItemsEnumerator.enumeratorStack) { var enumeratorType = enumerator.GetType(); sb.AppendLine($"\t{enumeratorType}"); } } return sb.ToString(); } } /// <summary> /// A MultiProviderAsyncSearchSession holds all the providers' async search sessions. /// </summary> class MultiProviderAsyncSearchSession { private System.Threading.CancellationTokenSource m_CancelSource; private ConcurrentDictionary<string, SearchSession> m_SearchSessions = new ConcurrentDictionary<string, SearchSession>(); /// <summary> /// This event is used to receive any async search result. /// </summary> public event Action<SearchContext, IEnumerable<SearchItem>> asyncItemReceived; /// <summary> /// This event is triggered when a session has started to fetch search items. /// </summary> public event Action<SearchContext> sessionStarted; /// <summary> /// This event is triggered when a session has finished to fetch all search items. /// </summary> public event Action<SearchContext> sessionEnded; /// <summary> /// Checks if any of the providers' async search are active. /// </summary> public bool searchInProgress => m_SearchSessions.Any(session => session.Value.searchInProgress); internal System.Threading.CancellationToken cancelToken => m_CancelSource?.Token ?? default(System.Threading.CancellationToken); internal SearchSessionContext currentSessionContext { get; private set; } /// <summary> /// Returns the specified provider's async search session. /// </summary> /// <param name="provider"></param> /// <returns>The provider's async search session.</returns> public SearchSession GetProviderSession(SearchProvider provider) { if (!m_SearchSessions.TryGetValue(provider.id, out var session)) { session = new SearchSession(currentSessionContext, provider); if (m_SearchSessions.TryAdd(provider.id, session)) { session.sessionStarted += OnProviderAsyncSessionStarted; session.sessionEnded += OnProviderAsyncSessionEnded; session.asyncItemReceived += OnProviderAsyncItemReceived; } else throw new Exception($"Failed to add session for {provider.id}"); } return session; } private void OnProviderAsyncSessionStarted(SearchContext context) { sessionStarted?.Invoke(context); } private void OnProviderAsyncSessionEnded(SearchContext context) { sessionEnded?.Invoke(context); } private void OnProviderAsyncItemReceived(SearchContext context, IEnumerable<SearchItem> items) { asyncItemReceived?.Invoke(context, items); } public void StartSessions(SearchContext context, Hash128 sessionGuid) { if (m_CancelSource != null) { m_CancelSource.Dispose(); m_CancelSource = null; } m_CancelSource = new System.Threading.CancellationTokenSource(); currentSessionContext = new SearchSessionContext(context, sessionGuid); } /// <summary> /// Stops all active async search sessions held by this MultiProviderAsyncSearchSession. /// </summary> public void StopAllAsyncSearchSessions() { m_CancelSource?.Cancel(); foreach (var searchSession in m_SearchSessions) { searchSession.Value.Stop(); } } /// <summary> /// Clears all async search sessions held by this MultiProviderAsyncSearchSession. /// </summary> public void Clear() { m_CancelSource?.Dispose(); m_CancelSource = null; foreach (var searchSession in m_SearchSessions) { searchSession.Value.asyncItemReceived -= OnProviderAsyncItemReceived; searchSession.Value.sessionStarted -= OnProviderAsyncSessionStarted; searchSession.Value.sessionEnded -= OnProviderAsyncSessionEnded; } m_SearchSessions.Clear(); asyncItemReceived = null; } public void Tick() { foreach (var searchSession in m_SearchSessions) searchSession.Value.OnUpdate(); } } }
UnityCsReference/Modules/QuickSearch/Editor/SearchSession.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/SearchSession.cs", "repo_id": "UnityCsReference", "token_count": 7216 }
456
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.IO; using UnityEngine; namespace UnityEditor.Search { [Flags] enum AssetModification { Updated = 1, Removed = 1 << 1, Moved = 1 << 2 } struct Transaction { public long timestamp; public Hash128 guid; public int state; public static int size { get { unsafe { return sizeof(long) + sizeof(Hash128) + sizeof(int); } } } public Transaction(string guid, int state) : this(guid, state, DateTime.UtcNow.ToBinary()) { } public Transaction(string guid, int state, long timestamp) : this(Hash128.Parse(guid), state, timestamp) { } public Transaction(string guid, AssetModification state) : this(guid, (int)state) { } public Transaction(string guid, AssetModification state, long timestamp) : this(guid, (int)state, timestamp) { } public Transaction(Hash128 guid, int state, long timestamp) { this.timestamp = timestamp; this.guid = guid; this.state = state; } public override string ToString() { return $"[{DateTime.FromBinary(timestamp).ToUniversalTime():u}] ({state}) {guid}"; } public AssetModification GetState() { return (AssetModification)state; } public void ToBinary(BinaryWriter bw) { bw.Write(timestamp); bw.Write(guid.u64_0); bw.Write(guid.u64_1); bw.Write(state); } public static Transaction FromBinary(BinaryReader br) { var timestamp = br.ReadInt64(); var u640 = br.ReadUInt64(); var u641 = br.ReadUInt64(); var state = br.ReadInt32(); return new Transaction(new Hash128(u640, u641), state, timestamp); } } }
UnityCsReference/Modules/QuickSearch/Editor/Transactions/Transaction.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/Transactions/Transaction.cs", "repo_id": "UnityCsReference", "token_count": 1107 }
457
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine.UIElements; namespace UnityEditor.Search { class RenamableLabel : VisualElement { /// <summary> /// USS class name of elements of this type. /// </summary> public static readonly string ussClassName = "search-renamable-label"; public static readonly string labelClassName = ussClassName.WithUssElement("label"); Label m_Label; TextField m_TextField; public string text { get => m_Label.text; set => m_Label.text = value; } public event Action<string> renameFinished; public RenamableLabel() : this(string.Empty) { } public RenamableLabel(string text) { AddToClassList(ussClassName); m_Label = new Label(text); m_Label.AddToClassList(labelClassName); Add(m_Label); } public void StartRename() { SetElementDisplay(m_Label, false); m_TextField = CreateNewTextField(); m_TextField.SetValueWithoutNotify(m_Label.text); m_TextField.RegisterValueChangedCallback(HandleTextFieldValueChanged); m_TextField.RegisterCallback<BlurEvent>(HandleBlurEvent); Add(m_TextField); m_TextField.Focus(); m_TextField.SelectAll(); } public void StopRename() { m_TextField.UnregisterValueChangedCallback(HandleTextFieldValueChanged); m_TextField.UnregisterCallback<BlurEvent>(HandleBlurEvent); Remove(m_TextField); SetElementDisplay(m_Label, true); } void HandleBlurEvent(BlurEvent evt) { AcceptRename(m_TextField.text); } void HandleTextFieldValueChanged(ChangeEvent<string> evt) { AcceptRename(evt.newValue); } void AcceptRename(string newName) { text = Utils.Simplify(newName); StopRename(); SendRenameFinishedEvent(); } void SendRenameFinishedEvent() { renameFinished?.Invoke(text); } static void SetElementDisplay(VisualElement element, bool value) { if (element == null) return; element.style.display = value ? DisplayStyle.Flex : DisplayStyle.None; element.style.visibility = value ? Visibility.Visible : Visibility.Hidden; } static TextField CreateNewTextField() { var textField = new TextField { multiline = false, isDelayed = true }; return textField; } } }
UnityCsReference/Modules/QuickSearch/Editor/UITK/RenamableLabel.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/UITK/RenamableLabel.cs", "repo_id": "UnityCsReference", "token_count": 1364 }
458
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.UIElements; using UnityEngine.UIElements.Internal; namespace UnityEditor.Search { class SearchTableView : SearchBaseCollectionView<MultiColumnListView>, ITableView { public static readonly string ussClassName = "search-table-view"; public static readonly string resultsListClassName = ussClassName.WithUssElement("results-list"); public static readonly string addColumnButtonClassName = ussClassName.WithUssElement("add-column-button"); public static readonly string resetColumnsButtonClassName = ussClassName.WithUssElement("reset-columns-button"); public static readonly string addMoreColumnsTooltip = L10n.Tr("Add column..."); public static readonly string resetSearchColumnsTooltip = L10n.Tr("Reset search result columns."); private Action m_DeferredSortColumnOff; public SearchTable tableConfig { get => viewState.tableConfig; private set { viewState.tableConfig = value; Refresh(RefreshFlags.DisplayModeChanged); } } bool ITableView.readOnly => false; public override bool showNoResultMessage => m_ViewModel.displayMode != DisplayMode.Table; Columns viewColumns => m_ListView.columns; public SearchTableView(ISearchView viewModel) : base("SearchTableView", viewModel, ussClassName) { m_ListView = new MultiColumnListView(BuildColumns(tableConfig)) { fixedItemHeight = 22f, showAlternatingRowBackgrounds = AlternatingRowBackground.All, selectionType = m_ViewModel.multiselect ? SelectionType.Multiple : SelectionType.Single, itemsSource = (IList)m_ViewModel.results, sortingMode = ColumnSortingMode.Custom }; m_ListView.AddToClassList(resultsListClassName); Add(m_ListView); if (tableConfig == null) SetupColumns(); SetupColumnSorting(); } protected override void OnAttachToPanel(AttachToPanelEvent evt) { base.OnAttachToPanel(evt); m_ListView.columnSortingChanged += OnSortColumn; m_ListView.columns.columnReordered += OnColumnReordered; var header = this.Q<MultiColumnCollectionHeader>(); header.contextMenuPopulateEvent += OnSearchColumnContextualMenu; On(SearchEvent.SearchContextChanged, OnContextChanged); On(SearchEvent.RequestResultViewButtons, OnAddResultViewButtons); } protected override void OnDetachFromPanel(DetachFromPanelEvent evt) { Off(SearchEvent.SearchContextChanged, OnContextChanged); Off(SearchEvent.RequestResultViewButtons, OnAddResultViewButtons); var header = this.Q<MultiColumnCollectionHeader>(); header.contextMenuPopulateEvent -= OnSearchColumnContextualMenu; m_ListView.columnSortingChanged -= OnSortColumn; m_ListView.columns.columnReordered -= OnColumnReordered; base.OnDetachFromPanel(evt); } private bool IsTableViewRow(VisualElement ve) { return ve.ClassListContains("unity-multi-column-view__row-container"); } protected override void OnPointerDown(PointerDownEvent evt) { if (evt.clickCount != 1 && evt.button != 0) return; if (evt.target is not VisualElement ve) return; if (!IsTableViewRow(ve) && ve.GetFirstAncestorWhere((ve) => { return IsTableViewRow(ve); }) == null) m_ListView.ClearSelection(); } protected override void OnGroupChanged(string prevGroupId, string newGroupId) { OnSortColumn(); base.OnGroupChanged(prevGroupId, newGroupId); } public IEnumerable<SearchItem> GetElements() { return m_ViewModel.results ?? Enumerable.Empty<SearchItem>(); } float ITableView.GetRowHeight() => m_ListView.fixedItemHeight; IEnumerable<SearchItem> ITableView.GetRows() => m_ViewModel.results; SearchTable ITableView.GetSearchTable() => tableConfig; void ITableView.SetSelection(IEnumerable<SearchItem> items) => m_ViewModel.SetSelection(items.Select(e => m_ViewModel.results.IndexOf(e)).Where(i => i != -1).ToArray()); void ITableView.OnItemExecuted(SearchItem item) => m_ViewModel.ExecuteSelection(); void ITableView.SetDirty() => Refresh(); int ITableView.GetColumnIndex(string name) => GetColumnIndex(name); bool ITableView.OpenContextualMenu(Event evt, SearchItem item) { var selection = m_ViewModel.selection; if (selection.Count <= 0 && item == null) return false; var contextRect = new Rect(evt.mousePosition, new Vector2(1, 1)); m_ViewModel.ShowItemContextualMenu(item, contextRect); return true; } SearchColumn ITableView.FindColumnBySelector(string selector) { var columnIndex = GetColumnIndex(selector); if (columnIndex == -1) return null; return tableConfig.columns[columnIndex]; } IEnumerable<object> ITableView.GetValues(int columnIdx) { if (m_ViewModel?.state?.tableConfig?.columns == null) yield break; var column = tableConfig.columns[columnIdx]; foreach (var ltd in m_ViewModel.results) yield return column.ResolveValue(ltd, context); } void ITableView.UpdateColumnSettings(int columnIndex, IMGUI.Controls.MultiColumnHeaderState.Column columnSettings) => throw new NotSupportedException("Search table view IMGUI is not supported anymore"); bool ITableView.AddColumnHeaderContextMenuItems(GenericMenu menu) => throw new NotSupportedException("Search table view IMGUI is not supported anymore"); void ITableView.AddColumnHeaderContextMenuItems(GenericMenu menu, SearchColumn sourceColumn) => throw new NotSupportedException("Search table view IMGUI is not supported anymore"); public override void Refresh(RefreshFlags flags) { if (flags.HasAny(RefreshFlags.ItemsChanged | RefreshFlags.GroupChanged | RefreshFlags.QueryCompleted)) { Refresh(); } else if (flags.HasAny(RefreshFlags.DisplayModeChanged)) { if (m_ListView != null) BuildColumns(viewColumns, tableConfig, clear: true); ExportTableConfig(); } } protected override float GetItemHeight() => m_ListView.fixedItemHeight; private void SetupColumnSorting() { bool applySorting = false; foreach (var tc in m_ListView.columns) { if (tc is not SearchTableViewColumn stvc) continue; if (stvc.searchColumn.options.HasAny(SearchColumnFlags.Sorted)) { applySorting = true; var sortedBy = SortDirection.Ascending; if (stvc.searchColumn.options.HasAny(SearchColumnFlags.SortedDescending)) sortedBy = SortDirection.Descending; m_ListView.sortColumnDescriptions.Add(new SortColumnDescription(tc.index, sortedBy)); } } if (applySorting) OnSortColumn(); } private void OnSortColumn() { m_DeferredSortColumnOff?.Invoke(); m_DeferredSortColumnOff = Utils.CallDelayed(SortColumns); } private void SortColumns() { var sorter = new SearchTableViewColumnSorter(); foreach (var c in tableConfig.columns) c.options &= ~SearchColumnFlags.Sorted; foreach (var sortC in m_ListView.sortedColumns) { var sc = ((SearchTableViewColumn)sortC.column).searchColumn; sc.options |= SearchColumnFlags.Sorted; if (sortC.direction == SortDirection.Ascending) sc.options &= ~SearchColumnFlags.SortedDescending; else sc.options |= SearchColumnFlags.SortedDescending; sorter.Add(sc, sortC.direction); } m_ViewModel.results.SortBy(sorter); Refresh(); } private void OnAddResultViewButtons(ISearchEvent evt) { var container = evt.GetArgument<VisualElement>(0); var addColumnButton = new Button { tooltip = addMoreColumnsTooltip }; addColumnButton.RegisterCallback<ClickEvent>(OnAddColumn); addColumnButton.AddToClassList(SearchGroupBar.groupBarButtonClassName); addColumnButton.AddToClassList(addColumnButtonClassName); container.Add(addColumnButton); var resetColumnsButton = new Button(ResetColumnLayout) { tooltip = resetSearchColumnsTooltip }; resetColumnsButton.AddToClassList(SearchGroupBar.groupBarButtonClassName); resetColumnsButton.AddToClassList(resetColumnsButtonClassName); container.Add(resetColumnsButton); } private void OnColumnReordered(Column arg1, int arg2, int arg3) { SwapColumns(arg2, arg3); } private void OnContextChanged(ISearchEvent evt) { if (evt.sourceViewState != m_ViewModel.state) return; m_ListView.itemsSource = (IList)m_ViewModel.results; if (tableConfig == null) SetupColumns(); else BuildColumns(viewColumns, tableConfig, clear: true); } private void OnSearchColumnContextualMenu(ContextualMenuPopulateEvent evt, Column columnUnderMouse) { evt.menu.ClearItems(); var visibleColumnCount = m_ListView.columns.visibleList.Count(); if (viewColumns.Count > 1) { for (int i = 0; i < viewColumns.Count; ++i) { var column = viewColumns[i]; var menuContent = "Show Columns/" + GetDisplayLabel(column); if (visibleColumnCount == 1 && column.visible) evt.menu.AppendAction(menuContent, (a) => { }, DropdownMenuAction.Status.Disabled); else evt.menu.AppendAction(menuContent, (a) => { ToggleColumnVisibility(column); }, column.visible ? DropdownMenuAction.Status.Checked : DropdownMenuAction.Status.Normal); } } if (columnUnderMouse is SearchTableViewColumn pc) AddColumnHeaderContextMenuItems(evt.menu, pc.searchColumn); var mp = evt.mousePosition; var activeColumnIndex = columnUnderMouse != null ? FindColumnIndex(columnUnderMouse) : -1; evt.menu.AppendSeparator(); evt.menu.AppendAction(EditorGUIUtility.TrTextContent("Add Column...").text, (a) => AddColumn(mp, activeColumnIndex)); if (columnUnderMouse != null) { var colName = (columnUnderMouse as SearchTableViewColumn)?.title ?? columnUnderMouse.title; evt.menu.AppendAction(EditorGUIUtility.TrTextContent($"Edit {colName}...").text, (a) => EditColumn(activeColumnIndex)); evt.menu.AppendAction(EditorGUIUtility.TrTextContent($"Remove {colName}").text, (a) => RemoveColumn(activeColumnIndex)); } evt.menu.AppendSeparator(); evt.menu.AppendAction(EditorGUIUtility.TrTextContent("Reset Columns").text, (a) => ResetColumnLayout()); } private static string GetDisplayLabel(Column col) { if (!string.IsNullOrEmpty(col.title)) return col.title; if (!string.IsNullOrEmpty(col.name)) return col.name; if (col.icon.texture != null && !string.IsNullOrEmpty(col.icon.texture.name)) return col.icon.texture.name; return "Unnamed"; } private void ToggleColumnVisibility(Column column) { column.visible = !column.visible; SearchAnalytics.SendEvent(null, SearchAnalytics.GenericEventType.QuickSearchTableToggleColumnVisibility); } private void EditColumn(int columnIndex) { if (TryGetViewModelColumn(tableConfig.columns[columnIndex], out var viewColumn)) ColumnEditor.ShowWindow(viewColumn, (_column) => UpdateColumnSettings(columnIndex, _column)); } private bool TryGetViewModelColumn(in SearchColumn sc, out SearchTableViewColumn viewColumn) { foreach (var c in viewColumns) { if (c is not SearchTableViewColumn stvc) continue; if (stvc.searchColumn == sc) { viewColumn = stvc; return true; } } viewColumn = null; return false; } internal void ResetColumnLayout() { tableConfig = LoadDefaultTableConfig(reset: true); SearchAnalytics.SendEvent(null, SearchAnalytics.GenericEventType.QuickSearchTableReset, context.searchQuery); } private void OnAddColumn(ClickEvent evt) { var searchColumns = SearchColumn.Enumerate(context, GetElements()); var windowMousePosition = Utils.Unclip(new Rect(evt.position, Vector2.zero)).position; SearchUtils.ShowColumnSelector(AddColumns, searchColumns, windowMousePosition, -1); } void ExportTableConfig(string id = null) { if (viewState.tableConfig == null) return; SessionState.SetString(GetDefaultGroupId(id), viewState.tableConfig.Export()); } private SearchTable LoadDefaultTableConfig(bool reset, string id = null, SearchTable defaultConfig = null) { if (!reset) { var sessionSearchTableData = SessionState.GetString(GetDefaultGroupId(id), null); if (!string.IsNullOrEmpty(sessionSearchTableData)) return SearchTable.Import(sessionSearchTableData); } if (m_ViewModel != null) { var providers = m_ViewModel.context.GetProviders(); var provider = providers.Count == 1 ? providers.FirstOrDefault() : SearchService.GetProvider(m_ViewModel.currentGroup); if (provider?.tableConfig != null) return provider.tableConfig(context); } return defaultConfig ?? SearchTable.CreateDefault(); } private string GetDefaultGroupId(string id = null) { var key = "CurrentSearchTableConfig_V2"; if (id == null) { var providers = m_ViewModel.context.GetProviders(); if (providers.Count == 1) key += "_" + providers[0].id; else if (!string.IsNullOrEmpty(m_ViewModel.currentGroup)) key += "_" + m_ViewModel.currentGroup; } else if (!string.IsNullOrEmpty(id)) key += "_" + id; return key; } public void AddColumns(IEnumerable<SearchColumn> newColumns, int insertColumnAt) { if (tableConfig == null) return; var uniqueColumns = newColumns.Where(newColumn => tableConfig.columns.All(c => c.selector != newColumn.selector)).ToList(); if (uniqueColumns.Count == 0) return; var searchColumns = new List<SearchColumn>(tableConfig.columns); if (insertColumnAt == -1) insertColumnAt = searchColumns.Count; var columnCountBefore = searchColumns.Count; searchColumns.InsertRange(insertColumnAt, uniqueColumns); var columnAdded = searchColumns.Count - columnCountBefore; if (columnAdded > 0) { var firstColumn = uniqueColumns.First(); var e = SearchAnalytics.GenericEvent.Create(null, SearchAnalytics.GenericEventType.QuickSearchTableAddColumn, firstColumn.name); e.intPayload1 = columnAdded; e.message = firstColumn.provider; e.description = firstColumn.selector; SearchAnalytics.SendEvent(e); for (int ca = 0; ca < columnAdded; ++ca) { var newViewColumn = new SearchTableViewColumn(searchColumns[insertColumnAt + ca], m_ViewModel, this); viewColumns.Insert(insertColumnAt + ca, newViewColumn); } tableConfig.columns = searchColumns.ToArray(); ExportTableConfig(); Refresh(); } } private Columns BuildColumns(SearchTable tableConfig) { var columns = new Columns(); if (tableConfig == null) return columns; foreach (var sc in tableConfig.columns) columns.Add(new SearchTableViewColumn(sc, m_ViewModel, this)); return columns; } private void BuildColumns(Columns columns, SearchTable tableConfig, bool clear = false) { if (clear) columns.Clear(); foreach (var sc in tableConfig.columns) { if (!clear && columns.Any(x => string.Equals(x.name, sc.path, StringComparison.Ordinal))) continue; // FIXME: Each call to Add here does a Rebuild of the table view columns.Add(new SearchTableViewColumn(sc, m_ViewModel, this)); } } public void AddColumn(Vector2 mousePosition, int activeColumnIndex) { var columns = SearchColumn.Enumerate(context, GetElements()); SearchUtils.ShowColumnSelector(AddColumns, columns, mousePosition, activeColumnIndex); } public void SetupColumns(IEnumerable<SearchItem> elements = null) { SetupColumns(elements ?? m_ViewModel.results, SearchColumnFlags.Default); } public void SetupColumns(IEnumerable<SearchItem> items, SearchColumnFlags options) { var currentTableConfig = tableConfig; if (currentTableConfig == null) currentTableConfig = LoadDefaultTableConfig(reset: false); var fields = new HashSet<SearchField>(); foreach (var e in items ?? GetElements()) fields.UnionWith(e.GetFields().Where(f => f.value != null)); if (fields.Count > 0) currentTableConfig.columns = fields.Select(f => ItemSelectors.CreateColumn(f.label, f.name, options: options)).ToArray(); tableConfig = currentTableConfig; } internal void SetupColumns(IList<SearchField> fields) { var searchColumns = new List<SearchColumn>(tableConfig.columns.Where(c => { var fp = fields.IndexOf(new SearchField(c.selector)); if (fp != -1) { if (!string.IsNullOrEmpty(fields[fp].alias)) c.content.text = fields[fp].alias; else if (fields[fp].value is string alias && !string.IsNullOrEmpty(alias)) c.content.text = alias; fields.RemoveAt(fp); return true; } return (c.options & SearchColumnFlags.Volatile) == 0; })); foreach (var f in fields) { var c = ItemSelectors.CreateColumn(f.label, f.name); string alias = null; if (!string.IsNullOrEmpty(f.alias)) alias = f.alias; else if (f.value is string a && !string.IsNullOrEmpty(a)) alias = a; c.content.text = alias ?? c.content.text; c.options |= SearchColumnFlags.Volatile; searchColumns.Add(c); } if (searchColumns.Count > 0) { tableConfig.columns = searchColumns.ToArray(); BuildColumns(viewColumns, tableConfig, clear: true); ExportTableConfig(); } } public void RemoveColumn(int removeColumnAt) { if (tableConfig == null || removeColumnAt == -1) return; var columnToRemove = tableConfig.columns[removeColumnAt]; if (TryGetViewModelColumn(columnToRemove, out var viewColumn) && viewColumns.Remove(viewColumn)) { var columns = new List<SearchColumn>(tableConfig.columns); columns.RemoveAt(removeColumnAt); tableConfig.columns = columns.ToArray(); ExportTableConfig(); Refresh(); SearchAnalytics.SendEvent(null, SearchAnalytics.GenericEventType.QuickSearchTableRemoveColumn, columnToRemove.name, columnToRemove.provider, columnToRemove.selector); } } public void SwapColumns(int columnIndex, int swappedColumnIndex) { if (tableConfig == null || swappedColumnIndex == -1) return; var temp = tableConfig.columns[columnIndex]; tableConfig.columns[columnIndex] = tableConfig.columns[swappedColumnIndex]; tableConfig.columns[swappedColumnIndex] = temp; Refresh(); } private void UpdateColumnSettings(int columnIndex, Column columnSettings) { if (tableConfig == null || columnIndex >= tableConfig.columns.Length) return; var searchColumn = tableConfig.columns[columnIndex]; searchColumn.width = columnSettings.width.value; searchColumn.content = new GUIContent(columnSettings.title, columnSettings.icon.texture); if (columnSettings.sortable) searchColumn.options |= SearchColumnFlags.CanSort; else searchColumn.options &= ~SearchColumnFlags.CanSort; if (columnSettings.optional) searchColumn.options |= SearchColumnFlags.CanHide; else searchColumn.options &= ~SearchColumnFlags.CanHide; // Hack trigger rebinding columnSettings.optional = !columnSettings.optional; columnSettings.optional = !columnSettings.optional; SearchAnalytics.SendEvent(null, SearchAnalytics.GenericEventType.QuickSearchTableEditColumn, searchColumn.name, searchColumn.provider, searchColumn.selector); SearchColumnSettings.Save(searchColumn); Refresh(); } public IEnumerable<SearchColumn> GetColumns() { if (tableConfig == null || tableConfig.columns == null) return Enumerable.Empty<SearchColumn>(); return tableConfig.columns; } private void AddColumnHeaderContextMenuItems(DropdownMenu menu, SearchColumn sourceColumn) { menu.AppendAction("Column Format/Default", (a) => { sourceColumn.SetProvider(null); Refresh(); }, string.IsNullOrEmpty(sourceColumn.provider) ? DropdownMenuAction.Status.Checked : DropdownMenuAction.Status.Normal); foreach (var scp in SearchColumnProvider.providers) { var provider = scp.provider; var selected = string.Equals(sourceColumn.provider, provider, StringComparison.Ordinal); var menuContent = new GUIContent("Column Format/" + ObjectNames.NicifyVariableName(provider)); menu.AppendAction(menuContent.text, (a) => { sourceColumn.SetProvider(provider); Refresh(); }, selected ? DropdownMenuAction.Status.Checked : DropdownMenuAction.Status.Normal); } } private int GetColumnIndex(in string name) { if (tableConfig.columns == null || tableConfig.columns.Length == 0) return -1; // Search by selector name first for (int i = 0; i < tableConfig.columns.Length; ++i) { if (string.Equals(tableConfig.columns[i].selector, name, StringComparison.Ordinal)) return i; } // Continue with column name if nothing was found. for (int i = 0; i < tableConfig.columns.Length; ++i) { if (string.Equals(tableConfig.columns[i].name, name, StringComparison.OrdinalIgnoreCase)) return i; } return -1; } public int FindColumnIndex(in Column viewColumn) { if (tableConfig.columns == null || tableConfig.columns.Length == 0) return -1; if (viewColumn is not SearchTableViewColumn stvc) return -1; for (int i = 0; i < tableConfig.columns.Length; ++i) { if (stvc.searchColumn == tableConfig.columns[i]) return i; } return -1; } } }
UnityCsReference/Modules/QuickSearch/Editor/UITK/SearchTableView.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/UITK/SearchTableView.cs", "repo_id": "UnityCsReference", "token_count": 11924 }
459
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Linq; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Reflection; using System.Globalization; using System.Text.RegularExpressions; using UnityEngine; using UnityEditorInternal; using UnityEngine.UIElements; using UnityEditor.Connect; using UnityEditor.StyleSheets; [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("com.unity.quicksearch.tests")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Unity.Environment.Core.Editor")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Unity.ProceduralGraph.Editor")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Unity.Rendering.Hybrid")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Unity.VisualEffectGraph.Editor")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Unity.Localization.Editor")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Unity.Hierarchy.Tests")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Unity.Hierarchy.Editor.Tests")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Unity.Entities.Editor.Tests")] namespace UnityEditor.Search { static class EventModifiersExtensions { public static bool HasAny(this EventModifiers flags, EventModifiers f) => (flags & f) != 0; public static bool HasAll(this EventModifiers flags, EventModifiers all) => (flags & all) == all; } /// <summary> /// This utility class mainly contains proxy to internal API that are shared between the version in trunk and the package version. /// </summary> static class Utils { const int k_MaxRegexTimeout = 25; internal static readonly bool isDeveloperBuild = false; internal static bool runningTests { get; set; } internal static bool fakeWorkerProcess { get; set; } private static readonly Regex s_RangeRx = new Regex(@"(-?[\d\.]+)\.\.(-?[\d\.]+)"); struct RootDescriptor { public RootDescriptor(string root) { this.root = root; absPath = CleanPath(new FileInfo(root).FullName); } public string root; public string absPath; public override string ToString() { return $"{root} -> {absPath}"; } } static RootDescriptor[] s_RootDescriptors; static RootDescriptor[] rootDescriptors { get { return s_RootDescriptors ?? (s_RootDescriptors = GetAssetRootFolders().Select(root => new RootDescriptor(root)).OrderByDescending(desc => desc.absPath.Length).ToArray()); } } private static UnityEngine.Object[] s_LastDraggedObjects; public static GUIStyle objectFieldButton { get { return EditorStyles.objectFieldButton; } } static Utils() { isDeveloperBuild = Unsupported.IsSourceBuild(); } internal static void OpenInBrowser(string baseUrl, List<Tuple<string, string>> query = null) { var url = baseUrl; if (query != null) { url += "?"; for (var i = 0; i < query.Count; ++i) { var item = query[i]; url += item.Item1 + "=" + item.Item2; if (i < query.Count - 1) { url += "&"; } } } var uri = new Uri(url); Process.Start(uri.AbsoluteUri); } internal static SettingsProvider[] FetchSettingsProviders() { return SettingsService.FetchSettingsProviders(); } internal static string GetNameFromPath(string path) { var lastSep = path.LastIndexOf('/'); if (lastSep == -1) return path; return path.Substring(lastSep + 1); } internal static Hash128 GetSourceAssetFileHash(string guid) { return AssetDatabase.GetSourceAssetFileHash(guid); } public static Texture2D GetAssetThumbnailFromPath(SearchContext ctx, string path) { var thumbnail = GetAssetPreviewFromGUID(ctx, AssetDatabase.AssetPathToGUID(path)); if (thumbnail) return thumbnail; thumbnail = AssetDatabase.GetCachedIcon(path) as Texture2D; return thumbnail ?? InternalEditorUtility.FindIconForFile(path); } private static Texture2D GetAssetPreviewFromGUID(SearchContext ctx, string guid) { return AssetPreview.GetAssetPreviewFromGUID(guid, GetClientId(ctx)); } public static Texture2D GetAssetPreviewFromPath(SearchContext ctx, string path, FetchPreviewOptions previewOptions) { return GetAssetPreviewFromPath(ctx, path, new Vector2(128, 128), previewOptions); } public static Texture2D GetAssetPreviewFromPath(SearchContext ctx, string path, Vector2 previewSize, FetchPreviewOptions previewOptions) { var assetType = AssetDatabase.GetMainAssetTypeAtPath(path); if (assetType == typeof(SceneAsset)) return AssetDatabase.GetCachedIcon(path) as Texture2D; if (previewOptions.HasAny(FetchPreviewOptions.Normal)) { if (assetType == typeof(AudioClip)) return GetAssetThumbnailFromPath(ctx, path); try { var fi = new FileInfo(path); if (!fi.Exists) return null; if (fi.Length > 16 * 1024 * 1024) return GetAssetThumbnailFromPath(ctx, path); } catch { return null; } } if (!typeof(Texture).IsAssignableFrom(assetType)) { var tex = AssetDatabase.LoadAssetAtPath<Texture2D>(path); if (tex) return tex; } var obj = AssetDatabase.LoadMainAssetAtPath(path); if (obj == null) return null; if (previewOptions.HasAny(FetchPreviewOptions.Large)) { var tex = AssetPreviewUpdater.CreatePreview(obj, null, path, (int)previewSize.x, (int)previewSize.y); if (tex) return tex; } return GetAssetPreview(ctx, obj, previewOptions) ?? AssetDatabase.GetCachedIcon(path) as Texture2D; } internal static bool HasInvalidComponent(UnityEngine.Object obj) { return PrefabUtility.HasInvalidComponent(obj); } public static int GetMainAssetInstanceID(string assetPath) { return AssetDatabase.GetMainAssetInstanceID(assetPath); } internal static GUIContent GUIContentTemp(string text, string tooltip) { return GUIContent.Temp(text, tooltip); } internal static GUIContent GUIContentTemp(string text, Texture image) { return GUIContent.Temp(text, image); } internal static GUIContent GUIContentTemp(string text) { return GUIContent.Temp(text); } internal static Texture2D GetAssetPreview(SearchContext ctx, UnityEngine.Object obj, FetchPreviewOptions previewOptions) { var preview = AssetPreview.GetAssetPreview(obj.GetInstanceID(), GetClientId(ctx)); if (preview == null || previewOptions.HasAny(FetchPreviewOptions.Large)) { var largePreview = AssetPreview.GetMiniThumbnail(obj); if (preview == null || (largePreview != null && largePreview.width > preview.width)) preview = largePreview; } return preview; } internal static bool IsEditorValid(Editor e) { return e && e.serializedObject != null && e.serializedObject.isValid; } internal static int Wrap(int index, int n) { return ((index % n) + n) % n; } internal static void SetCurrentViewWidth(float width) { EditorGUIUtility.currentViewWidth = width; } internal static void SelectObject(UnityEngine.Object obj, bool ping = false) { if (!obj) return; Selection.activeObject = obj; if (ping) { EditorApplication.delayCall += () => { EditorWindow.FocusWindowIfItsOpen(GetProjectBrowserWindowType()); EditorApplication.delayCall += () => EditorGUIUtility.PingObject(obj); }; } } internal static UnityEngine.Object SelectAssetFromPath(string path, bool ping = false) { var asset = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(path); SelectObject(asset, ping); return asset; } internal static void SetTextEditorHasFocus(TextEditor editor, bool hasFocus) { editor.m_HasFocus = hasFocus; } public static void FrameAssetFromPath(string path) { var asset = SelectAssetFromPath(path); if (asset != null) { EditorApplication.delayCall += () => { EditorWindow.FocusWindowIfItsOpen(GetProjectBrowserWindowType()); EditorApplication.delayCall += () => EditorGUIUtility.PingObject(asset); }; } else { EditorUtility.RevealInFinder(path); } } internal static IEnumerable<Type> GetLoadableTypes(this Assembly assembly) { try { return assembly.GetTypes(); } catch (ReflectionTypeLoadException e) { return e.Types.Where(t => t != null); } } internal static void GetMenuItemDefaultShortcuts(List<string> outItemNames, List<string> outItemDefaultShortcuts) { Menu.GetMenuItemDefaultShortcuts(outItemNames, outItemDefaultShortcuts); } static string PrintTabs(int level) { var tabs = string.Empty; for (int i = 0; i < level; ++i) tabs += "\t"; return tabs; } static void Append(System.Text.StringBuilder sb, string name, object v, int level, HashSet<object> _seen) { try { var vt = v?.GetType(); if (v == null) sb.AppendLine($"{PrintTabs(level)}{name}: nil"); else if (v is UnityEngine.Object ueo) sb.AppendLine($"{PrintTabs(level)}{name}: ({ueo.GetInstanceID()}) {ueo.name} [{ueo.GetType()}]"); else if (v is string s) sb.AppendLine($"{PrintTabs(level)}{name}: {s}"); else if (vt.IsPrimitive) sb.AppendLine($"{PrintTabs(level)}{name}: {v}"); else if (v is Enum @enum) sb.AppendLine($"{PrintTabs(level)}{name}: {@enum}"); else if (v is Delegate d) sb.AppendLine($"{PrintTabs(level)}{name}: {d.Method.DeclaringType.Name}.{d.Method.Name}"); else if (v is System.Collections.ICollection coll) { sb.AppendLine($"{PrintTabs(level)}{name} ({coll.Count}):"); int i = 0; foreach (var e in coll) Append(sb, $"[{i++}] {e?.GetType()}", e, level + 2, _seen); } else if (vt.FullName.StartsWith("System.", StringComparison.Ordinal)) sb.AppendLine($"{PrintTabs(level)}{name}: {v}"); else sb.AppendLine(PrintObject(name, v, level + 1, _seen)); } catch (Exception ex) { sb.AppendLine($"{PrintTabs(level)}{name}: <{ex.Message}>"); } } static bool PrintField(FieldInfo fi) { if (!fi.DeclaringType.IsSerializable) return false; return fi.GetCustomAttribute<NonSerializedAttribute>() == null; } public static string PrintObject(string label, object obj, int level = 1, HashSet<object> seen = null) { seen = seen ?? new HashSet<object>(); if (!seen.Contains(obj)) { seen.Add(obj); var t = obj.GetType(); var bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; var sb = new System.Text.StringBuilder(); foreach (var item in t.GetFields(bindingAttr).Where(p => PrintField(p))) Append(sb, item.Name, item.GetValue(obj), level, seen); var result = sb.ToString().Trim(' ', '\r', '\n'); if (result.Length > 0) result = "\r\n" + result; return $"{PrintTabs(level - 1)}{label} [{obj?.GetHashCode() ?? -1:X}]: {result}"; } return $"{PrintTabs(level - 1)}{label}: [{obj?.GetHashCode() ?? -1:X}]"; } internal static string FormatProviderList(IEnumerable<SearchProvider> providers, bool fullTimingInfo = false, bool showFetchTime = true) { return string.Join(fullTimingInfo ? "\r\n" : ", ", providers.Select(p => { var fetchTime = p.fetchTime; if (fullTimingInfo) return $"{p.name} ({fetchTime:0.#} ms, Enable: {p.enableTime:0.#} ms, Init: {p.loadTime:0.#} ms)"; var avgTimeLabel = String.Empty; if (showFetchTime && fetchTime > 9.99) avgTimeLabel = $" ({fetchTime:#} ms)"; return $"<b>{p.name}</b>{avgTimeLabel}"; })); } public static string FormatBytes(long byteCount) { string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; if (byteCount == 0) return "0" + suf[0]; long bytes = Math.Abs(byteCount); int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024))); double num = Math.Round(bytes / Math.Pow(1024, place), 1); return $"{Math.Sign(byteCount) * num} {suf[place]}"; } internal static string ToGuid(string assetPath) { string metaFile = $"{assetPath}.meta"; if (!File.Exists(metaFile)) return null; string line; using (var file = new StreamReader(metaFile)) { while ((line = file.ReadLine()) != null) { if (!line.StartsWith("guid:", StringComparison.Ordinal)) continue; return line.Substring(6); } } return null; } internal static Rect GetEditorMainWindowPos() { var windows = Resources.FindObjectsOfTypeAll<ContainerWindow>(); foreach (var win in windows) { if (win.showMode == ShowMode.MainWindow) return win.position; } return new Rect(0, 0, 800, 600); } internal static Rect GetCenteredWindowPosition(Rect parentWindowPosition, Vector2 size) { var pos = new Rect { x = 0, y = 0, width = Mathf.Min(size.x, parentWindowPosition.width * 0.90f), height = Mathf.Min(size.y, parentWindowPosition.height * 0.90f) }; var w = (parentWindowPosition.width - pos.width) * 0.5f; var h = (parentWindowPosition.height - pos.height) * 0.5f; pos.x = parentWindowPosition.x + w; pos.y = parentWindowPosition.y + h; return pos; } internal static Type GetProjectBrowserWindowType() { return typeof(ProjectBrowser); } public static Rect GetMainWindowCenteredPosition(Vector2 size) { var mainWindowRect = GetEditorMainWindowPos(); return GetCenteredWindowPosition(mainWindowRect, size); } internal static void ShowDropDown(this EditorWindow window, Vector2 size) { window.maxSize = window.minSize = size; window.position = GetMainWindowCenteredPosition(size); window.ShowPopup(); var parentView = window.m_Parent; parentView.AddToAuxWindowList(); parentView.window.m_DontSaveToLayout = true; } internal static string JsonSerialize(object obj) { return Json.Serialize(obj); } internal static object JsonDeserialize(string json) { return Json.Deserialize(json); } internal static string GetNextWord(string src, ref int index) { // Skip potential white space BEFORE the actual word we are extracting for (; index < src.Length; ++index) { if (!char.IsWhiteSpace(src[index])) { break; } } var startIndex = index; for (; index < src.Length; ++index) { if (char.IsWhiteSpace(src[index])) { break; } } return src.Substring(startIndex, index - startIndex); } internal static int LevenshteinDistance<T>(IEnumerable<T> lhs, IEnumerable<T> rhs) where T : System.IEquatable<T> { if (lhs == null) throw new System.ArgumentNullException("lhs"); if (rhs == null) throw new System.ArgumentNullException("rhs"); IList<T> first = lhs as IList<T> ?? new List<T>(lhs); IList<T> second = rhs as IList<T> ?? new List<T>(rhs); int n = first.Count, m = second.Count; if (n == 0) return m; if (m == 0) return n; int curRow = 0, nextRow = 1; int[][] rows = { new int[m + 1], new int[m + 1] }; for (int j = 0; j <= m; ++j) rows[curRow][j] = j; for (int i = 1; i <= n; ++i) { rows[nextRow][0] = i; for (int j = 1; j <= m; ++j) { int dist1 = rows[curRow][j] + 1; int dist2 = rows[nextRow][j - 1] + 1; int dist3 = rows[curRow][j - 1] + (first[i - 1].Equals(second[j - 1]) ? 0 : 1); rows[nextRow][j] = System.Math.Min(dist1, System.Math.Min(dist2, dist3)); } if (curRow == 0) { curRow = 1; nextRow = 0; } else { curRow = 0; nextRow = 1; } } return rows[curRow][m]; } internal static int LevenshteinDistance(string lhs, string rhs, bool caseSensitive = true) { if (!caseSensitive) { lhs = lhs.ToLower(); rhs = rhs.ToLower(); } char[] first = lhs.ToCharArray(); char[] second = rhs.ToCharArray(); return LevenshteinDistance(first, second); } internal static Texture2D GetThumbnailForGameObject(GameObject go) { var thumbnail = PrefabUtility.GetIconForGameObject(go); if (thumbnail) return thumbnail; return EditorGUIUtility.ObjectContent(go, go.GetType()).image as Texture2D; } internal static Texture2D FindTextureForType(Type type) { if (type == null) return null; return EditorGUIUtility.FindTexture(type); } internal static Texture2D GetIconForObject(UnityEngine.Object obj) { return EditorGUIUtility.GetIconForObject(obj); } public static void PingAsset(string assetPath) { EditorGUIUtility.PingObject(AssetDatabase.GetMainAssetInstanceID(assetPath)); } internal static T ConvertValue<T>(string value) { var type = typeof(T); var converter = TypeDescriptor.GetConverter(type); if (converter.IsValid(value)) { // ReSharper disable once AssignNullToNotNullAttribute return (T)converter.ConvertFromString(null, CultureInfo.InvariantCulture, value); } return (T)Activator.CreateInstance(type); } internal static bool TryConvertValue<T>(string value, out T convertedValue) { var type = typeof(T); var converter = TypeDescriptor.GetConverter(type); try { // ReSharper disable once AssignNullToNotNullAttribute convertedValue = (T)converter.ConvertFromString(null, CultureInfo.InvariantCulture, value); return true; } catch { convertedValue = default; return false; } } public static void StartDrag(UnityEngine.Object[] objects, string label = null) { s_LastDraggedObjects = objects; if (s_LastDraggedObjects == null) return; DragAndDrop.PrepareStartDrag(); DragAndDrop.objectReferences = s_LastDraggedObjects; DragAndDrop.StartDrag(label); } public static void StartDrag(UnityEngine.Object[] objects, string[] paths, string label = null) { s_LastDraggedObjects = objects; if (paths == null || paths.Length == 0) return; DragAndDrop.PrepareStartDrag(); DragAndDrop.objectReferences = s_LastDraggedObjects; DragAndDrop.paths = paths; DragAndDrop.StartDrag(label); } internal static Type GetTypeFromName(string typeName) { return TypeCache.GetTypesDerivedFrom<UnityEngine.Object>().FirstOrDefault(t => string.Equals(t.Name, typeName, StringComparison.Ordinal)) ?? typeof(UnityEngine.Object); } internal static string StripHTML(string input) { return Regex.Replace(input, "<.*?>", String.Empty); } internal static UnityEngine.Object ToObject(SearchItem item, Type filterType) { if (item == null || item.provider == null) return null; return item.provider.toObject?.Invoke(item, filterType); } internal static bool IsFocusedWindowTypeName(string focusWindowName) { return EditorWindow.focusedWindow != null && EditorWindow.focusedWindow.GetType().ToString().EndsWith("." + focusWindowName); } internal static string CleanString(string s) { var sb = s.ToCharArray(); for (int c = 0; c < s.Length; ++c) { var ch = s[c]; if (ch == '_' || ch == '.' || ch == '-' || ch == '/') sb[c] = ' '; } return new string(sb).ToLowerInvariant(); } internal static string CleanPath(string path) { return path.Replace("\\", "/"); } internal static bool IsPathUnderProject(string path) { if (!Path.IsPathRooted(path)) { path = new FileInfo(path).FullName; } path = CleanPath(path); return rootDescriptors.Any(desc => path.StartsWith(desc.absPath)); } internal static string GetPathUnderProject(string path) { path = CleanPath(path); if (!Path.IsPathRooted(path)) { return path; } foreach (var desc in rootDescriptors) { if (path.StartsWith(desc.absPath)) { var relativePath = path.Substring(desc.absPath.Length); return desc.root + relativePath; } } return path; } private static int GetClientId(SearchContext ctx) { return ctx != null && ctx.searchView != null ? ctx.searchView.GetViewId() : 0; } internal static Texture2D GetSceneObjectPreview(SearchContext ctx, GameObject obj, Vector2 previewSize, FetchPreviewOptions options, Texture2D defaultThumbnail) { var sr = obj.GetComponent<SpriteRenderer>(); if (sr && sr.sprite && sr.sprite.texture) return sr.sprite.texture; if (!options.HasAny(FetchPreviewOptions.Large)) { var preview = AssetPreview.GetAssetPreview(obj.GetInstanceID(), GetClientId(ctx)); if (preview) return preview; if (AssetPreview.IsLoadingAssetPreview(obj.GetInstanceID())) return null; } var assetPath = SearchUtils.GetHierarchyAssetPath(obj, true); if (string.IsNullOrEmpty(assetPath)) return AssetPreview.GetAssetPreview(obj.GetInstanceID(), GetClientId(ctx)) ?? defaultThumbnail; return GetAssetPreviewFromPath(ctx, assetPath, previewSize, options); } internal static bool TryGetNumber(object value, out double number) { if (value == null) { number = double.NaN; return false; } if (value is string s) { if (TryParse(s, out number)) return true; else { number = double.NaN; return false; } } if (value.GetType().IsPrimitive || value is decimal) { number = Convert.ToDouble(value); return true; } return TryParse(Convert.ToString(value), out number); } internal static bool TryGetFloat(object value, out float number) { if (value == null) { number = float.NaN; return false; } if (value is string s) { if (TryParse(s, out number)) return true; else { number = float.NaN; return false; } } if (value.GetType().IsPrimitive || value is decimal) { number = Convert.ToSingle(value); return true; } return TryParse(Convert.ToString(value), out number); } internal const double DOUBLE_EPSILON = 0.0001; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] internal static bool Approximately(double a, double b) { // If a or b is zero, compare that the other is less or equal to epsilon. // If neither a or b are 0, then find an epsilon that is good for // comparing numbers at the maximum magnitude of a and b. // Floating points have about 7 significant digits, so // 1.000001f can be represented while 1.0000001f is rounded to zero, // thus we could use an epsilon of 0.000001f for comparing values close to 1. // We multiply this epsilon by the biggest magnitude of a and b. return Math.Abs(b - a) < Math.Max(0.000001 * Math.Max(Math.Abs(a), Math.Abs(b)), double.Epsilon * 8); } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] internal static bool NumberCompare(SearchIndexOperator op, double d1, double d2) { switch (op) { case SearchIndexOperator.Equal: return Approximately(d1, d2); case SearchIndexOperator.Contains: return Approximately(d1, d2); case SearchIndexOperator.NotEqual: return !Approximately(d1, d2); case SearchIndexOperator.Greater: return d1 > d2; case SearchIndexOperator.GreaterOrEqual: return d1 > d2 || Approximately(d1, d2); case SearchIndexOperator.Less: return d1 < d2; case SearchIndexOperator.LessOrEqual: return d1 < d2 || Approximately(d1, d2); } return false; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] internal static bool NumberCompare(SearchIndexOperator op, float d1, float d2) { switch (op) { case SearchIndexOperator.Equal: return Mathf.Approximately(d1, d2); case SearchIndexOperator.Contains: return Mathf.Approximately(d1, d2); case SearchIndexOperator.NotEqual: return !Mathf.Approximately(d1, d2); case SearchIndexOperator.Greater: return d1 > d2; case SearchIndexOperator.GreaterOrEqual: return d1 > d2 || Mathf.Approximately(d1, d2); case SearchIndexOperator.Less: return d1 < d2; case SearchIndexOperator.LessOrEqual: return d1 < d2 || Mathf.Approximately(d1, d2); } return false; } internal static bool IsRunningTests() { return runningTests; } internal static bool IsFakeWorkerProcess() { return fakeWorkerProcess; } internal static bool IsMainProcess() { if (AssetDatabaseAPI.IsAssetImportWorkerProcess()) return false; if (EditorUtility.isInSafeMode) return false; if (MPE.ProcessService.level != MPE.ProcessLevel.Main) return false; if (IsRunningTests()) { return !IsFakeWorkerProcess(); } return true; } internal static event EditorApplication.CallbackFunction tick { add { EditorApplication.tick -= value; EditorApplication.tick += value; } remove { EditorApplication.tick -= value; } } public static Action CallAnimated(EditorApplication.CallbackFunction callback, double seconds = 0.05d) { return CallDelayed(callback, seconds); } public static Action CallDelayed(EditorApplication.CallbackFunction callback, double seconds = 0) { return EditorApplication.CallDelayed(callback, seconds); } internal static void SetFirstInspectedEditor(Editor editor) { editor.firstInspectedEditor = true; } public static GUIStyle FromUSS(string name) { return GUIStyleExtensions.FromUSS(GUIStyle.none, name); } public static GUIStyle FromUSS(GUIStyle @base, string name) { return GUIStyleExtensions.FromUSS(@base, name); } internal static bool HasCurrentWindowKeyFocus() { return EditorGUIUtility.HasCurrentWindowKeyFocus(); } internal static void AddStyleSheet(VisualElement rootVisualElement, string ussFileName) { rootVisualElement.AddStyleSheetPath($"StyleSheets/QuickSearch/{ussFileName}"); } internal static InspectorWindowUtils.LayoutGroupChecker LayoutGroupChecker() { return new InspectorWindowUtils.LayoutGroupChecker(); } internal static string GetConnectAccessToken() { return UnityConnect.instance.GetAccessToken(); } internal static string GetPackagesKey() { return UnityConnect.instance.GetConfigurationURL(CloudConfigUrl.CloudPackagesKey); } internal static void OpenPackageManager(string packageName) { PackageManager.UI.PackageManagerWindow.SelectPackageAndPageStatic(packageName, PackageManager.UI.Internal.MyAssetsPage.k_Id); } internal static char FastToLower(char c) { // ASCII non-letter characters and // lower case letters. if (c < 'A' || (c > 'Z' && c <= 'z')) { return c; } if (c >= 'A' && c <= 'Z') { return (char)(c + 32); } return Char.ToLower(c, CultureInfo.InvariantCulture); } internal static string FastToLower(string str) { int length = str.Length; var chars = new char[length]; for (int i = 0; i < length; ++i) { chars[i] = FastToLower(str[i]); } return new string(chars); } public static string FormatCount(ulong count) { if (count < 1000U) return count.ToString(CultureInfo.InvariantCulture.NumberFormat); if (count < 1000000U) return (count / 1000U).ToString(CultureInfo.InvariantCulture.NumberFormat) + "k"; if (count < 1000000000U) return (count / 1000000U).ToString(CultureInfo.InvariantCulture.NumberFormat) + "M"; return (count / 1000000000U).ToString(CultureInfo.InvariantCulture.NumberFormat) + "G"; } internal static bool TryAdd<K, V>(this Dictionary<K, V> dict, K key, V value) { if (!dict.ContainsKey(key)) { dict.Add(key, value); return true; } return false; } internal static string[] GetAssetRootFolders() { return AssetDatabase.GetAssetRootFolders(); } internal static string ToString(in Vector3 v) { return $"({FormatFloatString(v.x)},{FormatFloatString(v.y)},{FormatFloatString(v.z)})"; } internal static string ToString(in Vector4 v, int dim) { switch (dim) { case 2: return $"({FormatFloatString(v.x)},{FormatFloatString(v.y)})"; case 3: return $"({FormatFloatString(v.x)},{FormatFloatString(v.y)},{FormatFloatString(v.z)})"; case 4: return $"({FormatFloatString(v.x)},{FormatFloatString(v.y)},{FormatFloatString(v.z)},{FormatFloatString(v.w)})"; } return null; } internal static string ToString(in Vector2Int v) { return $"({FormatIntString(v.x)},{FormatIntString(v.y)})"; } internal static string ToString(in Vector3Int v) { return $"({FormatIntString(v.x)},{FormatIntString(v.y)},{FormatIntString(v.z)})"; } internal static string ToString(in Rect r) { return $"({FormatFloatString(r.x)},{FormatFloatString(r.y)},{FormatFloatString(r.width)},{FormatFloatString(r.height)})"; } internal static string ToString(in RectInt r) { return $"({FormatIntString(r.x)},{FormatIntString(r.y)},{FormatIntString(r.width)},{FormatIntString(r.height)})"; } internal static string FormatFloatString(in float f) { if (float.IsNaN(f)) return string.Empty; return f.ToString(CultureInfo.InvariantCulture); } internal static string FormatIntString(in int i) { if (int.MaxValue == i) return string.Empty; return i.ToString(); } internal static bool TryParseVectorValue(in object value, out Vector4 vc, out int dim) { dim = 0; vc = new Vector4(float.NaN, float.NaN, float.NaN, float.NaN); if (!(value is string arg)) return false; if (arg.Length < 3 || arg[0] != '(' || arg[arg.Length - 1] != ')' || arg.IndexOf(',') == -1) return false; var ves = arg.Substring(1, arg.Length - 2); var values = ves.Split(','); if (values.Length < 2 || values.Length > 4) return false; dim = values.Length; if (values.Length >= 1 && values[0].Length > 0 && (values[0].Length > 1 || values[0][0] != '-') && TryParse<float>(values[0], out var f)) vc.x = f; if (values.Length >= 2 && values[1].Length > 0 && (values[1].Length > 1 || values[1][0] != '-') && TryParse(values[1], out f)) vc.y = f; if (values.Length >= 3 && values[2].Length > 0 && (values[2].Length > 1 || values[2][0] != '-') && TryParse(values[2], out f)) vc.z = f; if (values.Length >= 4 && values[3].Length > 0 && (values[3].Length > 1 || values[3][0] != '-') && TryParse(values[3], out f)) vc.w = f; return true; } internal static bool TryParseRange(in string arg, out PropertyRange range) { range = default; if (arg.Length < 2 || arg.IndexOf("..") == -1) return false; var rangeMatches = s_RangeRx.Matches(arg); if (rangeMatches.Count != 1 || rangeMatches[0].Groups.Count != 3) return false; var rg = rangeMatches[0].Groups; if (!Utils.TryParse(rg[1].Value, out float min) || !Utils.TryParse(rg[2].Value, out float max)) return false; range = new PropertyRange(min, max); return true; } public static bool TryParse<T>(string expression, out T result, bool supportNamedNumber = true) { expression = expression.Replace(',', '.'); expression = expression.ToLowerInvariant(); return TryParseLowerInvariant(expression.GetStringView(), out result, supportNamedNumber); } public static bool TryParseLowerInvariant<T>(StringView sv, out T result, bool supportNamedNumber = true) { sv = sv.TrimEnd('f'); var expression = sv.ToReadOnlySpan(); bool success = false; result = default; if (typeof(T) == typeof(float)) { if (supportNamedNumber && expression == "pi") { success = true; result = (T)(object)(float)Math.PI; } else { success = float.TryParse(expression, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out var temp); result = (T)(object)temp; } } else if (typeof(T) == typeof(int)) { success = int.TryParse(expression, NumberStyles.Integer, CultureInfo.InvariantCulture.NumberFormat, out var temp); result = (T)(object)temp; } else if (typeof(T) == typeof(uint)) { success = uint.TryParse(expression, NumberStyles.Integer, CultureInfo.InvariantCulture.NumberFormat, out var temp); result = (T)(object)temp; } else if (typeof(T) == typeof(double)) { if (supportNamedNumber && expression == "pi") { success = true; result = (T)(object)Math.PI; } else { success = double.TryParse(expression, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out var temp); result = (T)(object)temp; } } else if (typeof(T) == typeof(long)) { success = long.TryParse(expression, NumberStyles.Integer, CultureInfo.InvariantCulture.NumberFormat, out var temp); result = (T)(object)temp; } else if (typeof(T) == typeof(ulong)) { success = ulong.TryParse(expression, NumberStyles.Integer, CultureInfo.InvariantCulture.NumberFormat, out var temp); result = (T)(object)temp; } return success; } private const string k_RevealInFinderLabel = "Open Containing Folder"; internal static string GetRevealInFinderLabel() { return k_RevealInFinderLabel; } public static string TrimText(string text) { return text.Trim().Replace("\n", " "); } public static string TrimText(string text, int maxLength) { text = TrimText(text); if (text.Length > maxLength) { text = Utils.StripHTML(text); text = text.Substring(0, Math.Min(text.Length, maxLength) - 1) + "\u2026"; } return text; } public static ulong GetHashCode64(this string strText) { if (string.IsNullOrEmpty(strText)) return 0; var s1 = (ulong)strText.Substring(0, strText.Length / 2).GetHashCode(); var s2 = (ulong)strText.Substring(strText.Length / 2).GetHashCode(); return s1 << 32 | s2; } public static string RemoveInvalidCharsFromPath(string path, char repl = '/') { var invalidChars = Path.GetInvalidPathChars(); foreach (var c in invalidChars) path = path.Replace(c, repl); return path; } public static Rect BeginHorizontal(GUIContent content, GUIStyle style, params GUILayoutOption[] options) { return EditorGUILayout.BeginHorizontal(content, style, options); } public static bool IsGUIClipEnabled() { return GUIClip.enabled; } public static Rect Unclip(in Rect r) { return GUIClip.Unclip(r); } public static MonoScript MonoScriptFromScriptedObject(UnityEngine.Object obj) { return MonoScript.FromScriptedObject(obj); } public static bool SerializedPropertyIsScript(SerializedProperty property) { return property.isScript; } public static string SerializedPropertyObjectReferenceStringValue(SerializedProperty property) { return property.objectReferenceStringValue; } public static GUIContent ObjectContent(UnityEngine.Object obj, Type type, int instanceID) { return EditorGUIUtility.ObjectContent(obj, type, instanceID); } public static bool IsCommandDelete(string commandName) { return commandName == EventCommandNames.Delete || commandName == EventCommandNames.SoftDelete; } public static void PopupWindowWithoutFocus(Rect position, PopupWindowContent windowContent) { UnityEditor.PopupWindowWithoutFocus.Show( position, windowContent, new[] { UnityEditor.PopupLocation.Left, UnityEditor.PopupLocation.Below, UnityEditor.PopupLocation.Right }); } public static void OpenPropertyEditor(UnityEngine.Object target) { PropertyEditor.OpenPropertyEditor(target); } public static bool MainActionKeyForControl(Event evt, int id) { return evt.MainActionKeyForControl(id); } public static bool IsNavigationKey(in Event evt) { if (!evt.isKey) return false; switch (evt.keyCode) { case KeyCode.UpArrow: case KeyCode.DownArrow: case KeyCode.LeftArrow: case KeyCode.RightArrow: case KeyCode.Home: case KeyCode.End: case KeyCode.PageUp: case KeyCode.PageDown: return true; } return false; } public static Texture2D LoadIcon(string name) { return EditorGUIUtility.LoadIcon(name); } public static string GetIconSkinAgnosticName(Texture2D icon) { if (icon == null) return null; return GetIconSkinAgnosticName(icon.name); } public static string GetIconSkinAgnosticName(string name) { if (string.IsNullOrEmpty(name)) return name; var oldName = Path.GetFileName(name); var dirName = Path.GetDirectoryName(name); var newName = oldName.StartsWith("d_") ? oldName.Substring(2) : oldName; if (!string.IsNullOrEmpty(dirName)) newName = $"{dirName}/{newName}"; return newName; } public static ulong GetFileIDHint(in UnityEngine.Object obj) { return Unsupported.GetFileIDHint(obj); } public static bool IsEditingTextField() { return GUIUtility.textFieldInput || EditorGUI.IsEditingTextField(); } static readonly Regex trimmer = new Regex(@"(\s\s+)|(\r\n|\r|\n)+"); public static string Simplify(string text) { return trimmer.Replace(text, " ").Replace("\r\n", " ").Replace('\n', ' '); } public static void OpenGraphViewer(in string searchQuery) { } internal static void WriteTextFileToDisk(in string path, in string content) { FileUtil.WriteTextFileToDisk(path, content); } internal static bool ParseRx(string pattern, bool exact, out Regex rx) { try { rx = new Regex(!exact ? pattern : $"^{pattern}$", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(k_MaxRegexTimeout)); } catch (ArgumentException) { rx = null; return false; } return true; } internal static bool ParseGlob(string pattern, bool exact, out Regex rx) { try { pattern = Regex.Escape(RemoveDuplicateAdjacentCharacters(pattern, '*')).Replace(@"\*", ".*").Replace(@"\?", "."); rx = new Regex(!exact ? pattern : $"^{pattern}$", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(k_MaxRegexTimeout)); } catch (ArgumentException) { rx = null; return false; } return true; } static string RemoveDuplicateAdjacentCharacters(string pattern, char c) { for (int i = pattern.Length - 1; i >= 0; --i) { if (pattern[i] != c || i == 0) continue; if (pattern[i - 1] == c) pattern = pattern.Remove(i, 1); } return pattern; } internal static T GetAttribute<T>(this MethodInfo mi) where T : System.Attribute { var attrs = mi.GetCustomAttributes(typeof(T), false); if (attrs == null || attrs.Length == 0) return null; return attrs[0] as T; } internal static T GetAttribute<T>(this Type mi) where T : System.Attribute { var attrs = mi.GetCustomAttributes(typeof(T), false); if (attrs == null || attrs.Length == 0) return null; return attrs[0] as T; } internal static bool TryParseObjectValue(in string value, out UnityEngine.Object objValue) { objValue = null; if (string.IsNullOrEmpty(value)) { return false; } if (string.Equals("none", value, StringComparison.OrdinalIgnoreCase)) return true; if (value.StartsWith("GlobalObjectId", StringComparison.Ordinal) && GlobalObjectId.TryParse(value, out var gid)) { objValue = GlobalObjectId.GlobalObjectIdentifierToObjectSlow(gid); return objValue != null; } // ADB prints a warning if the path starts with / if (!value.StartsWith("/") && AssetDatabase.AssetPathExists(value)) { var guid = AssetDatabase.AssetPathToGUID(value); if (!string.IsNullOrEmpty(guid)) { objValue = AssetDatabase.LoadMainAssetAtPath(value); return true; } } // Try to get the corresponding gameObject from the scene. var go = GameObject.Find(value); if (go) { objValue = go; return true; } return false; } internal static bool IsBuiltInResource(UnityEngine.Object obj) { var resPath = AssetDatabase.GetAssetPath(obj); return IsBuiltInResource(resPath); } internal static bool IsBuiltInResource(in string resPath) { return string.Equals(resPath, "Library/unity editor resources", StringComparison.OrdinalIgnoreCase) || string.Equals(resPath, "resources/unity_builtin_extra", StringComparison.OrdinalIgnoreCase) || string.Equals(resPath, "library/unity default resources", StringComparison.OrdinalIgnoreCase); } public static int CombineHashCodes(params int[] hashCodes) { int hash1 = (5381 << 16) + 5381; int hash2 = hash1; int i = 0; foreach (var hashCode in hashCodes) { if (i % 2 == 0) hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ hashCode; else hash2 = ((hash2 << 5) + hash2 + (hash2 >> 27)) ^ hashCode; ++i; } return hash1 + (hash2 * 1566083941); } } static class SerializedPropertyExtension { readonly struct Cache : IEquatable<Cache> { readonly Type host; readonly string path; public Cache(Type host, string path) { this.host = host; this.path = path; } public bool Equals(Cache other) { return Equals(host, other.host) && string.Equals(path, other.path, StringComparison.Ordinal); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is Cache && Equals((Cache)obj); } public override int GetHashCode() { unchecked { return ((host != null ? host.GetHashCode() : 0) * 397) ^ (path != null ? path.GetHashCode() : 0); } } } class MemberInfoCache { public MemberInfo fieldInfo; public Type type; } static Type s_NativePropertyAttributeType; static Dictionary<Cache, MemberInfoCache> s_MemberInfoFromPropertyPathCache = new Dictionary<Cache, MemberInfoCache>(); public static Type GetManagedType(this SerializedProperty property) { var host = property.serializedObject?.targetObject?.GetType(); if (host == null) return null; var path = property.propertyPath; var cache = new Cache(host, path); if (s_MemberInfoFromPropertyPathCache.TryGetValue(cache, out var infoCache)) return infoCache?.type; const string arrayData = @"\.Array\.data\[[0-9]+\]"; // we are looking for array element only when the path ends with Array.data[x] var lookingForArrayElement = Regex.IsMatch(path, arrayData + "$"); // remove any Array.data[x] from the path because it is prevents cache searching. path = Regex.Replace(path, arrayData, ".___ArrayElement___"); MemberInfo memberInfo = null; var type = host; string[] parts = path.Split('.'); for (int i = 0; i < parts.Length; i++) { string member = parts[i]; string alternateName = null; if (member.StartsWith("m_", StringComparison.Ordinal)) alternateName = member.Substring(2); foreach (MemberInfo f in type.GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { if ((f.MemberType & (MemberTypes.Property | MemberTypes.Field)) == 0) continue; var memberName = f.Name; if (f is PropertyInfo pi) { if (!pi.CanRead) continue; s_NativePropertyAttributeType = typeof(UnityEngine.Bindings.NativePropertyAttribute); var nattr = pi.GetCustomAttribute(s_NativePropertyAttributeType); if (nattr != null) memberName = s_NativePropertyAttributeType.GetProperty("Name").GetValue(nattr) as string ?? string.Empty; } if (string.Equals(member, memberName, StringComparison.Ordinal) || (alternateName != null && string.Equals(alternateName, memberName, StringComparison.OrdinalIgnoreCase))) { memberInfo = f; break; } } if (memberInfo is FieldInfo fi) type = fi.FieldType; else if (memberInfo is PropertyInfo pi) type = pi.PropertyType; else continue; // we want to get the element type if we are looking for Array.data[x] if (i < parts.Length - 1 && parts[i + 1] == "___ArrayElement___" && type.IsArrayOrList()) { i++; // skip the "___ArrayElement___" part type = type.GetArrayOrListElementType(); } } if (memberInfo == null) { s_MemberInfoFromPropertyPathCache.Add(cache, null); return null; } // we want to get the element type if we are looking for Array.data[x] if (lookingForArrayElement && type != null && type.IsArrayOrList()) type = type.GetArrayOrListElementType(); s_MemberInfoFromPropertyPathCache.Add(cache, new MemberInfoCache { type = type, fieldInfo = memberInfo }); return type; } } }
UnityCsReference/Modules/QuickSearch/Editor/Utilities/Utils.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/Utilities/Utils.cs", "repo_id": "UnityCsReference", "token_count": 28164 }
460
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using UnityEditor.PackageManager; using UnityEditor.SceneManagement; using UnityEditor.Scripting.ScriptCompilation; using UnityEditor.Utils; using UnityEngine; using UnityEngine.SceneManagement; namespace UnityEditor.SceneTemplate { internal enum BuiltinTemplateType { Empty, Default2D, Default2DMode3DCamera, Default3D } internal static class SceneTemplateUtils { private const string k_LastSceneOperationFolder = "SceneTemplateLastOperationFolder"; public const string TemplateScenePropertyName = nameof(SceneTemplateAsset.templateScene); public const string TemplatePipelineName = nameof(SceneTemplateAsset.templatePipeline); public const string TemplateTitlePropertyName = nameof(SceneTemplateAsset.templateName); public const string TemplateDescriptionPropertyName = nameof(SceneTemplateAsset.description); public const string TemplateAddToDefaultsPropertyName = nameof(SceneTemplateAsset.addToDefaults); public const string TemplateThumbnailPropertyName = nameof(SceneTemplateAsset.preview); public const string TemplateThumbnailBadgePropertyName = nameof(SceneTemplateAsset.badge); public const string DependenciesPropertyName = nameof(SceneTemplateAsset.dependencies); public const string DependencyPropertyName = nameof(DependencyInfo.dependency); public const string InstantiationModePropertyName = nameof(DependencyInfo.instantiationMode); internal static SceneTemplateInfo emptySceneTemplateInfo = new SceneTemplateInfo { name = "Empty", isPinned = true, thumbnailPath = $"{Styles.k_IconsFolderFolder}scene-template-empty-scene.png", description = L10n.Tr("Just an empty scene - no Game Objects."), onCreateCallback = additive => CreateBuiltinScene(BuiltinTemplateType.Empty, additive) }; internal static SceneTemplateInfo default2DSceneTemplateInfo = new SceneTemplateInfo { name = "Basic 2D (Built-in)", isPinned = true, thumbnailPath = $"{Styles.k_IconsFolderFolder}scene-template-2d-scene.png", badgePath = $"{Styles.k_IconsFolderFolder}2d-badge-scene-template.png", description = L10n.Tr("Contains an orthographic camera setup for 2D games. Works with built-in renderer."), onCreateCallback = additive => CreateBuiltinScene(BuiltinTemplateType.Default2D, additive) }; internal static SceneTemplateInfo default2DMode3DSceneTemplateInfo = new SceneTemplateInfo { name = "Basic 3D (Built-in)", isPinned = true, thumbnailPath = $"{Styles.k_IconsFolderFolder}scene-template-3d-scene.png", badgePath = $"{Styles.k_IconsFolderFolder}3d-badge-scene-template.png", description = L10n.Tr("Contains a camera and directional light. Works with built-in renderer."), onCreateCallback = additive => CreateBuiltinScene(BuiltinTemplateType.Default2DMode3DCamera, additive) }; internal static SceneTemplateInfo default3DSceneTemplateInfo = new SceneTemplateInfo { name = "Basic (Built-in)", isPinned = true, thumbnailPath = $"{Styles.k_IconsFolderFolder}scene-template-3d-scene.png", badgePath = $"{Styles.k_IconsFolderFolder}3d-badge-scene-template.png", description = L10n.Tr("Contains a camera and directional light, works with built-in renderer."), onCreateCallback = additive => CreateBuiltinScene(BuiltinTemplateType.Default3D, additive) }; internal static SceneTemplateInfo[] builtinTemplateInfos = new[] { emptySceneTemplateInfo, default2DSceneTemplateInfo, default2DMode3DSceneTemplateInfo, default3DSceneTemplateInfo }; internal static SceneTemplateInfo[] builtin2DTemplateInfos = new[] { emptySceneTemplateInfo, default2DSceneTemplateInfo, default2DMode3DSceneTemplateInfo }; internal static SceneTemplateInfo[] builtin3DTemplateInfos = new[] { emptySceneTemplateInfo, default3DSceneTemplateInfo }; internal static IEnumerable<string> GetSceneTemplatePaths() { return GetSceneTemplates().Select(asset => AssetDatabase.GetAssetPath(asset.GetInstanceID())); } internal static IEnumerable<SceneTemplateAsset> GetSceneTemplates() { using (var sceneTemplateItr = AssetDatabase.EnumerateAllAssets(CreateSceneTemplateSearchFilter())) { while (sceneTemplateItr.MoveNext()) yield return sceneTemplateItr.Current.pptrValue as SceneTemplateAsset; } } private static SearchFilter CreateSceneTemplateSearchFilter() { return new SearchFilter { searchArea = SearchFilter.SearchArea.AllAssets, classNames = new[] { nameof(SceneTemplateAsset) }, showAllHits = false }; } internal static Rect GetMainWindowCenteredPosition(Vector2 size) { var mainWindowRect = EditorGUIUtility.GetMainWindowPosition(); return EditorGUIUtility.GetCenteredWindowPosition(mainWindowRect, size); } internal static void SetLastFolder(string path) { if (!string.IsNullOrEmpty(path)) { var lastFolder = path; if (File.Exists(path)) lastFolder = Path.GetDirectoryName(path); if (Path.IsPathRooted(lastFolder)) { lastFolder = FileUtil.GetProjectRelativePath(lastFolder); } if (Directory.Exists(lastFolder)) { EditorPrefs.SetString($"{k_LastSceneOperationFolder}{Path.GetExtension(path)}", lastFolder); } } } internal static string GetLastFolder(string fileExtension) { var lastFolder = EditorPrefs.GetString($"{k_LastSceneOperationFolder}.{fileExtension}", null); if (lastFolder != null) { if (Path.IsPathRooted(lastFolder)) { lastFolder = FileUtil.GetProjectRelativePath(lastFolder); } if (!Directory.Exists(lastFolder)) { lastFolder = null; } } return lastFolder ?? "Assets"; } internal static string SaveFilePanelUniqueName(string title, string directory, string filename, string extension, bool showSaveFilePanel = true) { var extensionWithDot = $".{extension}"; var initialPath = Path.Combine(directory, filename + extensionWithDot).Replace("\\", "/"); if (Path.IsPathRooted(initialPath)) { initialPath = FileUtil.GetProjectRelativePath(initialPath); } var uniqueAssetPath = AssetDatabase.GenerateUniqueAssetPath(initialPath); directory = Path.GetDirectoryName(uniqueAssetPath); filename = Path.GetFileName(uniqueAssetPath); var result = showSaveFilePanel ? EditorUtility.SaveFilePanel(title, directory, filename, extension) : new FileInfo(uniqueAssetPath).FullName; if (string.IsNullOrEmpty(result)) { // User has cancelled. return null; } directory = Paths.ConvertSeparatorsToUnity(Path.GetDirectoryName(result)); if (!Search.Utils.IsPathUnderProject(directory)) { UnityEngine.Debug.LogWarning($"Not a valid folder to save an asset: {directory}."); return null; } if (!Paths.IsValidAssetPath(result, extensionWithDot, out var errorMessage)) { UnityEngine.Debug.LogWarning($"Invalid asset path: {errorMessage}."); return null; } SetLastFolder(directory); return Search.Utils.GetPathUnderProject(result); } internal static void OpenDocumentationUrl() { Help.BrowseURL(Help.FindHelpNamed("scene-templates")); } internal static List<SceneTemplateInfo> GetSceneTemplateInfos() { var sceneTemplateList = new List<SceneTemplateInfo>(); // Add the special Empty and Basic template foreach (var builtinTemplateInfo in builtinTemplateInfos) { builtinTemplateInfo.isPinned = SceneTemplateProjectSettings.Get().GetPinState(builtinTemplateInfo.name); } // Check for real templateAssets: var sceneTemplateAssetInfos = GetSceneTemplates().Select(sceneTemplateAsset => { var templateAssetPath = AssetDatabase.GetAssetPath(sceneTemplateAsset.GetInstanceID()); return Tuple.Create(templateAssetPath, sceneTemplateAsset); }) .Where(templateData => { if (templateData.Item2 == null) return false; if (!templateData.Item2.isValid) return false; var pipeline = templateData.Item2.CreatePipeline(); if (pipeline == null) return true; return pipeline.IsValidTemplateForInstantiation(templateData.Item2); }). Select(templateData => { var assetName = Path.GetFileNameWithoutExtension(templateData.Item1); var isReadOnly = false; if (templateData.Item1.StartsWith("Packages/") && AssetDatabase.TryGetAssetFolderInfo(templateData.Item1, out var isRootFolder, out var isImmutable)) { isReadOnly = isImmutable; } return new SceneTemplateInfo { name = string.IsNullOrEmpty(templateData.Item2.templateName) ? assetName : templateData.Item2.templateName, isPinned = templateData.Item2.addToDefaults, isReadonly = isReadOnly, assetPath = templateData.Item1, description = templateData.Item2.description, thumbnail = templateData.Item2.preview, badge = templateData.Item2.badge, sceneTemplate = templateData.Item2, onCreateCallback = loadAdditively => CreateSceneFromTemplate(templateData.Item1, loadAdditively) }; }).ToList(); sceneTemplateAssetInfos.Sort(); sceneTemplateList.AddRange(sceneTemplateAssetInfos); if (EditorSettings.defaultBehaviorMode == EditorBehaviorMode.Mode2D) { sceneTemplateList.AddRange(builtin2DTemplateInfos); } else { sceneTemplateList.AddRange(builtin3DTemplateInfos); } return sceneTemplateList; } internal static bool CreateBuiltinScene(BuiltinTemplateType type, bool loadAdditively) { if (loadAdditively && HasSceneUntitled() && !EditorSceneManager.SaveOpenScenes()) { return false; } if (!loadAdditively && !EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) { return false; } var eventType = type != BuiltinTemplateType.Empty ? SceneTemplateAnalytics.SceneInstantiationType.DefaultScene : SceneTemplateAnalytics.SceneInstantiationType.EmptyScene; var instantiateEvent = new SceneTemplateAnalytics.SceneInstantiationEvent(eventType) { additive = loadAdditively }; Scene scene; switch (type) { case BuiltinTemplateType.Default2DMode3DCamera: // Fake 3D mode to ensure proper set of default game objects are created. EditorSettings.defaultBehaviorMode = EditorBehaviorMode.Mode3D; scene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, loadAdditively ? NewSceneMode.Additive : NewSceneMode.Single); EditorSettings.defaultBehaviorMode = EditorBehaviorMode.Mode2D; break; case BuiltinTemplateType.Default3D: scene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, loadAdditively ? NewSceneMode.Additive : NewSceneMode.Single); break; case BuiltinTemplateType.Default2D: scene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, loadAdditively ? NewSceneMode.Additive : NewSceneMode.Single); break; default: scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, loadAdditively ? NewSceneMode.Additive : NewSceneMode.Single); break; } EditorSceneManager.ClearSceneDirtiness(scene); SceneTemplateAnalytics.SendSceneInstantiationEvent(instantiateEvent); return true; } private static bool CreateSceneFromTemplate(string templateAssetPath, bool loadAdditively) { var sceneAsset = AssetDatabase.LoadAssetAtPath<SceneTemplateAsset>(templateAssetPath); if (sceneAsset == null) return false; if (!sceneAsset.isValid) { UnityEngine.Debug.LogError("Cannot instantiate scene template: scene is null or deleted."); return false; } return SceneTemplateService.Instantiate(sceneAsset, loadAdditively, null, SceneTemplateAnalytics.SceneInstantiationType.NewSceneMenu) != null; } internal static bool HasSceneUntitled() { for (var i = 0; i < SceneManager.sceneCount; ++i) { var scene = SceneManager.GetSceneAt(i); if (string.IsNullOrEmpty(scene.path)) return true; } return false; } // Based on UpmPackageInfo::IsPackageReadOnly() in PackageManagerCommon.cpp internal static bool IsPackageReadOnly(PackageManager.PackageInfo pi) { if (pi.source == PackageSource.Embedded || pi.source == PackageSource.Local) return false; return true; } internal static bool IsAssetReadOnly(string assetPath) { var pi = PackageManager.PackageInfo.FindForAssetPath(assetPath); return pi != null && IsPackageReadOnly(pi); } internal static void DeleteAsset(string path, int retryCount = 5) { var retries = 0; while (retries < retryCount && !AssetDatabase.DeleteAsset(path)) ++retries; if (retries >= retryCount) throw new Exception($"Failed to delete asset \"{path}\""); } } }
UnityCsReference/Modules/SceneTemplateEditor/SceneTemplateUtils.cs/0
{ "file_path": "UnityCsReference/Modules/SceneTemplateEditor/SceneTemplateUtils.cs", "repo_id": "UnityCsReference", "token_count": 6857 }
461
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using UnityEngine.Bindings; namespace UnityEditor.ShaderFoundry { [NativeHeader("Modules/ShaderFoundry/Public/BlockShaderInterface.h")] internal struct BlockShaderInterfaceInternal : IInternalType<BlockShaderInterfaceInternal> { internal FoundryHandle m_NameHandle; internal FoundryHandle m_AttributeListHandle; internal FoundryHandle m_ContainingNamespaceHandle; internal FoundryHandle m_ExtensionsListHandle; internal FoundryHandle m_CustomizationPointListHandle; internal FoundryHandle m_RegisteredTemplateListHandle; internal extern static BlockShaderInterfaceInternal Invalid(); internal extern bool IsValid(); internal extern bool RegisterTemplate(ShaderContainer container, FoundryHandle handle); // IInternalType BlockShaderInterfaceInternal IInternalType<BlockShaderInterfaceInternal>.ConstructInvalid() => Invalid(); } [FoundryAPI] internal readonly struct BlockShaderInterface : IEquatable<BlockShaderInterface>, IPublicType<BlockShaderInterface> { // data members readonly ShaderContainer container; readonly internal FoundryHandle handle; readonly BlockShaderInterfaceInternal blockShaderInterfaceInternal; // IPublicType ShaderContainer IPublicType.Container => Container; bool IPublicType.IsValid => IsValid; FoundryHandle IPublicType.Handle => handle; BlockShaderInterface IPublicType<BlockShaderInterface>.ConstructFromHandle(ShaderContainer container, FoundryHandle handle) => new BlockShaderInterface(container, handle); // public API public ShaderContainer Container => container; public bool IsValid => (container != null && handle.IsValid); public string Name => container?.GetString(blockShaderInterfaceInternal.m_NameHandle) ?? string.Empty; public IEnumerable<ShaderAttribute> Attributes { get { var listHandle = blockShaderInterfaceInternal.m_AttributeListHandle; return HandleListInternal.Enumerate<ShaderAttribute>(container, listHandle); } } public Namespace ContainingNamespace => new Namespace(container, blockShaderInterfaceInternal.m_ContainingNamespaceHandle); public IEnumerable<BlockShaderInterface> Extensions { get { var listHandle = blockShaderInterfaceInternal.m_ExtensionsListHandle; return HandleListInternal.Enumerate<BlockShaderInterface>(container, listHandle); } } public IEnumerable<CustomizationPoint> CustomizationPoints { get { var listHandle = blockShaderInterfaceInternal.m_CustomizationPointListHandle; return HandleListInternal.Enumerate<CustomizationPoint>(container, listHandle); } } public IEnumerable<InterfaceRegistrationStatement> RegisteredTemplates { get { var listHandle = blockShaderInterfaceInternal.m_RegisteredTemplateListHandle; return HandleListInternal.Enumerate<InterfaceRegistrationStatement>(container, listHandle); } } internal bool RegisterTemplate(ShaderContainer container, FoundryHandle statementHandle) { return blockShaderInterfaceInternal.RegisterTemplate(container, statementHandle); } // private internal BlockShaderInterface(ShaderContainer container, FoundryHandle handle) { this.container = container; this.handle = handle; ShaderContainer.Get(container, handle, out blockShaderInterfaceInternal); } public static BlockShaderInterface Invalid => new BlockShaderInterface(null, FoundryHandle.Invalid()); // Equals and operator == implement Reference Equality. ValueEquals does a deep compare if you need that instead. public override bool Equals(object obj) => obj is BlockShaderInterface other && this.Equals(other); public bool Equals(BlockShaderInterface other) => EqualityChecks.ReferenceEquals(this.handle, this.container, other.handle, other.container); public override int GetHashCode() => (container, handle).GetHashCode(); public static bool operator==(BlockShaderInterface lhs, BlockShaderInterface rhs) => lhs.Equals(rhs); public static bool operator!=(BlockShaderInterface lhs, BlockShaderInterface rhs) => !lhs.Equals(rhs); public class Builder { ShaderContainer container; public string Name; public List<ShaderAttribute> Attributes; public Namespace containingNamespace; public List<BlockShaderInterface> Extensions; public List<CustomizationPoint> CustomizationPoints; public ShaderContainer Container => container; public Builder(ShaderContainer container, string name) { this.container = container; this.Name = name; } public void AddAttribute(ShaderAttribute attribute) { Utilities.AddToList(ref Attributes, attribute); } public void AddExtension(BlockShaderInterface blockShaderInterface) { Utilities.AddToList(ref Extensions, blockShaderInterface); } public void AddCustomizationPoint(CustomizationPoint customizationPoint) { Utilities.AddToList(ref CustomizationPoints, customizationPoint); } public BlockShaderInterface Build() { var blockShaderInterfaceInternal = new BlockShaderInterfaceInternal() { m_NameHandle = container.AddString(Name), }; blockShaderInterfaceInternal.m_AttributeListHandle = HandleListInternal.Build(container, Attributes); blockShaderInterfaceInternal.m_ContainingNamespaceHandle = containingNamespace.handle; blockShaderInterfaceInternal.m_ExtensionsListHandle = HandleListInternal.Build(container, Extensions); blockShaderInterfaceInternal.m_CustomizationPointListHandle = HandleListInternal.Build(container, CustomizationPoints); blockShaderInterfaceInternal.m_RegisteredTemplateListHandle = HandleListInternal.Build(container, new List<InterfaceRegistrationStatement>()); var returnTypeHandle = container.Add(blockShaderInterfaceInternal); return new BlockShaderInterface(container, returnTypeHandle); } } } }
UnityCsReference/Modules/ShaderFoundry/ScriptBindings/BlockShaderInterface.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/ShaderFoundry/ScriptBindings/BlockShaderInterface.bindings.cs", "repo_id": "UnityCsReference", "token_count": 2601 }
462
// Unity 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.ShaderFoundry { [NativeHeader("Modules/ShaderFoundry/Public/IncludeDescriptor.h")] internal struct IncludeDescriptorInternal : IInternalType<IncludeDescriptorInternal> { internal FoundryHandle m_StringHandle; internal extern bool IsValid(); internal extern string GetValue(ShaderContainer container); internal extern static IncludeDescriptorInternal Invalid(); // IInternalType IncludeDescriptorInternal IInternalType<IncludeDescriptorInternal>.ConstructInvalid() => Invalid(); } [FoundryAPI] internal readonly struct IncludeDescriptor : IEquatable<IncludeDescriptor>, IPublicType<IncludeDescriptor> { // data members readonly ShaderContainer container; readonly IncludeDescriptorInternal descriptor; internal readonly FoundryHandle handle; // IPublicType ShaderContainer IPublicType.Container => Container; bool IPublicType.IsValid => IsValid; FoundryHandle IPublicType.Handle => handle; IncludeDescriptor IPublicType<IncludeDescriptor>.ConstructFromHandle(ShaderContainer container, FoundryHandle handle) => new IncludeDescriptor(container, handle); // public API public ShaderContainer Container => container; public bool IsValid => (container != null && descriptor.IsValid()); public string Value => descriptor.GetValue(container); // private internal IncludeDescriptor(ShaderContainer container, FoundryHandle handle) { this.container = container; this.handle = handle; ShaderContainer.Get(container, handle, out descriptor); } public static IncludeDescriptor Invalid => new IncludeDescriptor(null, FoundryHandle.Invalid()); // Equals and operator == implement Reference Equality. ValueEquals does a deep compare if you need that instead. public override bool Equals(object obj) => obj is IncludeDescriptor other && this.Equals(other); public bool Equals(IncludeDescriptor other) => EqualityChecks.ReferenceEquals(this.handle, this.container, other.handle, other.container); public override int GetHashCode() => (container, handle).GetHashCode(); public static bool operator==(IncludeDescriptor lhs, IncludeDescriptor rhs) => lhs.Equals(rhs); public static bool operator!=(IncludeDescriptor lhs, IncludeDescriptor rhs) => !lhs.Equals(rhs); public class Builder { ShaderContainer container; string value; public ShaderContainer Container => container; public Builder(ShaderContainer container, string value) { this.container = container; this.value = value; } public IncludeDescriptor Build() { var descriptor = new IncludeDescriptorInternal(); descriptor.m_StringHandle = container.AddString(value); var resultHandle = container.Add(descriptor); return new IncludeDescriptor(container, resultHandle); } } } }
UnityCsReference/Modules/ShaderFoundry/ScriptBindings/IncludeDescriptor.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/ShaderFoundry/ScriptBindings/IncludeDescriptor.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1246 }
463
// Unity 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.ShaderFoundry { [NativeHeader("Modules/ShaderFoundry/Public/ShaderDependency.h")] internal struct ShaderDependencyInternal : IInternalType<ShaderDependencyInternal> { internal FoundryHandle m_DependencyNameStringHandle; // string internal FoundryHandle m_ShaderNameStringHandle; // string internal extern static ShaderDependencyInternal Invalid(); internal extern bool IsValid(); internal extern string GetDependencyName(ShaderContainer container); internal extern string GetShaderName(ShaderContainer container); // IInternalType ShaderDependencyInternal IInternalType<ShaderDependencyInternal>.ConstructInvalid() => Invalid(); } [FoundryAPI] internal readonly struct ShaderDependency : IEquatable<ShaderDependency>, IComparable<ShaderDependency>, IPublicType<ShaderDependency> { // data members readonly ShaderContainer container; readonly internal FoundryHandle handle; readonly ShaderDependencyInternal shaderDependency; // IPublicType ShaderContainer IPublicType.Container => Container; bool IPublicType.IsValid => IsValid; FoundryHandle IPublicType.Handle => handle; ShaderDependency IPublicType<ShaderDependency>.ConstructFromHandle(ShaderContainer container, FoundryHandle handle) => new ShaderDependency(container, handle); // public API public ShaderContainer Container => container; public bool IsValid => (container != null && handle.IsValid); public ShaderDependency(ShaderContainer container, string dependencyName, string shaderName) : this(container, container.AddString(dependencyName), container.AddString(shaderName)) { } internal ShaderDependency(ShaderContainer container, FoundryHandle dependencyName, FoundryHandle shaderName) { if ((container == null) || (!dependencyName.IsValid) || (!shaderName.IsValid)) { this = Invalid; } else { shaderDependency.m_DependencyNameStringHandle = dependencyName; shaderDependency.m_ShaderNameStringHandle = shaderName; handle = container.Add(shaderDependency); this.container = handle.IsValid ? container : null; } } public string DependencyName => shaderDependency.GetDependencyName(container); public string ShaderName => shaderDependency.GetShaderName(container); internal ShaderDependency(ShaderContainer container, FoundryHandle handle) { this.container = container; this.handle = handle; ShaderContainer.Get(container, handle, out shaderDependency); } public static ShaderDependency Invalid => new ShaderDependency(null, FoundryHandle.Invalid()); // Equals and operator == implement Reference Equality. ValueEquals does a deep compare if you need that instead. public override bool Equals(object obj) => obj is ShaderDependency other && this.Equals(other); public bool Equals(ShaderDependency other) => EqualityChecks.ReferenceEquals(this.handle, this.container, other.handle, other.container); public override int GetHashCode() => (container, handle).GetHashCode(); public static bool operator==(ShaderDependency lhs, ShaderDependency rhs) => lhs.Equals(rhs); public static bool operator!=(ShaderDependency lhs, ShaderDependency rhs) => !lhs.Equals(rhs); public int CompareTo(ShaderDependency other) { int result = string.CompareOrdinal(DependencyName, other.DependencyName); if (result == 0) result = string.CompareOrdinal(ShaderName, other.ShaderName); return result; } public class Builder { ShaderContainer container; string dependencyName; string shaderName; public ShaderContainer Container => container; public Builder(ShaderContainer container, string dependencyName, string shaderName) { this.container = container; this.dependencyName = dependencyName; this.shaderName = shaderName; } public ShaderDependency Build() { return new ShaderDependency(container, dependencyName, shaderName); } } } }
UnityCsReference/Modules/ShaderFoundry/ScriptBindings/ShaderDependency.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/ShaderFoundry/ScriptBindings/ShaderDependency.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1826 }
464
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Collections.Generic; using System.Linq; using UnityEditor.IMGUI.Controls; using UnityEngine; namespace UnityEditor.ShortcutManagement { interface IConflictResolverView { void Show(IConflictResolver conflictResolver, IEnumerable<KeyCombination> keyCombinationSequence, IEnumerable<ShortcutEntry> entries); } class ConflictResolverView : IConflictResolverView { public void Show(IConflictResolver conflictResolver, IEnumerable<KeyCombination> keyCombinationSequence, IEnumerable<ShortcutEntry> entries) { ConflictResolverWindow.Show(conflictResolver, keyCombinationSequence, entries); } } class ConflictResolverWindow : EditorWindow { internal const string performButtonControlName = "PerformButton"; internal const string cancelButtonControlName = "CancelButton"; internal const string rebindToggleCommandName = "rebindToggle"; internal static ConflictResolverWindow Show(IConflictResolver conflictResolver, IEnumerable<KeyCombination> keyCombinationSequence, IEnumerable<ShortcutEntry> entries) { var win = CreateInstance<ConflictResolverWindow>(); win.Init(conflictResolver, keyCombinationSequence, entries, GUIView.focusedView); win.minSize = new Vector2(550, 250); win.maxSize = new Vector2(550, 600); win.ShowModal(); win.Focus(); return win; } static class Styles { public static GUIStyle wordWrapped = EditorStyles.wordWrappedLabel; public static GUIStyle commandsArea; public static GUIStyle panel; public static GUIStyle warningIcon; static Styles() { commandsArea = new GUIStyle(); commandsArea.margin = new RectOffset(0, 10, 0, 0); commandsArea.stretchHeight = true; panel = new GUIStyle(); panel.margin = new RectOffset(10, 10, 10, 10); warningIcon = new GUIStyle(); warningIcon.margin = new RectOffset(15, 15, 15, 15); } } static class Contents { public static GUIContent description = EditorGUIUtility.TrTextContent("You can choose to perform a single command, rebind the shortcut to the selected command, or resolve the conflict in the Shortcut Manager."); public static GUIContent cancel = EditorGUIUtility.TrTextContent("Cancel"); public static GUIContent perform = EditorGUIUtility.TrTextContent("Perform Selected"); public static GUIContent rebind = EditorGUIUtility.TrTextContent("Rebind Selected"); public static GUIContent itemName = EditorGUIUtility.TrTextContent("Name"); public static GUIContent itemType = EditorGUIUtility.TrTextContent("Type"); public static GUIContent itemBindings = EditorGUIUtility.TrTextContent("Shortcut"); public static GUIContent windowTitle = EditorGUIUtility.TrTextContent("Shortcut Conflict"); public static GUIContent rebindToSelectedCommand = EditorGUIUtility.TrTextContent("Rebind to selected command"); public static GUIContent SelectCommandHeading = EditorGUIUtility.TrTextContent("Select a command to perform:"); public static GUIContent OpenShortcutManager = EditorGUIUtility.TrTextContent("Resolve Conflict..."); public static Texture2D warningIcon = (Texture2D)EditorGUIUtility.LoadRequired("Icons/ShortcutManager/alertDialog.png"); } class ConflictListView : TreeView { List<ShortcutEntry> m_Entries; enum MyColumns { Name, Type, Binding } public ConflictListView(TreeViewState state, List<ShortcutEntry> entries) : base(state) { m_Entries = entries; Reload(); } public ConflictListView(TreeViewState state, MultiColumnHeader multicolumnHeader, List<ShortcutEntry> entries) : base(state, multicolumnHeader) { rowHeight = 20; showAlternatingRowBackgrounds = true; showBorder = true; m_Entries = entries; Reload(); } protected override bool CanMultiSelect(TreeViewItem item) { return false; } protected override TreeViewItem BuildRoot() { var root = new TreeViewItem {id = -1, depth = -1, displayName = "Root"}; var allItems = new List<TreeViewItem>(m_Entries.Count); for (var index = 0; index < m_Entries.Count; index++) { var shortcutEntry = m_Entries[index]; allItems.Add(new TreeViewItem { id = index, depth = 0, displayName = shortcutEntry.displayName }); } SetupParentsAndChildrenFromDepths(root, allItems); return root; } protected override void RowGUI(RowGUIArgs args) { var item = m_Entries[args.item.id]; for (int i = 0; i < args.GetNumVisibleColumns(); ++i) { CellGUI(args.GetCellRect(i), item, (MyColumns)args.GetColumn(i), ref args); } } static void CellGUI(Rect getCellRect, ShortcutEntry item, MyColumns getColumn, ref RowGUIArgs args) { switch (getColumn) { case MyColumns.Name: { GUI.Label(getCellRect, item.displayName); break; } case MyColumns.Type: { GUI.Label(getCellRect, item.type.ToString()); break; } case MyColumns.Binding: { GUI.Label(getCellRect, KeyCombination.SequenceToString(item.combinations)); break; } } } } enum ActionSelected { Cancel, ExecuteOnce, ExecuteAlways } IConflictResolver m_ConflictResolver; List<ShortcutEntry> m_Entries; [SerializeField] TreeViewState m_TreeViewState; [SerializeField] MultiColumnHeaderState m_MulticolumnHeaderState; ConflictListView m_ConflictListView; bool m_Rebind; string m_Header; bool m_InitialSizingDone; ShortcutEntry m_SelectedEntry; ActionSelected m_CloseBehaviour = ActionSelected.Cancel; GUIView m_PreviouslyFocusedView; internal void Init(IConflictResolver conflictResolver, IEnumerable<KeyCombination> keyCombinationSequence, IEnumerable<ShortcutEntry> entries, GUIView previouslyFocusedView) { m_PreviouslyFocusedView = previouslyFocusedView; m_ConflictResolver = conflictResolver; m_Entries = entries.ToList(); var multiColumnHeader = new MultiColumnHeader(m_MulticolumnHeaderState); multiColumnHeader.ResizeToFit(); m_ConflictListView = new ConflictListView(m_TreeViewState, multiColumnHeader, m_Entries); m_Header = string.Format(L10n.Tr("The binding \"{0}\" conflicts with multiple commands."), KeyCombination.SequenceToString(keyCombinationSequence)); } private void OnEnable() { titleContent = Contents.windowTitle; if (m_TreeViewState == null) m_TreeViewState = new TreeViewState(); var columns = new[] { new MultiColumnHeaderState.Column { headerContent = Contents.itemName, headerTextAlignment = TextAlignment.Left, canSort = false, autoResize = true, allowToggleVisibility = false, width = 350, }, new MultiColumnHeaderState.Column { headerContent = Contents.itemType, headerTextAlignment = TextAlignment.Left, width = 50f, canSort = false, autoResize = true, allowToggleVisibility = false, }, new MultiColumnHeaderState.Column { headerContent = Contents.itemBindings, headerTextAlignment = TextAlignment.Left, canSort = false, autoResize = true, allowToggleVisibility = false, width = 75f, } }; var newHeader = new MultiColumnHeaderState(columns); if (m_MulticolumnHeaderState != null) { MultiColumnHeaderState.OverwriteSerializedFields(m_MulticolumnHeaderState, newHeader); } m_MulticolumnHeaderState = newHeader; EditorApplication.LockReloadAssemblies(); } private void OnDisable() { if (m_CloseBehaviour == ActionSelected.Cancel) m_ConflictResolver.Cancel(); EditorApplication.UnlockReloadAssemblies(); //We need to delay this action, since actions can depend on the right view having focus, and when closing a window //that will change the current focused view to null. EditorApplication.CallDelayed(() => { m_PreviouslyFocusedView?.Focus(); switch (m_CloseBehaviour) { case ActionSelected.ExecuteAlways: m_ConflictResolver.ExecuteAlways(m_SelectedEntry); break; case ActionSelected.ExecuteOnce: m_ConflictResolver.ExecuteOnce(m_SelectedEntry); break; } }, 0f); } private void OnGUI() { EditorGUILayout.BeginVertical(Styles.panel); HandleInitialSizing(); Rect rect; EditorGUILayout.BeginHorizontal(); { GUILayout.Label(Contents.warningIcon, Styles.warningIcon); EditorGUILayout.BeginVertical(Styles.commandsArea); { GUILayout.Label(m_Header, EditorStyles.boldLabel); GUILayout.Label(Contents.description, EditorStyles.wordWrappedLabel); GUILayout.Label(Contents.SelectCommandHeading, EditorStyles.boldLabel); rect = GUILayoutUtility.GetRect(100, 4000, 50, 10000); GUI.Box(rect, GUIContent.none); GUI.SetNextControlName(rebindToggleCommandName); m_Rebind = GUILayout.Toggle(m_Rebind, Contents.rebindToSelectedCommand); } EditorGUILayout.EndVertical(); } EditorGUILayout.EndHorizontal(); m_ConflictListView.OnGUI(rect); EditorGUILayout.BeginHorizontal(); { if (GUILayout.Button(Contents.OpenShortcutManager)) { Close(); m_ConflictResolver.GoToShortcutManagerConflictCategory(); } GUILayout.FlexibleSpace(); bool hasSelection = m_ConflictListView.HasSelection(); using (new EditorGUI.DisabledScope(!hasSelection)) { ShortcutEntry entry = null; if (hasSelection) entry = m_Entries[m_ConflictListView.GetSelection().First()]; using (new EditorGUI.DisabledScope(entry == null || (entry.type == ShortcutType.Clutch && !m_Rebind))) { var buttonLabel = hasSelection && entry.type == ShortcutType.Clutch ? Contents.rebind : Contents.perform; GUI.SetNextControlName(performButtonControlName); if (GUILayout.Button(buttonLabel)) { m_SelectedEntry = entry; if (m_Rebind) m_CloseBehaviour = ActionSelected.ExecuteAlways; else m_CloseBehaviour = ActionSelected.ExecuteOnce; Close(); GUIUtility.ExitGUI(); } } } GUI.SetNextControlName(cancelButtonControlName); if (GUILayout.Button(Contents.cancel)) { Close(); GUIUtility.ExitGUI(); } } EditorGUILayout.EndHorizontal(); EditorGUILayout.EndVertical(); } void HandleInitialSizing() { if (m_InitialSizingDone) return; var pos = position; pos.height = 250; position = pos; m_InitialSizingDone = true; } } }
UnityCsReference/Modules/ShortcutManagerEditor/ConflictResolverWindow.cs/0
{ "file_path": "UnityCsReference/Modules/ShortcutManagerEditor/ConflictResolverWindow.cs", "repo_id": "UnityCsReference", "token_count": 6870 }
465
// Unity 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 System.Linq; using System.Reflection; using UnityEngine; namespace UnityEditor.ShortcutManagement { public abstract class ShortcutBaseAttribute : Attribute { internal abstract ShortcutEntry CreateShortcutEntry(MethodInfo methodInfo); } // TODO: Find better name [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class ShortcutAttribute : ShortcutBaseAttribute { internal string identifier { get; } internal Type context { get; } internal string tag { get; } internal ShortcutBinding defaultBinding { get; } internal int priority { get; } public string displayName { get; set; } Action m_NoArgumentsAction; ShortcutAttribute(string id, Type context, string tag, int priority, ShortcutBinding defaultBinding) { this.identifier = id; this.context = context; this.tag = tag; this.defaultBinding = defaultBinding; this.priority = ShortcutAttributeUtility.AssignPriority(context, priority); displayName = identifier; } public ShortcutAttribute(string id, [DefaultValue("null")] Type context = null) : this(id, context, null, int.MaxValue, ShortcutBinding.empty) { } public ShortcutAttribute(string id, Type context, KeyCode defaultKeyCode, [DefaultValue(nameof(ShortcutModifiers.None))] ShortcutModifiers defaultShortcutModifiers = ShortcutModifiers.None) : this(id, context, null, int.MaxValue, new ShortcutBinding(new KeyCombination(defaultKeyCode, defaultShortcutModifiers))) { } public ShortcutAttribute(string id, Type context, string tag, KeyCode defaultKeyCode, [DefaultValue(nameof(ShortcutModifiers.None))] ShortcutModifiers defaultShortcutModifiers = ShortcutModifiers.None) : this(id, context, tag, int.MaxValue, new ShortcutBinding(new KeyCombination(defaultKeyCode, defaultShortcutModifiers))) { } public ShortcutAttribute(string id, Type context, string tag, KeyCode defaultKeyCode, [DefaultValue(nameof(ShortcutModifiers.None))] ShortcutModifiers defaultShortcutModifiers, int priority) : this(id, context, tag, priority, new ShortcutBinding(new KeyCombination(defaultKeyCode, defaultShortcutModifiers))) { } public ShortcutAttribute(string id, KeyCode defaultKeyCode, [DefaultValue(nameof(ShortcutModifiers.None))] ShortcutModifiers defaultShortcutModifiers = ShortcutModifiers.None) : this(id, null, null, int.MaxValue, new ShortcutBinding(new KeyCombination(defaultKeyCode, defaultShortcutModifiers))) { } [RequiredSignature] static void ShortcutMethodWithArgs(ShortcutArguments args) { throw new InvalidOperationException(); } [RequiredSignature] static void ShortcutMethodNoArgs() { throw new InvalidOperationException(); } void NoArgumentShortcutMethodProxy(ShortcutArguments arguments) { m_NoArgumentsAction(); } internal override ShortcutEntry CreateShortcutEntry(MethodInfo methodInfo) { var identifier = new Identifier(methodInfo, this); var defaultCombination = defaultBinding.keyCombinationSequence; var type = this is ClutchShortcutAttribute ? ShortcutType.Clutch : ShortcutType.Action; var methodParams = methodInfo.GetParameters(); Action<ShortcutArguments> action; // We instantiate this as the specific delegate type in advance, // because passing ShortcutArguments in object[] via MethodInfo.Invoke() causes boxing/allocation if (methodParams.Any()) action = (Action<ShortcutArguments>)Delegate.CreateDelegate(typeof(Action<ShortcutArguments>), null, methodInfo); else { m_NoArgumentsAction = (Action)Delegate.CreateDelegate(typeof(Action), null, methodInfo); action = NoArgumentShortcutMethodProxy; } var entry = new ShortcutEntry(identifier, defaultCombination, action, context, tag, type, displayName, priority); foreach (var attribute in methodInfo.GetCustomAttributes(typeof(ReserveModifiersAttribute), true)) entry.m_ReservedModifier |= (attribute as ReserveModifiersAttribute).Modifiers; return entry; } } [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class ClutchShortcutAttribute : ShortcutAttribute { internal readonly Type clutchActivatedContext; public ClutchShortcutAttribute(string id, [DefaultValue("null")] Type context = null) : base(id, context) { } public ClutchShortcutAttribute(string id, Type context, KeyCode defaultKeyCode, [DefaultValue(nameof(ShortcutModifiers.None))] ShortcutModifiers defaultShortcutModifiers = ShortcutModifiers.None) : base(id, context, defaultKeyCode, defaultShortcutModifiers) { } public ClutchShortcutAttribute(string id, Type context, string tag, KeyCode defaultKeyCode, [DefaultValue(nameof(ShortcutModifiers.None))] ShortcutModifiers defaultShortcutModifiers = ShortcutModifiers.None) : base(id, context, tag, defaultKeyCode, defaultShortcutModifiers) { } public ClutchShortcutAttribute(string id, Type context, string tag, KeyCode defaultKeyCode, [DefaultValue(nameof(ShortcutModifiers.None))] ShortcutModifiers defaultShortcutModifiers, int priority) : base(id, context, tag, defaultKeyCode, defaultShortcutModifiers, priority) { } public ClutchShortcutAttribute(string id, KeyCode defaultKeyCode, [DefaultValue(nameof(ShortcutModifiers.None))] ShortcutModifiers defaultShortcutModifiers = ShortcutModifiers.None) : base(id, defaultKeyCode, defaultShortcutModifiers) { } internal ClutchShortcutAttribute(string id, Type context, Type clutchActivatedContext, KeyCode defaultKeyCode, ShortcutModifiers defaultShortcutModifiers = ShortcutModifiers.None) : base(id, context, defaultKeyCode, defaultShortcutModifiers) { this.clutchActivatedContext = clutchActivatedContext; } [RequiredSignature] static void ShortcutClutchMethod(ShortcutArguments args) { throw new InvalidOperationException(); } } // We want GameView shortcuts to trigger even in play mode so we declare them as menu shortcuts class GameViewShortcutAttribute : ShortcutBaseAttribute { internal string identifier { get; } internal ShortcutBinding defaultBinding { get; } public string displayName { get; set; } Action m_NoArgumentsAction; GameViewShortcutAttribute(string id, ShortcutBinding defaultBinding) { this.identifier = id; this.defaultBinding = defaultBinding; displayName = identifier; } public GameViewShortcutAttribute(string id) : this(id, ShortcutBinding.empty) { } public GameViewShortcutAttribute(string id, KeyCode defaultKeyCode, [DefaultValue("None")] ShortcutModifiers defaultShortcutModifiers = ShortcutModifiers.None) : this(id, new ShortcutBinding(new KeyCombination(defaultKeyCode, defaultShortcutModifiers))) { } void NoArgumentShortcutMethodProxy(ShortcutArguments arguments) { m_NoArgumentsAction(); } internal override ShortcutEntry CreateShortcutEntry(MethodInfo methodInfo) { var defaultCombination = defaultBinding.keyCombinationSequence; var type = ShortcutType.Menu; var methodParams = methodInfo.GetParameters(); Action<ShortcutArguments> action; // We instantiate this as the specific delegate type in advance, // because passing ShortcutArguments in object[] via MethodInfo.Invoke() causes boxing/allocation if (methodParams.Any()) action = (Action<ShortcutArguments>)Delegate.CreateDelegate(typeof(Action<ShortcutArguments>), null, methodInfo); else { m_NoArgumentsAction = (Action)Delegate.CreateDelegate(typeof(Action), null, methodInfo); action = NoArgumentShortcutMethodProxy; } return new ShortcutEntry(new Identifier(identifier), defaultCombination, action, typeof(GameView), null, type, displayName); } } class ShortcutAttributeUtility { internal const int DefaultGlobalPriority = 1_000_000; internal const int DefaultContextPriority = 1_000; internal static int AssignPriority(Type context, int suggestedPriority = int.MaxValue) { if (suggestedPriority == int.MaxValue) { if (context == null || context == ContextManager.globalContextType) return DefaultGlobalPriority; else return DefaultContextPriority; } return suggestedPriority; } } }
UnityCsReference/Modules/ShortcutManagerEditor/ShortcutAttribute.cs/0
{ "file_path": "UnityCsReference/Modules/ShortcutManagerEditor/ShortcutAttribute.cs", "repo_id": "UnityCsReference", "token_count": 3507 }
466
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using UnityEngine.Bindings; using UnityEngine.Scripting; namespace UnityEngine { [RejectDragAndDropMaterial] [NativeType(Header = "Modules/SpriteMask/Public/SpriteMask.h")] public sealed partial class SpriteMask : Renderer { public enum MaskSource { Sprite = 0, SupportedRenderers = 1, } extern public int frontSortingLayerID { get; set; } extern public int frontSortingOrder { get; set; } extern public int backSortingLayerID { get; set; } extern public int backSortingOrder { get; set; } extern public float alphaCutoff { get; set; } extern public Sprite sprite { get; set; } extern public bool isCustomRangeActive {[NativeMethod("IsCustomRangeActive")] get; [NativeMethod("SetCustomRangeActive")] set; } public extern SpriteSortPoint spriteSortPoint { get; set; } public extern MaskSource maskSource { get; set; } internal extern Renderer cachedSupportedRenderer { get; } internal extern Bounds GetSpriteBounds(); } [NativeHeader("Modules/SpriteMask/Public/ScriptBindings/SpriteMask.bindings.h")] [StaticAccessor("SpriteUtilityBindings", StaticAccessorType.DoubleColon)] public static class SpriteMaskUtility { extern public static bool HasSpriteMaskInScene(); } }
UnityCsReference/Modules/SpriteMask/Public/ScriptBindings/SpriteMask.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/SpriteMask/Public/ScriptBindings/SpriteMask.bindings.cs", "repo_id": "UnityCsReference", "token_count": 577 }
467
// Unity 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.IO; using System.Runtime.CompilerServices; using System.Text; using UnityEngine; using UnityEngine.UIElements; [assembly: InternalsVisibleTo("Assembly-CSharp-Editor-testable")] namespace UnityEditor.StyleSheets { internal class UssComments { public Dictionary<StyleRule, string> ruleComments { get; private set; } public Dictionary<StyleProperty, string> propertyComments { get; private set; } public UssComments() { ruleComments = new Dictionary<StyleRule, string>(); propertyComments = new Dictionary<StyleProperty, string>(); } public string Get(StyleRule rule) { string comment; if (!ruleComments.TryGetValue(rule, out comment)) { comment = ""; } return comment; } public string Get(StyleProperty property) { string comment; if (!propertyComments.TryGetValue(property, out comment)) { comment = ""; } return comment; } public void TryGet(StyleRule rule, Action<string> next) { string comment; if (ruleComments.TryGetValue(rule, out comment)) { next(comment); } } public void TryGet(StyleProperty property, Action<string> next) { string comment; if (propertyComments.TryGetValue(property, out comment)) { next(comment); } } public void AddComment(StyleRule rule, string comment) { if (!string.IsNullOrEmpty(comment)) { ruleComments.Add(rule, comment); } } public void AddComment(StyleProperty property, string comment) { if (!string.IsNullOrEmpty(comment)) { propertyComments.Add(property, comment); } } } internal class UssExportOptions { public UssExportOptions() { comments = new UssComments(); propertyIndent = " "; withComment = true; exportDefaultValues = true; } public UssExportOptions(UssExportOptions opts) : base() { comments = opts.comments ?? new UssComments(); propertyIndent = opts.propertyIndent; withComment = opts.withComment; exportDefaultValues = opts.exportDefaultValues; } public string propertyIndent { get; set; } public bool useColorCode { get; set; } public bool withComment { get; set; } public UssComments comments { get; set; } public bool exportDefaultValues { get; set; } public void AddComment(StyleRule rule, string comment) { if (withComment && !string.IsNullOrEmpty(comment)) { comments.ruleComments.Add(rule, comment); } } public void AddComment(StyleProperty property, string comment) { if (withComment && !string.IsNullOrEmpty(comment)) { comments.propertyComments.Add(property, comment); } } } internal class StyleSheetToUss { static void AddComment(StringBuilder sb, string comment, string indent = "") { sb.Append(indent); var lines = comment.Split('\n'); if (lines.Length == 1) { sb.Append("/* "); sb.Append(comment); sb.Append(" */\n"); } else { sb.Append("/*\n"); foreach (var line in lines) { sb.Append(" "); sb.Append(indent); sb.Append(line); sb.Append("\n"); } sb.Append(indent); sb.Append("*/\n"); } } static int ColorComponent(float component) { return (int)Math.Round(component * byte.MaxValue, 0, MidpointRounding.AwayFromZero); } public static string ToUssString(UnityEngine.Color color, bool useColorCode = false) { string str; string alpha = color.a.ToString("0.##", CultureInfo.InvariantCulture.NumberFormat); if (alpha != "1") { str = UnityString.Format("rgba({0}, {1}, {2}, {3:F2})", ColorComponent(color.r), ColorComponent(color.g), ColorComponent(color.b), alpha); } else if (!useColorCode) { str = UnityString.Format("rgb({0}, {1}, {2})", ColorComponent(color.r), ColorComponent(color.g), ColorComponent(color.b)); } else { str = UnityString.Format("#{0}", ColorUtility.ToHtmlStringRGB(color)); } return str; } public static string ToUssString(StyleSheet sheet, UssExportOptions options, StyleValueHandle handle) { string str = ""; switch (handle.valueType) { case StyleValueType.Keyword: str = sheet.ReadKeyword(handle).ToString().ToLower(); break; case StyleValueType.Float: str = sheet.ReadFloat(handle).ToString(CultureInfo.InvariantCulture.NumberFormat); break; case StyleValueType.Dimension: str = sheet.ReadDimension(handle).ToString(); break; case StyleValueType.Color: UnityEngine.Color color = sheet.ReadColor(handle); str = ToUssString(color, options.useColorCode); break; case StyleValueType.ResourcePath: str = $"resource(\"{sheet.ReadResourcePath(handle)}\")"; break; case StyleValueType.Enum: str = sheet.ReadEnum(handle); break; case StyleValueType.String: str = $"\"{sheet.ReadString(handle)}\""; break; case StyleValueType.Variable: str = sheet.ReadVariable(handle); break; case StyleValueType.Function: str = sheet.ReadFunctionName(handle); break; case StyleValueType.CommaSeparator: str = ","; break; default: throw new ArgumentException("Unhandled type " + handle.valueType); } return str; } public static void ToUssString(StringBuilder sb, StyleSheet sheet, UssExportOptions options, StyleValueHandle[] values, ref int valueIndex, int valueCount = -1) { for (; valueIndex < values.Length && valueCount != 0; --valueCount) { var propertyValue = values[valueIndex++]; switch (propertyValue.valueType) { case StyleValueType.Function: // First param: function name sb.Append(sheet.ReadFunctionName(propertyValue)); sb.Append("("); // Second param: number of arguments var nbParams = (int)sheet.ReadFloat(values[valueIndex++]); ToUssString(sb, sheet, options, values, ref valueIndex, nbParams); sb.Append(")"); break; case StyleValueType.CommaSeparator: sb.Append(","); break; default: { var propertyValueStr = ToUssString(sheet, options, propertyValue); sb.Append(propertyValueStr); break; } } if (valueIndex < values.Length && values[valueIndex].valueType != StyleValueType.CommaSeparator && valueCount != 1) { sb.Append(" "); } } } public static void ToUssString(StyleSheet sheet, UssExportOptions options, StyleRule rule, StringBuilder sb) { foreach (var property in rule.properties) { options.comments.TryGet(property, comment => { if (rule.properties[0] != property) { sb.Append("\n"); } AddComment(sb, comment, options.propertyIndent); }); sb.Append(options.propertyIndent); sb.Append(property.name); sb.Append(":"); if (property.name == "cursor" && property.values.Length > 1) { int i; string propertyValueStr; for (i = 0; i < property.values.Length - 1; i++) { propertyValueStr = ToUssString(sheet, options, property.values[i]); if (propertyValueStr != ",") sb.Append(" "); sb.Append(propertyValueStr); } sb.Append(" "); propertyValueStr = ToUssString(sheet, options, property.values[i]); sb.Append(propertyValueStr); } else { var valueIndex = 0; sb.Append(" "); ToUssString(sb, sheet, options, property.values, ref valueIndex); } sb.Append(";\n"); } } public static void ToUssString(StyleSelectorRelationship previousRelationship, StyleSelectorPart[] parts, StringBuilder sb) { if (previousRelationship != StyleSelectorRelationship.None) sb.Append(previousRelationship == StyleSelectorRelationship.Child ? " > " : " "); foreach (var selectorPart in parts) { switch (selectorPart.type) { case StyleSelectorType.Wildcard: sb.Append('*'); break; case StyleSelectorType.Type: sb.Append(selectorPart.value); break; case StyleSelectorType.Class: sb.Append('.'); sb.Append(selectorPart.value); break; case StyleSelectorType.PseudoClass: sb.Append(':'); sb.Append(selectorPart.value); break; case StyleSelectorType.ID: sb.Append('#'); sb.Append(selectorPart.value); break; default: throw new ArgumentOutOfRangeException(); } } } public static string ToUssSelector(StyleComplexSelector complexSelector) { var sb = new StringBuilder(); foreach (var selector in complexSelector.selectors) { ToUssString(selector.previousRelationship, selector.parts, sb); } return sb.ToString(); } public static void ToUssString(StyleSheet sheet, UssExportOptions options, StyleComplexSelector complexSelector, StringBuilder sb) { options.comments.TryGet(complexSelector.rule, comment => AddComment(sb, comment)); foreach (var selector in complexSelector.selectors) { ToUssString(selector.previousRelationship, selector.parts, sb); } sb.Append(" {\n"); ToUssString(sheet, options, complexSelector.rule, sb); sb.Append("}"); sb.Append("\n"); } public static string ToUssString(StyleSheet sheet, UssExportOptions options = null) { if (options == null) { options = new UssExportOptions(); } var sb = new StringBuilder(); if (sheet.complexSelectors != null) { for (var complexSelectorIndex = 0; complexSelectorIndex < sheet.complexSelectors.Length; ++complexSelectorIndex) { var complexSelector = sheet.complexSelectors[complexSelectorIndex]; ToUssString(sheet, options, complexSelector, sb); if (complexSelectorIndex != sheet.complexSelectors.Length - 1) { sb.Append("\n"); } } } return sb.ToString(); } public static void WriteStyleSheet(StyleSheet sheet, string path, UssExportOptions options = null) { File.WriteAllText(path, ToUssString(sheet, options)); } } }
UnityCsReference/Modules/StyleSheetsEditor/Converters/StyleSheetToUss.cs/0
{ "file_path": "UnityCsReference/Modules/StyleSheetsEditor/Converters/StyleSheetToUss.cs", "repo_id": "UnityCsReference", "token_count": 7450 }
468
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEngine.SubsystemsImplementation { public static partial class SubsystemDescriptorStore { #pragma warning disable CS0618 internal static void RegisterDeprecatedDescriptor(SubsystemDescriptor descriptor) => RegisterDescriptor(descriptor, s_DeprecatedDescriptors); #pragma warning restore CS0618 } }
UnityCsReference/Modules/Subsystems/SubsystemDescriptorStore.deprecated.cs/0
{ "file_path": "UnityCsReference/Modules/Subsystems/SubsystemDescriptorStore.deprecated.cs", "repo_id": "UnityCsReference", "token_count": 147 }
469
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Runtime.InteropServices; using UnityEngine.Bindings; using UnityEngine.Scripting; namespace UnityEngine { // NOTE: keep in sync with TerrainLayer::SmoothnessSource in TerrainLayer.h public enum TerrainLayerSmoothnessSource { Constant, DiffuseAlphaChannel } [StructLayout(LayoutKind.Sequential)] [UsedByNativeCode] [NativeHeader("TerrainScriptingClasses.h")] [NativeHeader("Modules/Terrain/Public/TerrainLayerScriptingInterface.h")] public sealed partial class TerrainLayer : Object { public TerrainLayer() { Internal_Create(this); } [FreeFunction("TerrainLayerScriptingInterface::Create")] extern private static void Internal_Create([Writable] TerrainLayer layer); extern public Texture2D diffuseTexture { get; set; } extern public Texture2D normalMapTexture { get; set; } extern public Texture2D maskMapTexture { get; set; } extern public Vector2 tileSize { get; set; } extern public Vector2 tileOffset { get; set; } [NativeProperty("SpecularColor")] extern public Color specular { get; set; } extern public float metallic { get; set; } extern public float smoothness { get; set; } extern public float normalScale { get; set; } extern public Vector4 diffuseRemapMin { get; set; } extern public Vector4 diffuseRemapMax { get; set; } extern public Vector4 maskMapRemapMin { get; set; } extern public Vector4 maskMapRemapMax { get; set; } extern public TerrainLayerSmoothnessSource smoothnessSource { get; set; } } }
UnityCsReference/Modules/Terrain/Public/TerrainLayer.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Terrain/Public/TerrainLayer.bindings.cs", "repo_id": "UnityCsReference", "token_count": 633 }
470
// 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 UnityEngine.TerrainTools; using UnityEditor.ShortcutManagement; namespace UnityEditor.TerrainTools { internal class PaintHeightTool : TerrainPaintToolWithOverlays<PaintHeightTool> { internal const string k_ToolName = "Raise or Lower Terrain"; public override string OnIcon => "TerrainOverlays/PaintHeight_On.png"; public override string OffIcon => "TerrainOverlays/PaintHeight.png"; [FormerlyPrefKeyAs("Terrain/Raise Height", "f1")] [Shortcut("Terrain/Raise or Lower Terrain", typeof(TerrainToolShortcutContext), KeyCode.F1)] static void SelectShortcut(ShortcutArguments args) { TerrainToolShortcutContext context = (TerrainToolShortcutContext)args.context; context.SelectPaintToolWithOverlays<PaintHeightTool>(); } class Styles { public readonly GUIContent description = EditorGUIUtility.TrTextContent("Left click to raise.\n\nHold shift and left click to lower."); } private static Styles m_styles; private Styles GetStyles() { if (m_styles == null) { m_styles = new Styles(); } return m_styles; } public override int IconIndex { get { return (int) SculptIndex.PaintHeight; } } public override TerrainCategory Category { get { return TerrainCategory.Sculpt; } } public override bool HasBrushMask => true; public override bool HasBrushAttributes => true; public override string GetName() { return k_ToolName; } public override string GetDescription() { return GetStyles().description.text; } public override void OnInspectorGUI(Terrain terrain, IOnInspectorGUI editContext) { int textureRez = terrain.terrainData.heightmapResolution; editContext.ShowBrushesGUI(5, BrushGUIEditFlags.All, textureRez); } private void ApplyBrushInternal(PaintContext paintContext, float brushStrength, Texture brushTexture, BrushTransform brushXform) { Material mat = TerrainPaintUtility.GetBuiltinPaintMaterial(); brushStrength = Event.current.shift ? -brushStrength : brushStrength; Vector4 brushParams = new Vector4(0.01f * brushStrength, 0.0f, 0.0f, 0.0f); mat.SetTexture("_BrushTex", brushTexture); mat.SetVector("_BrushParams", brushParams); TerrainPaintUtility.SetupTerrainToolMaterialProperties(paintContext, brushXform, mat); Graphics.Blit(paintContext.sourceRenderTexture, paintContext.destinationRenderTexture, mat, (int)TerrainBuiltinPaintMaterialPasses.RaiseLowerHeight); } public override void OnRenderBrushPreview(Terrain terrain, IOnSceneGUI editContext) { // We're only doing painting operations, early out if it's not a repaint if (Event.current.type != EventType.Repaint) return; if (editContext.hitValidTerrain) { BrushTransform brushXform = TerrainPaintUtility.CalculateBrushTransform(terrain, editContext.raycastHit.textureCoord, editContext.brushSize, 0.0f); PaintContext paintContext = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushXform.GetBrushXYBounds(), 1); Material material = TerrainPaintUtilityEditor.GetDefaultBrushPreviewMaterial(); TerrainPaintUtilityEditor.DrawBrushPreview( paintContext, TerrainBrushPreviewMode.SourceRenderTexture, editContext.brushTexture, brushXform, material, 0); // draw result preview { ApplyBrushInternal(paintContext, editContext.brushStrength, editContext.brushTexture, brushXform); // restore old render target RenderTexture.active = paintContext.oldRenderTexture; material.SetTexture("_HeightmapOrig", paintContext.sourceRenderTexture); TerrainPaintUtilityEditor.DrawBrushPreview( paintContext, TerrainBrushPreviewMode.DestinationRenderTexture, editContext.brushTexture, brushXform, material, 1); } TerrainPaintUtility.ReleaseContextResources(paintContext); } } public override bool OnPaint(Terrain terrain, IOnPaint editContext) { BrushTransform brushXform = TerrainPaintUtility.CalculateBrushTransform(terrain, editContext.uv, editContext.brushSize, 0.0f); PaintContext paintContext = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushXform.GetBrushXYBounds()); ApplyBrushInternal(paintContext, editContext.brushStrength, editContext.brushTexture, brushXform); TerrainPaintUtility.EndPaintHeightmap(paintContext, "Terrain Paint - Raise or Lower Height"); return true; } } }
UnityCsReference/Modules/TerrainEditor/PaintTools/PaintHeightTool.cs/0
{ "file_path": "UnityCsReference/Modules/TerrainEditor/PaintTools/PaintHeightTool.cs", "repo_id": "UnityCsReference", "token_count": 2164 }
471
// Unity 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.TerrainTools; using UnityEngine.Scripting.APIUpdating; namespace UnityEditor.TerrainTools { public enum TerrainBrushPreviewMode { SourceRenderTexture, DestinationRenderTexture } [MovedFrom("UnityEditor.Experimental.TerrainAPI")] public static class TerrainPaintUtilityEditor { // This maintains the list of terrains we have touched in the current operation (and the current operation identifier, as an undo group) // We track this to have good cross-tile undo support: each modified tile should be added, at most, ONCE within a single operation private static int s_CurrentOperationUndoGroup = -1; private static Dictionary<UnityEngine.Object, int> s_CurrentOperationUndoStack = new Dictionary<UnityEngine.Object, int>(); static TerrainPaintUtilityEditor() { PaintContext.onTerrainTileBeforePaint += (tile, action, editorUndoName) => { // if we are in a new undo group (new operation) then start with an empty list if (Undo.GetCurrentGroup() != s_CurrentOperationUndoGroup) { s_CurrentOperationUndoGroup = Undo.GetCurrentGroup(); s_CurrentOperationUndoStack.Clear(); } if (string.IsNullOrEmpty(editorUndoName)) return; int recordedActions = 0; if (!s_CurrentOperationUndoStack.TryGetValue(tile.terrain, out recordedActions)) { recordedActions = 0; } // since action is a bitfield, this calculates all of the actions that aren't yet recorded int newActions = ((int)action) & ~recordedActions; if (newActions != 0) { var undoObjects = new List<UnityEngine.Object>(); // texture splats are serialized separately if (0 != (newActions & (int)PaintContext.ToolAction.PaintTexture)) { undoObjects.AddRange(tile.terrain.terrainData.alphamapTextures); recordedActions |= (int)PaintContext.ToolAction.PaintTexture; } // both PaintHeightmap and PaintHoles are serialized into the main terrainData object, // if either is flagged, record both int kPaintHeightmapOrHoles = (int)(PaintContext.ToolAction.PaintHeightmap | PaintContext.ToolAction.PaintHoles | PaintContext.ToolAction.AddTerrainLayer); if (0 != (newActions & kPaintHeightmapOrHoles)) { undoObjects.Add(tile.terrain.terrainData); recordedActions |= kPaintHeightmapOrHoles; // mark that we recorded both } if (undoObjects.Count > 0) { Undo.RegisterCompleteObjectUndo(undoObjects.ToArray(), editorUndoName); s_CurrentOperationUndoStack[tile.terrain] = recordedActions; } } }; } public static void UpdateTerrainDataUndo(TerrainData terrainData, string undoName) { // if we are in a new undo group (new operation) then start with an empty list if (Undo.GetCurrentGroup() != s_CurrentOperationUndoGroup) { s_CurrentOperationUndoGroup = Undo.GetCurrentGroup(); s_CurrentOperationUndoStack.Clear(); } if (!s_CurrentOperationUndoStack.ContainsKey(terrainData)) { s_CurrentOperationUndoStack.Add(terrainData, 0); Undo.RegisterCompleteObjectUndo(terrainData, undoName); } } public static void ShowDefaultPreviewBrush(Terrain terrain, Texture brushTexture, float brushSize) { Ray mouseRay = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); RaycastHit hit; if (terrain.GetComponent<Collider>().Raycast(mouseRay, out hit, Mathf.Infinity)) { BrushTransform brushXform = TerrainPaintUtility.CalculateBrushTransform(terrain, hit.textureCoord, brushSize, 0.0f); PaintContext ctx = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushXform.GetBrushXYBounds(), 1); DrawBrushPreview(ctx, TerrainBrushPreviewMode.SourceRenderTexture, brushTexture, brushXform, GetDefaultBrushPreviewMaterial(), 0); TerrainPaintUtility.ReleaseContextResources(ctx); } } public static Material GetDefaultBrushPreviewMaterial() { if (m_BrushPreviewMaterial == null) m_BrushPreviewMaterial = new Material(Shader.Find("Hidden/TerrainEngine/BrushPreview")); return m_BrushPreviewMaterial; } public static void DrawBrushPreview( PaintContext heightmapPC, TerrainBrushPreviewMode previewTexture, Texture brushTexture, // brush texture to apply BrushTransform brushXform, // brush transform that defines the brush UV space Material proceduralMaterial, // the material to render with (must support procedural quad-mesh generation) int materialPassIndex) // the pass to use within the material { // we want to build a quad mesh, with one vertex for each pixel in the heightmap // i.e. a 3x3 heightmap would create a mesh that looks like this: // // +-+-+ // |\|\| // +-+-+ // |\|\| // +-+-+ // int quadsX = heightmapPC.pixelRect.width - 1; int quadsY = heightmapPC.pixelRect.height - 1; int vertexCount = quadsX * quadsY * (2 * 3); // two triangles (2 * 3 vertices) per quad // issue: the 'int vertexID' in the shader is often stored in an fp32 // which can only represent exact integers up to 16777216 ~== 6 * 1672^2 // once we have more than 16777216 vertices, the vertexIDs start skipping odd values, resulting in missing triangles // the solution is to reduce vertex count by halving our mesh resolution before we hit that point const int kMaxFP32Int = 16777216; int vertSkip = 1; while (vertexCount > kMaxFP32Int / 2) // in practice we want to stay well below 16 million verts, for perf sanity { quadsX = (quadsX + 1) / 2; quadsY = (quadsY + 1) / 2; vertexCount = quadsX * quadsY * (2 * 3); vertSkip *= 2; } // this is used to tessellate the quad mesh (from within the vertex shader) proceduralMaterial.SetVector("_QuadRez", new Vector4(quadsX, quadsY, vertexCount, vertSkip)); // paint context pixels to heightmap uv: uv = (pixels + 0.5) / width Texture heightmapTexture = (previewTexture == TerrainBrushPreviewMode.SourceRenderTexture) ? heightmapPC.sourceRenderTexture : heightmapPC.destinationRenderTexture; float invWidth = 1.0f / heightmapTexture.width; float invHeight = 1.0f / heightmapTexture.height; proceduralMaterial.SetVector("_HeightmapUV_PCPixelsX", new Vector4(invWidth, 0.0f, 0.0f, 0.0f)); proceduralMaterial.SetVector("_HeightmapUV_PCPixelsY", new Vector4(0.0f, invHeight, 0.0f, 0.0f)); proceduralMaterial.SetVector("_HeightmapUV_Offset", new Vector4(0.5f * invWidth, 0.5f * invHeight, 0.0f, 0.0f)); // make sure we point filter the heightmap FilterMode oldFilter = heightmapTexture.filterMode; heightmapTexture.filterMode = FilterMode.Point; proceduralMaterial.SetTexture("_Heightmap", heightmapTexture); // paint context pixels to object (terrain) position // objectPos.x = scaleX * pcPixels.x + heightmapRect.xMin * scaleX // objectPos.y = scaleY * H // objectPos.z = scaleZ * pcPixels.y + heightmapRect.yMin * scaleZ float scaleX = heightmapPC.pixelSize.x; float scaleY = heightmapPC.heightWorldSpaceSize / PaintContext.kNormalizedHeightScale; float scaleZ = heightmapPC.pixelSize.y; proceduralMaterial.SetVector("_ObjectPos_PCPixelsX", new Vector4(scaleX, 0.0f, 0.0f, 0.0f)); proceduralMaterial.SetVector("_ObjectPos_HeightMapSample", new Vector4(0.0f, scaleY, 0.0f, 0.0f)); proceduralMaterial.SetVector("_ObjectPos_PCPixelsY", new Vector4(0.0f, 0.0f, scaleZ, 0.0f)); proceduralMaterial.SetVector("_ObjectPos_Offset", new Vector4(heightmapPC.pixelRect.xMin * scaleX, heightmapPC.heightWorldSpaceMin - heightmapPC.originTerrain.GetPosition().y, heightmapPC.pixelRect.yMin * scaleZ, 1.0f)); // heightmap paint context pixels to brush UV // derivation: // BrushUV = f(terrainSpace.xz) = f(g(pcPixels.xy)) // f(ts.xy) = ts.x * brushXform.X + ts.y * brushXform.Y + brushXform.Origin // g(pcPixels.xy) = ts.xz = pcOrigin + pcPixels.xy * pcSize // f(g(pcPixels.uv)) == (pcOrigin + pcPixels.uv * pcSize).x * brushXform.X + (pcOrigin + pcPixels.uv * pcSize).y * brushXform.Y + brushXform.Origin // f(g(pcPixels.uv)) == (pcOrigin.x + pcPixels.u * pcSize.x) * brushXform.X + (pcOrigin.y + pcPixels.v * pcSize.y) * brushXform.Y + brushXform.Origin // f(g(pcPixels.uv)) == (pcOrigin.x * brushXform.X) + (pcPixels.u * pcSize.x) * brushXform.X + (pcOrigin.y * brushXform.Y) + (pcPixels.v * pcSize.y) * brushXform.Y + brushXform.Origin // f(g(pcPixels.uv)) == pcPixels.u * (pcSize.x * brushXform.X) + pcPixels.v * (pcSize.y * brushXform.Y) + (brushXform.Origin + (pcOrigin.x * brushXform.X) + (pcOrigin.y * brushXform.Y)) // paint context origin in terrain space // (note this is the UV space origin and size, not the mesh origin & size) float pcOriginX = heightmapPC.pixelRect.xMin * heightmapPC.pixelSize.x; float pcOriginZ = heightmapPC.pixelRect.yMin * heightmapPC.pixelSize.y; float pcSizeX = heightmapPC.pixelSize.x; float pcSizeZ = heightmapPC.pixelSize.y; Vector2 scaleU = pcSizeX * brushXform.targetX; Vector2 scaleV = pcSizeZ * brushXform.targetY; Vector2 offset = brushXform.targetOrigin + pcOriginX * brushXform.targetX + pcOriginZ * brushXform.targetY; proceduralMaterial.SetVector("_BrushUV_PCPixelsX", new Vector4(scaleU.x, scaleU.y, 0.0f, 0.0f)); proceduralMaterial.SetVector("_BrushUV_PCPixelsY", new Vector4(scaleV.x, scaleV.y, 0.0f, 0.0f)); proceduralMaterial.SetVector("_BrushUV_Offset", new Vector4(offset.x, offset.y, 0.0f, 1.0f)); proceduralMaterial.SetTexture("_BrushTex", brushTexture); Vector3 terrainPos = heightmapPC.originTerrain.GetPosition(); proceduralMaterial.SetVector("_TerrainObjectToWorldOffset", terrainPos); proceduralMaterial.SetPass(materialPassIndex); Graphics.DrawProceduralNow(MeshTopology.Triangles, vertexCount); heightmapTexture.filterMode = oldFilter; } static Material m_BrushPreviewMaterial = null; } }
UnityCsReference/Modules/TerrainEditor/Utilities/TerrainPaintUtilityEditor.cs/0
{ "file_path": "UnityCsReference/Modules/TerrainEditor/Utilities/TerrainPaintUtilityEditor.cs", "repo_id": "UnityCsReference", "token_count": 5290 }
472
// 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.TextCore.Text { /// <summary> /// Enumeration of currently supported OpenType Layout features. /// </summary> public enum OTL_FeatureTag : uint { kern = 'k' << 24 | 'e' << 16 | 'r' << 8 | 'n', liga = 'l' << 24 | 'i' << 16 | 'g' << 8 | 'a', mark = 'm' << 24 | 'a' << 16 | 'r' << 8 | 'k', mkmk = 'm' << 24 | 'k' << 16 | 'm' << 8 | 'k', } }
UnityCsReference/Modules/TextCoreTextEngine/Managed/FontFeatureCommon.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreTextEngine/Managed/FontFeatureCommon.cs", "repo_id": "UnityCsReference", "token_count": 247 }
473
// 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.Scripting.APIUpdating; using UnityEngine.Serialization; namespace UnityEngine.TextCore.Text { [HelpURL("https://docs.unity3d.com/2023.3/Documentation/Manual/UIE-sprite.html")] [ExcludeFromPresetAttribute] public class SpriteAsset : TextAsset { internal Dictionary<int, int> m_NameLookup; internal Dictionary<uint, int> m_GlyphIndexLookup; /// <summary> /// Information about the sprite asset's face. /// </summary> public FaceInfo faceInfo { get { return m_FaceInfo; } internal set { m_FaceInfo = value; } } [SerializeField] internal FaceInfo m_FaceInfo; /// <summary> /// The texture containing the sprites referenced by this sprite asset. /// </summary> public Texture spriteSheet { get { return m_SpriteAtlasTexture; } internal set { m_SpriteAtlasTexture = value; width = m_SpriteAtlasTexture.width; height = m_SpriteAtlasTexture.height; } } [FormerlySerializedAs("spriteSheet")][SerializeField] internal Texture m_SpriteAtlasTexture; internal float width { get; private set; } internal float height { get; private set; } /// <summary> /// List containing the sprite characters. /// </summary> public List<SpriteCharacter> spriteCharacterTable { get { if (m_GlyphIndexLookup == null) UpdateLookupTables(); return m_SpriteCharacterTable; } internal set { m_SpriteCharacterTable = value; } } [SerializeField] private List<SpriteCharacter> m_SpriteCharacterTable = new List<SpriteCharacter>(); /// <summary> /// Dictionary used to lookup sprite characters by their unicode value. /// </summary> public Dictionary<uint, SpriteCharacter> spriteCharacterLookupTable { get { if (m_SpriteCharacterLookup == null) UpdateLookupTables(); return m_SpriteCharacterLookup; } internal set { m_SpriteCharacterLookup = value; } } internal Dictionary<uint, SpriteCharacter> m_SpriteCharacterLookup; public List<SpriteGlyph> spriteGlyphTable { get { return m_SpriteGlyphTable; } internal set { m_SpriteGlyphTable = value; } } [SerializeField] private List<SpriteGlyph> m_SpriteGlyphTable = new List<SpriteGlyph>(); internal Dictionary<uint, SpriteGlyph> m_SpriteGlyphLookup; /// <summary> /// List which contains the Fallback font assets for this font. /// </summary> [SerializeField] public List<SpriteAsset> fallbackSpriteAssets; internal bool m_IsSpriteAssetLookupTablesDirty = false; void Awake() {} /// <summary> /// Create a material for the sprite asset. /// </summary> /// <returns></returns> /*Material GetDefaultSpriteMaterial() { //isEditingAsset = true; TextShaderUtilities.GetShaderPropertyIDs(); // Add a new material Shader shader = Shader.Find("TextMeshPro/Sprite"); Material tempMaterial = new Material(shader); tempMaterial.SetTexture(TextShaderUtilities.ID_MainTex, spriteSheet); tempMaterial.hideFlags = HideFlags.HideInHierarchy; #if UNITY_EDITOR UnityEditor.AssetDatabase.AddObjectToAsset(tempMaterial, this); UnityEditor.AssetDatabase.ImportAsset(UnityEditor.AssetDatabase.GetAssetPath(this)); #endif //isEditingAsset = false; return tempMaterial; }*/ /// <summary> /// Function to update the sprite name and unicode lookup tables. /// This function should be called when a sprite's name or unicode value changes or when a new sprite is added. /// </summary> public void UpdateLookupTables() { width = m_SpriteAtlasTexture.width; height = m_SpriteAtlasTexture.height; //Debug.Log("Updating [" + this.name + "] Lookup tables."); // Initialize / Clear glyph index lookup dictionary. if (m_GlyphIndexLookup == null) m_GlyphIndexLookup = new Dictionary<uint, int>(); else m_GlyphIndexLookup.Clear(); // if (m_SpriteGlyphLookup == null) m_SpriteGlyphLookup = new Dictionary<uint, SpriteGlyph>(); else m_SpriteGlyphLookup.Clear(); // Initialize SpriteGlyphLookup for (int i = 0; i < m_SpriteGlyphTable.Count; i++) { SpriteGlyph spriteGlyph = m_SpriteGlyphTable[i]; uint glyphIndex = spriteGlyph.index; if (m_GlyphIndexLookup.ContainsKey(glyphIndex) == false) m_GlyphIndexLookup.Add(glyphIndex, i); if (m_SpriteGlyphLookup.ContainsKey(glyphIndex) == false) m_SpriteGlyphLookup.Add(glyphIndex, spriteGlyph); } // Initialize name lookup if (m_NameLookup == null) m_NameLookup = new Dictionary<int, int>(); else m_NameLookup.Clear(); // Initialize character lookup if (m_SpriteCharacterLookup == null) m_SpriteCharacterLookup = new Dictionary<uint, SpriteCharacter>(); else m_SpriteCharacterLookup.Clear(); // Populate Sprite Character lookup tables for (int i = 0; i < m_SpriteCharacterTable.Count; i++) { SpriteCharacter spriteCharacter = m_SpriteCharacterTable[i]; // Make sure sprite character is valid if (spriteCharacter == null) continue; uint glyphIndex = spriteCharacter.glyphIndex; // Lookup the glyph for this character if (m_SpriteGlyphLookup.ContainsKey(glyphIndex) == false) continue; // Assign glyph and text asset to this character spriteCharacter.glyph = m_SpriteGlyphLookup[glyphIndex]; spriteCharacter.textAsset = this; int nameHashCode = TextUtilities.GetHashCodeCaseInSensitive(m_SpriteCharacterTable[i].name); if (m_NameLookup.ContainsKey(nameHashCode) == false) m_NameLookup.Add(nameHashCode, i); uint unicode = m_SpriteCharacterTable[i].unicode; if (unicode != 0xFFFE && m_SpriteCharacterLookup.ContainsKey(unicode) == false) m_SpriteCharacterLookup.Add(unicode, spriteCharacter); } m_IsSpriteAssetLookupTablesDirty = false; } /// <summary> /// Function which returns the sprite index using the hashcode of the name /// </summary> /// <param name="hashCode"></param> /// <returns></returns> public int GetSpriteIndexFromHashcode(int hashCode) { if (m_NameLookup == null) UpdateLookupTables(); int index; if (m_NameLookup.TryGetValue(hashCode, out index)) return index; return -1; } /// <summary> /// Returns the index of the sprite for the given unicode value. /// </summary> /// <param name="unicode"></param> /// <returns></returns> public int GetSpriteIndexFromUnicode(uint unicode) { if (m_SpriteCharacterLookup == null) UpdateLookupTables(); SpriteCharacter spriteCharacter; if (m_SpriteCharacterLookup.TryGetValue(unicode, out spriteCharacter)) return (int)spriteCharacter.glyphIndex; return -1; } /// <summary> /// Returns the index of the sprite for the given name. /// </summary> /// <param name="name"></param> /// <returns></returns> public int GetSpriteIndexFromName(string name) { if (m_NameLookup == null) UpdateLookupTables(); int hashCode = TextUtilities.GetHashCodeCaseInSensitive(name); return GetSpriteIndexFromHashcode(hashCode); } /// <summary> /// Used to keep track of which Sprite Assets have been searched. /// </summary> private static HashSet<int> k_searchedSpriteAssets; /// <summary> /// Search through the given sprite asset and its fallbacks for the specified sprite matching the given unicode character. /// </summary> /// <param name="spriteAsset">The sprite asset asset to search for the given unicode.</param> /// <param name="unicode">The unicode character to find.</param> /// <param name="includeFallbacks">Include fallback sprite assets in the search?</param> /// <param name="spriteIndex">The index of the sprite in the sprite asset (if found)</param> /// <returns></returns> public static SpriteAsset SearchForSpriteByUnicode(SpriteAsset spriteAsset, uint unicode, bool includeFallbacks, out int spriteIndex) { // Check to make sure sprite asset is not null if (spriteAsset == null) { spriteIndex = -1; return null; } // Get sprite index for the given unicode spriteIndex = spriteAsset.GetSpriteIndexFromUnicode(unicode); if (spriteIndex != -1) return spriteAsset; // Initialize list to track instance of Sprite Assets that have already been searched. if (k_searchedSpriteAssets == null) k_searchedSpriteAssets = new HashSet<int>(); else k_searchedSpriteAssets.Clear(); // Get instance ID of sprite asset and add to list. int id = spriteAsset.GetInstanceID(); k_searchedSpriteAssets.Add(id); // Search potential fallback sprite assets if includeFallbacks is true. if (includeFallbacks && spriteAsset.fallbackSpriteAssets != null && spriteAsset.fallbackSpriteAssets.Count > 0) return SearchForSpriteByUnicodeInternal(spriteAsset.fallbackSpriteAssets, unicode, true, out spriteIndex); // Search default sprite asset potentially assigned in the TMP Settings. //if (includeFallbacks && TMP_Settings.defaultSpriteAsset != null) // return SearchForSpriteByUnicodeInternal(TMP_Settings.defaultSpriteAsset, unicode, true, out spriteIndex); spriteIndex = -1; return null; } /// <summary> /// Search through the given list of sprite assets and fallbacks for a sprite whose unicode value matches the target unicode. /// </summary> /// <param name="spriteAssets"></param> /// <param name="unicode"></param> /// <param name="includeFallbacks"></param> /// <param name="spriteIndex"></param> /// <returns></returns> private static SpriteAsset SearchForSpriteByUnicodeInternal(List<SpriteAsset> spriteAssets, uint unicode, bool includeFallbacks, out int spriteIndex) { for (int i = 0; i < spriteAssets.Count; i++) { SpriteAsset temp = spriteAssets[i]; if (temp == null) continue; int id = temp.GetInstanceID(); // Skip sprite asset if it has already been searched. if (k_searchedSpriteAssets.Add(id) == false) continue; temp = SearchForSpriteByUnicodeInternal(temp, unicode, includeFallbacks, out spriteIndex); if (temp != null) return temp; } spriteIndex = -1; return null; } /// <summary> /// Search the given sprite asset and fallbacks for a sprite whose unicode value matches the target unicode. /// </summary> /// <param name="spriteAsset"></param> /// <param name="unicode"></param> /// <param name="includeFallbacks"></param> /// <param name="spriteIndex"></param> /// <returns></returns> private static SpriteAsset SearchForSpriteByUnicodeInternal(SpriteAsset spriteAsset, uint unicode, bool includeFallbacks, out int spriteIndex) { // Get sprite index for the given unicode spriteIndex = spriteAsset.GetSpriteIndexFromUnicode(unicode); if (spriteIndex != -1) return spriteAsset; if (includeFallbacks && spriteAsset.fallbackSpriteAssets != null && spriteAsset.fallbackSpriteAssets.Count > 0) return SearchForSpriteByUnicodeInternal(spriteAsset.fallbackSpriteAssets, unicode, true, out spriteIndex); spriteIndex = -1; return null; } /// <summary> /// Search the given sprite asset and fallbacks for a sprite whose hash code value of its name matches the target hash code. /// </summary> /// <param name="spriteAsset">The Sprite Asset to search for the given sprite whose name matches the hashcode value</param> /// <param name="hashCode">The hash code value matching the name of the sprite</param> /// <param name="includeFallbacks">Include fallback sprite assets in the search</param> /// <param name="spriteIndex">The index of the sprite matching the provided hash code</param> /// <returns>The Sprite Asset that contains the sprite</returns> public static SpriteAsset SearchForSpriteByHashCode(SpriteAsset spriteAsset, int hashCode, bool includeFallbacks, out int spriteIndex, TextSettings textSettings = null) { // Make sure sprite asset is not null if (spriteAsset == null) { spriteIndex = -1; return null; } spriteIndex = spriteAsset.GetSpriteIndexFromHashcode(hashCode); if (spriteIndex != -1) return spriteAsset; // Initialize or clear list to Sprite Assets that have already been searched. if (k_searchedSpriteAssets == null) k_searchedSpriteAssets = new HashSet<int>(); else k_searchedSpriteAssets.Clear(); int id = spriteAsset.GetHashCode(); // Add to list of font assets already searched. k_searchedSpriteAssets.Add(id); SpriteAsset tempSpriteAsset; // Search potential local fallbacks assigned to the sprite asset. if (includeFallbacks && spriteAsset.fallbackSpriteAssets != null && spriteAsset.fallbackSpriteAssets.Count > 0) { tempSpriteAsset = SearchForSpriteByHashCodeInternal(spriteAsset.fallbackSpriteAssets, hashCode, true, out spriteIndex); if (spriteIndex != -1) return tempSpriteAsset; } // Early exist if text settings is null if (textSettings == null) { spriteIndex = -1; return null; } // Search default sprite asset potentially assigned in the Text Settings. if (includeFallbacks && textSettings.defaultSpriteAsset != null) { tempSpriteAsset = SearchForSpriteByHashCodeInternal(textSettings.defaultSpriteAsset, hashCode, true, out spriteIndex); if (spriteIndex != -1) return tempSpriteAsset; } // Clear search list since we are now looking for the missing sprite character. k_searchedSpriteAssets.Clear(); uint missingSpriteCharacterUnicode = textSettings.missingSpriteCharacterUnicode; // Get sprite index for the given unicode spriteIndex = spriteAsset.GetSpriteIndexFromUnicode(missingSpriteCharacterUnicode); if (spriteIndex != -1) return spriteAsset; // Add current sprite asset to list of assets already searched. k_searchedSpriteAssets.Add(id); // Search for the missing sprite character in the local sprite asset and potential fallbacks. if (includeFallbacks && spriteAsset.fallbackSpriteAssets != null && spriteAsset.fallbackSpriteAssets.Count > 0) { tempSpriteAsset = SearchForSpriteByUnicodeInternal(spriteAsset.fallbackSpriteAssets, missingSpriteCharacterUnicode, true, out spriteIndex); if (spriteIndex != -1) return tempSpriteAsset; } // Search for the missing sprite character in the default sprite asset and potential fallbacks. if (includeFallbacks && textSettings.defaultSpriteAsset != null) { tempSpriteAsset = SearchForSpriteByUnicodeInternal(textSettings.defaultSpriteAsset, missingSpriteCharacterUnicode, true, out spriteIndex); if (spriteIndex != -1) return tempSpriteAsset; } spriteIndex = -1; return null; } /// <summary> /// Search through the given list of sprite assets and fallbacks for a sprite whose hash code value of its name matches the target hash code. /// </summary> /// <param name="spriteAssets"></param> /// <param name="hashCode"></param> /// <param name="searchFallbacks"></param> /// <param name="spriteIndex"></param> /// <returns></returns> private static SpriteAsset SearchForSpriteByHashCodeInternal(List<SpriteAsset> spriteAssets, int hashCode, bool searchFallbacks, out int spriteIndex) { // Search through the list of sprite assets for (int i = 0; i < spriteAssets.Count; i++) { SpriteAsset temp = spriteAssets[i]; if (temp == null) continue; int id = temp.GetHashCode(); // Skip sprite asset if it has already been searched. if (k_searchedSpriteAssets.Add(id) == false) continue; temp = SearchForSpriteByHashCodeInternal(temp, hashCode, searchFallbacks, out spriteIndex); if (temp != null) return temp; } spriteIndex = -1; return null; } /// <summary> /// Search through the given sprite asset and fallbacks for a sprite whose hash code value of its name matches the target hash code. /// </summary> /// <param name="spriteAsset"></param> /// <param name="hashCode"></param> /// <param name="searchFallbacks"></param> /// <param name="spriteIndex"></param> /// <returns></returns> private static SpriteAsset SearchForSpriteByHashCodeInternal(SpriteAsset spriteAsset, int hashCode, bool searchFallbacks, out int spriteIndex) { // Get the sprite for the given hash code. spriteIndex = spriteAsset.GetSpriteIndexFromHashcode(hashCode); if (spriteIndex != -1) return spriteAsset; if (searchFallbacks && spriteAsset.fallbackSpriteAssets != null && spriteAsset.fallbackSpriteAssets.Count > 0) return SearchForSpriteByHashCodeInternal(spriteAsset.fallbackSpriteAssets, hashCode, true, out spriteIndex); spriteIndex = -1; return null; } /// <summary> /// Sort the sprite glyph table by glyph index. /// </summary> public void SortGlyphTable() { if (m_SpriteGlyphTable == null || m_SpriteGlyphTable.Count == 0) return; m_SpriteGlyphTable = m_SpriteGlyphTable.OrderBy(item => item.index).ToList(); } /// <summary> /// Sort the sprite character table by Unicode values. /// </summary> internal void SortCharacterTable() { if (m_SpriteCharacterTable != null && m_SpriteCharacterTable.Count > 0) m_SpriteCharacterTable = m_SpriteCharacterTable.OrderBy(c => c.unicode).ToList(); } /// <summary> /// Sort both sprite glyph and character tables. /// </summary> internal void SortGlyphAndCharacterTables() { SortGlyphTable(); SortCharacterTable(); } } }
UnityCsReference/Modules/TextCoreTextEngine/Managed/TextAssets/SpriteAsset.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreTextEngine/Managed/TextAssets/SpriteAsset.cs", "repo_id": "UnityCsReference", "token_count": 9178 }
474
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using Unity.Jobs.LowLevel.Unsafe; namespace UnityEngine.TextCore.Text { internal partial class TextGenerator { /// <summary> /// Function to identify and validate the rich tag. Returns the position of the > if the tag was valid. /// </summary> /// <param name="chars"></param> /// <param name="startIndex"></param> /// <param name="endIndex"></param> /// <returns></returns> bool ValidateHtmlTag(TextProcessingElement[] chars, int startIndex, out int endIndex, TextGenerationSettings generationSettings, TextInfo textInfo, out bool isThreadSuccess) { bool canWriteOnAsset = !IsExecutingJob; isThreadSuccess = true; TextSettings textSettings = generationSettings.textSettings; int tagCharCount = 0; byte attributeFlag = 0; int attributeIndex = 0; ClearMarkupTagAttributes(); TagValueType tagValueType = TagValueType.None; TagUnitType tagUnitType = TagUnitType.Pixels; endIndex = startIndex; bool isTagSet = false; bool isValidHtmlTag = false; bool startedWithQuotes = false; bool startedWithDoubleQuotes = false; for (int i = startIndex; i < chars.Length && chars[i].unicode != 0 && tagCharCount < m_HtmlTag.Length && chars[i].unicode != '<'; i++) { uint unicode = chars[i].unicode; if (unicode == '>') // ASCII Code of End HTML tag '>' { isValidHtmlTag = true; endIndex = i; m_HtmlTag[tagCharCount] = (char)0; break; } m_HtmlTag[tagCharCount] = (char)unicode; tagCharCount += 1; if (attributeFlag == 1) { if (tagValueType == TagValueType.None) { // Check for attribute type if (unicode == '+' || unicode == '-' || unicode == '.' || (unicode >= '0' && unicode <= '9')) { tagUnitType = TagUnitType.Pixels; tagValueType = m_XmlAttribute[attributeIndex].valueType = TagValueType.NumericalValue; m_XmlAttribute[attributeIndex].valueStartIndex = tagCharCount - 1; m_XmlAttribute[attributeIndex].valueLength += 1; } else if (unicode == '#') { tagUnitType = TagUnitType.Pixels; tagValueType = m_XmlAttribute[attributeIndex].valueType = TagValueType.ColorValue; m_XmlAttribute[attributeIndex].valueStartIndex = tagCharCount - 1; m_XmlAttribute[attributeIndex].valueLength += 1; } else if (unicode == '\'') { tagUnitType = TagUnitType.Pixels; tagValueType = m_XmlAttribute[attributeIndex].valueType = TagValueType.StringValue; m_XmlAttribute[attributeIndex].valueStartIndex = tagCharCount; startedWithQuotes = true; } else if (unicode == '"') { tagUnitType = TagUnitType.Pixels; tagValueType = m_XmlAttribute[attributeIndex].valueType = TagValueType.StringValue; m_XmlAttribute[attributeIndex].valueStartIndex = tagCharCount; startedWithDoubleQuotes = true; } else { tagUnitType = TagUnitType.Pixels; tagValueType = m_XmlAttribute[attributeIndex].valueType = TagValueType.StringValue; m_XmlAttribute[attributeIndex].valueStartIndex = tagCharCount - 1; m_XmlAttribute[attributeIndex].valueHashCode = (m_XmlAttribute[attributeIndex].valueHashCode << 5) + m_XmlAttribute[attributeIndex].valueHashCode ^ TextGeneratorUtilities.ToUpperFast((char)unicode); m_XmlAttribute[attributeIndex].valueLength += 1; } } else { if (tagValueType == TagValueType.NumericalValue) { // Check for termination of numerical value. if (unicode == 'p' || unicode == 'e' || unicode == '%' || unicode == ' ') { attributeFlag = 2; tagValueType = TagValueType.None; switch (unicode) { case 'e': m_XmlAttribute[attributeIndex].unitType = tagUnitType = TagUnitType.FontUnits; break; case '%': m_XmlAttribute[attributeIndex].unitType = tagUnitType = TagUnitType.Percentage; break; default: m_XmlAttribute[attributeIndex].unitType = tagUnitType = TagUnitType.Pixels; break; } attributeIndex += 1; m_XmlAttribute[attributeIndex].nameHashCode = 0; m_XmlAttribute[attributeIndex].valueHashCode = 0; m_XmlAttribute[attributeIndex].valueType = TagValueType.None; m_XmlAttribute[attributeIndex].unitType = TagUnitType.Pixels; m_XmlAttribute[attributeIndex].valueStartIndex = 0; m_XmlAttribute[attributeIndex].valueLength = 0; } else { m_XmlAttribute[attributeIndex].valueLength += 1; } } else if (tagValueType == TagValueType.ColorValue) { if (unicode != ' ') { m_XmlAttribute[attributeIndex].valueLength += 1; } else { attributeFlag = 2; tagValueType = TagValueType.None; tagUnitType = TagUnitType.Pixels; attributeIndex += 1; m_XmlAttribute[attributeIndex].nameHashCode = 0; m_XmlAttribute[attributeIndex].valueType = TagValueType.None; m_XmlAttribute[attributeIndex].unitType = TagUnitType.Pixels; m_XmlAttribute[attributeIndex].valueHashCode = 0; m_XmlAttribute[attributeIndex].valueStartIndex = 0; m_XmlAttribute[attributeIndex].valueLength = 0; } } else if (tagValueType == TagValueType.StringValue) { // Compute HashCode value for the named tag. // startedWithQuotes/doubleQuotes is needed to make sure we don't exit the tag if a different type of quotes is used (UUM-59167) if (!(startedWithDoubleQuotes && unicode == '"') && !(startedWithQuotes && unicode == '\'')) { m_XmlAttribute[attributeIndex].valueHashCode = (m_XmlAttribute[attributeIndex].valueHashCode << 5) + m_XmlAttribute[attributeIndex].valueHashCode ^ TextGeneratorUtilities.ToUpperFast((char)unicode); m_XmlAttribute[attributeIndex].valueLength += 1; } else { attributeFlag = 2; tagValueType = TagValueType.None; tagUnitType = TagUnitType.Pixels; attributeIndex += 1; m_XmlAttribute[attributeIndex].nameHashCode = 0; m_XmlAttribute[attributeIndex].valueType = TagValueType.None; m_XmlAttribute[attributeIndex].unitType = TagUnitType.Pixels; m_XmlAttribute[attributeIndex].valueHashCode = 0; m_XmlAttribute[attributeIndex].valueStartIndex = 0; m_XmlAttribute[attributeIndex].valueLength = 0; } } } } if (unicode == '=') // '=' attributeFlag = 1; // Compute HashCode for the name of the attribute if (attributeFlag == 0 && unicode == ' ') { if (isTagSet) return false; isTagSet = true; attributeFlag = 2; tagValueType = TagValueType.None; tagUnitType = TagUnitType.Pixels; attributeIndex += 1; m_XmlAttribute[attributeIndex].nameHashCode = 0; m_XmlAttribute[attributeIndex].valueType = TagValueType.None; m_XmlAttribute[attributeIndex].unitType = TagUnitType.Pixels; m_XmlAttribute[attributeIndex].valueHashCode = 0; m_XmlAttribute[attributeIndex].valueStartIndex = 0; m_XmlAttribute[attributeIndex].valueLength = 0; } if (attributeFlag == 0) m_XmlAttribute[attributeIndex].nameHashCode = (m_XmlAttribute[attributeIndex].nameHashCode << 5) + m_XmlAttribute[attributeIndex].nameHashCode ^ TextGeneratorUtilities.ToUpperFast((char)unicode); if (attributeFlag == 2 && unicode == ' ') attributeFlag = 0; } if (!isValidHtmlTag) return false; #region Rich Text Tag Processing // Special handling of the no parsing tag </noparse> </NOPARSE> tag if (m_TagNoParsing && (m_XmlAttribute[0].nameHashCode != (int)MarkupTag.SLASH_NO_PARSE)) return false; if (m_XmlAttribute[0].nameHashCode == (int)MarkupTag.SLASH_NO_PARSE) { m_TagNoParsing = false; return true; } // Color <#FFF> 3 Hex values (short form) if (m_HtmlTag[0] == k_NumberSign && tagCharCount == 4) { m_HtmlColor = TextGeneratorUtilities.HexCharsToColor(m_HtmlTag, tagCharCount); m_ColorStack.Add(m_HtmlColor); return true; } // Color <#FFF7> 4 Hex values with alpha (short form) else if (m_HtmlTag[0] == k_NumberSign && tagCharCount == 5) { m_HtmlColor = TextGeneratorUtilities.HexCharsToColor(m_HtmlTag, tagCharCount); m_ColorStack.Add(m_HtmlColor); return true; } // Color <#FF00FF> else if (m_HtmlTag[0] == k_NumberSign && tagCharCount == 7) // if Tag begins with # and contains 7 characters. { m_HtmlColor = TextGeneratorUtilities.HexCharsToColor(m_HtmlTag, tagCharCount); m_ColorStack.Add(m_HtmlColor); return true; } // Color <#FF00FF00> with alpha else if (m_HtmlTag[0] == k_NumberSign && tagCharCount == k_Tab) // if Tag begins with # and contains 9 characters. { m_HtmlColor = TextGeneratorUtilities.HexCharsToColor(m_HtmlTag, tagCharCount); m_ColorStack.Add(m_HtmlColor); return true; } else { float value = 0; float fontScale; switch ((MarkupTag)m_XmlAttribute[0].nameHashCode) { case MarkupTag.BOLD: m_FontStyleInternal |= FontStyles.Bold; m_FontStyleStack.Add(FontStyles.Bold); m_FontWeightInternal = TextFontWeight.Bold; return true; case MarkupTag.SLASH_BOLD: if ((generationSettings.fontStyle & FontStyles.Bold) != FontStyles.Bold) { if (m_FontStyleStack.Remove(FontStyles.Bold) == 0) { m_FontStyleInternal &= ~FontStyles.Bold; m_FontWeightInternal = m_FontWeightStack.Peek(); } } return true; case MarkupTag.ITALIC: m_FontStyleInternal |= FontStyles.Italic; m_FontStyleStack.Add(FontStyles.Italic); if (m_XmlAttribute[1].nameHashCode == (int)MarkupTag.ANGLE) { m_ItalicAngle = (int)TextGeneratorUtilities.ConvertToFloat(m_HtmlTag, m_XmlAttribute[1].valueStartIndex, m_XmlAttribute[1].valueLength); // Make sure angle is within valid range. if (m_ItalicAngle < -180 || m_ItalicAngle > 180) return false; } else m_ItalicAngle = m_CurrentFontAsset.italicStyleSlant; m_ItalicAngleStack.Add(m_ItalicAngle); return true; case MarkupTag.SLASH_ITALIC: if ((generationSettings.fontStyle & FontStyles.Italic) != FontStyles.Italic) { m_ItalicAngle = m_ItalicAngleStack.Remove(); if (m_FontStyleStack.Remove(FontStyles.Italic) == 0) m_FontStyleInternal &= ~FontStyles.Italic; } return true; case MarkupTag.STRIKETHROUGH: m_FontStyleInternal |= FontStyles.Strikethrough; m_FontStyleStack.Add(FontStyles.Strikethrough); if (m_XmlAttribute[1].nameHashCode == (int)MarkupTag.COLOR) { m_StrikethroughColor = TextGeneratorUtilities.HexCharsToColor(m_HtmlTag, m_XmlAttribute[1].valueStartIndex, m_XmlAttribute[1].valueLength); m_StrikethroughColor.a = m_HtmlColor.a < m_StrikethroughColor.a ? (byte)(m_HtmlColor.a) : (byte)(m_StrikethroughColor.a); if (textInfo != null) textInfo.hasMultipleColors = true; } else m_StrikethroughColor = m_HtmlColor; m_StrikethroughColorStack.Add(m_StrikethroughColor); return true; case MarkupTag.SLASH_STRIKETHROUGH: if ((generationSettings.fontStyle & FontStyles.Strikethrough) != FontStyles.Strikethrough) { if (m_FontStyleStack.Remove(FontStyles.Strikethrough) == 0) m_FontStyleInternal &= ~FontStyles.Strikethrough; } m_StrikethroughColor = m_StrikethroughColorStack.Remove(); return true; case MarkupTag.UNDERLINE: m_FontStyleInternal |= FontStyles.Underline; m_FontStyleStack.Add(FontStyles.Underline); if (m_XmlAttribute[1].nameHashCode == (int)MarkupTag.COLOR) { m_UnderlineColor = TextGeneratorUtilities.HexCharsToColor(m_HtmlTag, m_XmlAttribute[1].valueStartIndex, m_XmlAttribute[1].valueLength); m_UnderlineColor.a = m_HtmlColor.a < m_UnderlineColor.a ? (m_HtmlColor.a) : (m_UnderlineColor.a); if (textInfo != null) textInfo.hasMultipleColors = true; } else m_UnderlineColor = m_HtmlColor; m_UnderlineColorStack.Add(m_UnderlineColor); return true; case MarkupTag.SLASH_UNDERLINE: if ((generationSettings.fontStyle & FontStyles.Underline) != FontStyles.Underline) { if (m_FontStyleStack.Remove(FontStyles.Underline) == 0) m_FontStyleInternal &= ~FontStyles.Underline; } m_UnderlineColor = m_UnderlineColorStack.Remove(); return true; case MarkupTag.MARK: m_FontStyleInternal |= FontStyles.Highlight; m_FontStyleStack.Add(FontStyles.Highlight); Color32 highlightColor = new Color32(255, 255, 0, 64); Offset highlightPadding = Offset.zero; // Handle Mark Tag and potential attributes for (int i = 0; i < m_XmlAttribute.Length && m_XmlAttribute[i].nameHashCode != 0; i++) { switch ((MarkupTag)m_XmlAttribute[i].nameHashCode) { // Mark tag case MarkupTag.MARK: if (m_XmlAttribute[i].valueType == TagValueType.ColorValue) highlightColor = TextGeneratorUtilities.HexCharsToColor(m_HtmlTag, m_XmlAttribute[0].valueStartIndex, m_XmlAttribute[0].valueLength); break; // Color attribute case MarkupTag.COLOR: highlightColor = TextGeneratorUtilities.HexCharsToColor(m_HtmlTag, m_XmlAttribute[i].valueStartIndex, m_XmlAttribute[i].valueLength); break; // Padding attribute case MarkupTag.PADDING: int paramCount = TextGeneratorUtilities.GetAttributeParameters(m_HtmlTag, m_XmlAttribute[i].valueStartIndex, m_XmlAttribute[i].valueLength, ref m_AttributeParameterValues); if (paramCount != 4) return false; highlightPadding = new Offset(m_AttributeParameterValues[0], m_AttributeParameterValues[1], m_AttributeParameterValues[2], m_AttributeParameterValues[3]); highlightPadding *= m_FontSize * 0.01f * (generationSettings.isOrthographic ? 1 : 0.1f); break; } } highlightColor.a = m_HtmlColor.a < highlightColor.a ? (byte)(m_HtmlColor.a) : (byte)(highlightColor.a); m_HighlightState = new HighlightState(highlightColor, highlightPadding); m_HighlightStateStack.Push(m_HighlightState); if (textInfo != null) textInfo.hasMultipleColors = true; return true; case MarkupTag.SLASH_MARK: if ((generationSettings.fontStyle & FontStyles.Highlight) != FontStyles.Highlight) { m_HighlightStateStack.Remove(); m_HighlightState = m_HighlightStateStack.current; if (m_FontStyleStack.Remove(FontStyles.Highlight) == 0) m_FontStyleInternal &= ~FontStyles.Highlight; } return true; case MarkupTag.SUBSCRIPT: m_FontScaleMultiplier *= m_CurrentFontAsset.faceInfo.subscriptSize > 0 ? m_CurrentFontAsset.faceInfo.subscriptSize : 1; m_BaselineOffsetStack.Push(m_BaselineOffset); fontScale = (m_CurrentFontSize / m_CurrentFontAsset.faceInfo.pointSize * m_CurrentFontAsset.faceInfo.scale * (generationSettings.isOrthographic ? 1 : 0.1f)); m_BaselineOffset += m_CurrentFontAsset.faceInfo.subscriptOffset * fontScale * m_FontScaleMultiplier; m_FontStyleStack.Add(FontStyles.Subscript); m_FontStyleInternal |= FontStyles.Subscript; return true; case MarkupTag.SLASH_SUBSCRIPT: if ((m_FontStyleInternal & FontStyles.Subscript) == FontStyles.Subscript) { if (m_FontScaleMultiplier < 1) { m_BaselineOffset = m_BaselineOffsetStack.Pop(); m_FontScaleMultiplier /= m_CurrentFontAsset.faceInfo.subscriptSize > 0 ? m_CurrentFontAsset.faceInfo.subscriptSize : 1; } if (m_FontStyleStack.Remove(FontStyles.Subscript) == 0) m_FontStyleInternal &= ~FontStyles.Subscript; } return true; case MarkupTag.SUPERSCRIPT: m_FontScaleMultiplier *= m_CurrentFontAsset.faceInfo.superscriptSize > 0 ? m_CurrentFontAsset.faceInfo.superscriptSize : 1; m_BaselineOffsetStack.Push(m_BaselineOffset); fontScale = (m_CurrentFontSize / m_CurrentFontAsset.faceInfo.pointSize * m_CurrentFontAsset.faceInfo.scale * (generationSettings.isOrthographic ? 1 : 0.1f)); m_BaselineOffset += m_CurrentFontAsset.faceInfo.superscriptOffset * fontScale * m_FontScaleMultiplier; m_FontStyleStack.Add(FontStyles.Superscript); m_FontStyleInternal |= FontStyles.Superscript; return true; case MarkupTag.SLASH_SUPERSCRIPT: if ((m_FontStyleInternal & FontStyles.Superscript) == FontStyles.Superscript) { if (m_FontScaleMultiplier < 1) { m_BaselineOffset = m_BaselineOffsetStack.Pop(); m_FontScaleMultiplier /= m_CurrentFontAsset.faceInfo.superscriptSize > 0 ? m_CurrentFontAsset.faceInfo.superscriptSize : 1; } if (m_FontStyleStack.Remove(FontStyles.Superscript) == 0) m_FontStyleInternal &= ~FontStyles.Superscript; } return true; case MarkupTag.FONT_WEIGHT: value = TextGeneratorUtilities.ConvertToFloat(m_HtmlTag, m_XmlAttribute[0].valueStartIndex, m_XmlAttribute[0].valueLength); // Reject tag if value is invalid. if (value == Int16.MinValue) return false; switch ((int)value) { case 100: m_FontWeightInternal = TextFontWeight.Thin; break; case 200: m_FontWeightInternal = TextFontWeight.ExtraLight; break; case 300: m_FontWeightInternal = TextFontWeight.Light; break; case 400: m_FontWeightInternal = TextFontWeight.Regular; break; case 500: m_FontWeightInternal = TextFontWeight.Medium; break; case 600: m_FontWeightInternal = TextFontWeight.SemiBold; break; case 700: m_FontWeightInternal = TextFontWeight.Bold; break; case 800: m_FontWeightInternal = TextFontWeight.Heavy; break; case 900: m_FontWeightInternal = TextFontWeight.Black; break; } m_FontWeightStack.Add(m_FontWeightInternal); return true; case MarkupTag.SLASH_FONT_WEIGHT: m_FontWeightStack.Remove(); if (m_FontStyleInternal == FontStyles.Bold) m_FontWeightInternal = TextFontWeight.Bold; else m_FontWeightInternal = m_FontWeightStack.Peek(); return true; case MarkupTag.POSITION: value = TextGeneratorUtilities.ConvertToFloat(m_HtmlTag, m_XmlAttribute[0].valueStartIndex, m_XmlAttribute[0].valueLength); // Reject tag if value is invalid. if (value == Int16.MinValue) return false; switch (tagUnitType) { case TagUnitType.Pixels: m_XAdvance = value * (generationSettings.isOrthographic ? 1.0f : 0.1f); //m_isIgnoringAlignment = true; return true; case TagUnitType.FontUnits: m_XAdvance = value * m_CurrentFontSize * (generationSettings.isOrthographic ? 1.0f : 0.1f); //m_isIgnoringAlignment = true; return true; case TagUnitType.Percentage: m_XAdvance = m_MarginWidth * value / 100; //m_isIgnoringAlignment = true; return true; } return false; case MarkupTag.SLASH_POSITION: m_IsIgnoringAlignment = false; return true; case MarkupTag.VERTICAL_OFFSET: value = TextGeneratorUtilities.ConvertToFloat(m_HtmlTag, m_XmlAttribute[0].valueStartIndex, m_XmlAttribute[0].valueLength); // Reject tag if value is invalid. if (value == Int16.MinValue) return false; switch (tagUnitType) { case TagUnitType.Pixels: m_BaselineOffset = value * (generationSettings.isOrthographic ? 1 : 0.1f); return true; case TagUnitType.FontUnits: m_BaselineOffset = value * (generationSettings.isOrthographic ? 1 : 0.1f) * m_CurrentFontSize; return true; case TagUnitType.Percentage: //m_BaselineOffset = m_MarginHeight * val / 100; return false; } return false; case MarkupTag.SLASH_VERTICAL_OFFSET: m_BaselineOffset = 0; return true; case MarkupTag.PAGE: // This tag only works when Overflow - Page mode is used. if (generationSettings.overflowMode == TextOverflowMode.Page) { m_XAdvance = 0 + m_TagLineIndent + m_TagIndent; m_LineOffset = 0; m_PageNumber += 1; m_IsNewPage = true; } return true; case MarkupTag.NO_BREAK: m_IsNonBreakingSpace = true; return true; case MarkupTag.SLASH_NO_BREAK: m_IsNonBreakingSpace = false; return true; case MarkupTag.SIZE: value = TextGeneratorUtilities.ConvertToFloat(m_HtmlTag, m_XmlAttribute[0].valueStartIndex, m_XmlAttribute[0].valueLength); // Reject tag if value is invalid. if (value == Int16.MinValue) return false; switch (tagUnitType) { case TagUnitType.Pixels: if (m_HtmlTag[5] == k_Plus) // <size=+00> { m_CurrentFontSize = m_FontSize + value; m_SizeStack.Add(m_CurrentFontSize); return true; } else if (m_HtmlTag[5] == k_HyphenMinus) // <size=-00> { m_CurrentFontSize = m_FontSize + value; m_SizeStack.Add(m_CurrentFontSize); return true; } else // <size=00.0> { m_CurrentFontSize = value; m_SizeStack.Add(m_CurrentFontSize); return true; } case TagUnitType.FontUnits: m_CurrentFontSize = m_FontSize * value; m_SizeStack.Add(m_CurrentFontSize); return true; case TagUnitType.Percentage: m_CurrentFontSize = m_FontSize * value / 100; m_SizeStack.Add(m_CurrentFontSize); return true; } return false; case MarkupTag.SLASH_SIZE: m_CurrentFontSize = m_SizeStack.Remove(); return true; case MarkupTag.FONT: int fontHashCode = m_XmlAttribute[0].valueHashCode; int materialAttributeHashCode = m_XmlAttribute[1].nameHashCode; int materialHashCode = m_XmlAttribute[1].valueHashCode; // Special handling for <font=default> or <font=Default> if (fontHashCode == (int)MarkupTag.DEFAULT) { m_CurrentFontAsset = m_MaterialReferences[0].fontAsset; m_CurrentMaterial = m_MaterialReferences[0].material; m_CurrentMaterialIndex = 0; m_MaterialReferenceStack.Add(m_MaterialReferences[0]); return true; } FontAsset tempFont; Material tempMaterial; // HANDLE NEW FONT ASSET // Check if we already have a reference to this font asset. MaterialReferenceManager.TryGetFontAsset(fontHashCode, out tempFont); // Try loading font asset from potential delegate or resources. if (tempFont == null) { if (tempFont == null) { if (!canWriteOnAsset) { isThreadSuccess = false; return false; } // Load Font Asset tempFont = Resources.Load<FontAsset>(textSettings.defaultFontAssetPath + new string(m_HtmlTag, m_XmlAttribute[0].valueStartIndex, m_XmlAttribute[0].valueLength)); } if (tempFont == null) return false; // Add new reference to the font asset as well as default material to the MaterialReferenceManager MaterialReferenceManager.AddFontAsset(tempFont); } // HANDLE NEW MATERIAL if (materialAttributeHashCode == 0 && materialHashCode == 0) { // No material specified then use default font asset material. m_CurrentMaterial = tempFont.material; m_CurrentMaterialIndex = MaterialReference.AddMaterialReference(m_CurrentMaterial, tempFont, ref m_MaterialReferences, m_MaterialReferenceIndexLookup); m_MaterialReferenceStack.Add(m_MaterialReferences[m_CurrentMaterialIndex]); } else if (materialAttributeHashCode == (int)MarkupTag.MATERIAL) // using material attribute { if (MaterialReferenceManager.TryGetMaterial(materialHashCode, out tempMaterial)) { m_CurrentMaterial = tempMaterial; m_CurrentMaterialIndex = MaterialReference.AddMaterialReference(m_CurrentMaterial, tempFont, ref m_MaterialReferences, m_MaterialReferenceIndexLookup); m_MaterialReferenceStack.Add(m_MaterialReferences[m_CurrentMaterialIndex]); } else { if (!canWriteOnAsset) { isThreadSuccess = false; return false; } // Load new material tempMaterial = Resources.Load<Material>(textSettings.defaultFontAssetPath + new string(m_HtmlTag, m_XmlAttribute[1].valueStartIndex, m_XmlAttribute[1].valueLength)); if (tempMaterial == null) return false; // Add new reference to this material in the MaterialReferenceManager MaterialReferenceManager.AddFontMaterial(materialHashCode, tempMaterial); m_CurrentMaterial = tempMaterial; m_CurrentMaterialIndex = MaterialReference.AddMaterialReference(m_CurrentMaterial, tempFont, ref m_MaterialReferences, m_MaterialReferenceIndexLookup); m_MaterialReferenceStack.Add(m_MaterialReferences[m_CurrentMaterialIndex]); } } else return false; m_CurrentFontAsset = tempFont; return true; case MarkupTag.SLASH_FONT: { MaterialReference materialReference = m_MaterialReferenceStack.Remove(); m_CurrentFontAsset = materialReference.fontAsset; m_CurrentMaterial = materialReference.material; m_CurrentMaterialIndex = materialReference.index; return true; } case MarkupTag.MATERIAL: materialHashCode = m_XmlAttribute[0].valueHashCode; // Special handling for <material=default> or <material=Default> if (materialHashCode == (int)MarkupTag.DEFAULT) { // Check if material font atlas texture matches that of the current font asset. //if (m_CurrentFontAsset.atlas.GetInstanceID() != m_CurrentMaterial.GetTexture(TextShaderUtilities.ID_MainTex).GetInstanceID()) return false; m_CurrentMaterial = m_MaterialReferences[0].material; m_CurrentMaterialIndex = 0; m_MaterialReferenceStack.Add(m_MaterialReferences[0]); return true; } // Check if material if (MaterialReferenceManager.TryGetMaterial(materialHashCode, out tempMaterial)) { // Check if material font atlas texture matches that of the current font asset. //if (m_CurrentFontAsset.atlas.GetInstanceID() != tempMaterial.GetTexture(TextShaderUtilities.ID_MainTex).GetInstanceID()) return false; m_CurrentMaterial = tempMaterial; m_CurrentMaterialIndex = MaterialReference.AddMaterialReference(m_CurrentMaterial, m_CurrentFontAsset, ref m_MaterialReferences, m_MaterialReferenceIndexLookup); m_MaterialReferenceStack.Add(m_MaterialReferences[m_CurrentMaterialIndex]); } else { if (!canWriteOnAsset) { isThreadSuccess = false; return false; } // Load new material tempMaterial = Resources.Load<Material>(textSettings.defaultFontAssetPath + new string(m_HtmlTag, m_XmlAttribute[0].valueStartIndex, m_XmlAttribute[0].valueLength)); if (tempMaterial == null) return false; // Check if material font atlas texture matches that of the current font asset. //if (m_CurrentFontAsset.atlas.GetInstanceID() != tempMaterial.GetTexture(TextShaderUtilities.ID_MainTex).GetInstanceID()) return false; // Add new reference to this material in the MaterialReferenceManager MaterialReferenceManager.AddFontMaterial(materialHashCode, tempMaterial); m_CurrentMaterial = tempMaterial; m_CurrentMaterialIndex = MaterialReference.AddMaterialReference(m_CurrentMaterial, m_CurrentFontAsset, ref m_MaterialReferences, m_MaterialReferenceIndexLookup); m_MaterialReferenceStack.Add(m_MaterialReferences[m_CurrentMaterialIndex]); } return true; case MarkupTag.SLASH_MATERIAL: { //if (m_CurrentMaterial.GetTexture(TextShaderUtilities.ID_MainTex).GetInstanceID() != m_MaterialReferenceStack.PreviousItem().material.GetTexture(TextShaderUtilities.ID_MainTex).GetInstanceID()) // return false; MaterialReference materialReference = m_MaterialReferenceStack.Remove(); m_CurrentMaterial = materialReference.material; m_CurrentMaterialIndex = materialReference.index; return true; } case MarkupTag.SPACE: value = TextGeneratorUtilities.ConvertToFloat(m_HtmlTag, m_XmlAttribute[0].valueStartIndex, m_XmlAttribute[0].valueLength); // Reject tag if value is invalid. if (value == Int16.MinValue) return false; switch (tagUnitType) { case TagUnitType.Pixels: m_XAdvance += value * (generationSettings.isOrthographic ? 1 : 0.1f); return true; case TagUnitType.FontUnits: m_XAdvance += value * (generationSettings.isOrthographic ? 1 : 0.1f) * m_CurrentFontSize; return true; case TagUnitType.Percentage: // Not applicable return false; } return false; case MarkupTag.ALPHA: if (m_XmlAttribute[0].valueLength != 3) return false; m_HtmlColor.a = (byte)(TextGeneratorUtilities.HexToInt(m_HtmlTag[7]) * 16 + TextGeneratorUtilities.HexToInt(m_HtmlTag[8])); return true; case MarkupTag.A: if (m_isTextLayoutPhase && !m_IsCalculatingPreferredValues) { // For IMGUI, we want to treat the a tag as we do with the link tag if (generationSettings.isIMGUI && textInfo != null) { int index = textInfo.linkCount; if (index + 1 > textInfo.linkInfo.Length) TextInfo.Resize(ref textInfo.linkInfo, index + 1); textInfo.linkInfo[index].hashCode = (int)MarkupTag.HREF; textInfo.linkInfo[index].linkTextfirstCharacterIndex = m_CharacterCount; textInfo.linkInfo[index].linkIdFirstCharacterIndex = 3; if (m_XmlAttribute[1].valueLength > 0) textInfo.linkInfo[index].SetLinkId(m_HtmlTag, 2, m_XmlAttribute[1].valueLength + m_XmlAttribute[1].valueStartIndex - 1); } else if (m_XmlAttribute[1].nameHashCode == (int)MarkupTag.HREF && textInfo != null) { // Make sure linkInfo array is of appropriate size. int index = textInfo.linkCount; if (index + 1 > textInfo.linkInfo.Length) TextInfo.Resize(ref textInfo.linkInfo, index + 1); textInfo.linkInfo[index].hashCode = (int)MarkupTag.HREF; textInfo.linkInfo[index].linkTextfirstCharacterIndex = m_CharacterCount; textInfo.linkInfo[index].linkIdFirstCharacterIndex = startIndex + m_XmlAttribute[1].valueStartIndex; textInfo.linkInfo[index].SetLinkId(m_HtmlTag, m_XmlAttribute[1].valueStartIndex, m_XmlAttribute[1].valueLength); } textInfo.linkCount += 1; } return true; case MarkupTag.SLASH_A: if (m_isTextLayoutPhase && !m_IsCalculatingPreferredValues && textInfo != null) { if (textInfo.linkInfo.Length <= 0 || textInfo.linkCount <= 0) { if (generationSettings.textSettings.displayWarnings) Debug.LogWarning($"There seems to be an issue with the formatting of the <a> tag. Possible issues include: missing or misplaced closing '>', missing or incorrect attribute, or unclosed quotes for attribute values. Please review the tag syntax."); } else { int index = textInfo.linkCount - 1; textInfo.linkInfo[index].linkTextLength = m_CharacterCount - textInfo.linkInfo[index].linkTextfirstCharacterIndex; } } return true; case MarkupTag.LINK: if (m_isTextLayoutPhase && !m_IsCalculatingPreferredValues && textInfo != null) { int index = textInfo.linkCount; if (index + 1 > textInfo.linkInfo.Length) TextInfo.Resize(ref textInfo.linkInfo, index + 1); textInfo.linkInfo[index].hashCode = m_XmlAttribute[0].valueHashCode; textInfo.linkInfo[index].linkTextfirstCharacterIndex = m_CharacterCount; textInfo.linkInfo[index].linkIdFirstCharacterIndex = startIndex + m_XmlAttribute[0].valueStartIndex; textInfo.linkInfo[index].SetLinkId(m_HtmlTag, m_XmlAttribute[0].valueStartIndex, m_XmlAttribute[0].valueLength); } return true; case MarkupTag.SLASH_LINK: if (m_isTextLayoutPhase && !m_IsCalculatingPreferredValues && textInfo != null) { if (textInfo.linkCount < textInfo.linkInfo.Length) { textInfo.linkInfo[textInfo.linkCount].linkTextLength = m_CharacterCount - textInfo.linkInfo[textInfo.linkCount].linkTextfirstCharacterIndex; textInfo.linkCount += 1; } } return true; case MarkupTag.ALIGN: // <align=> switch ((MarkupTag)m_XmlAttribute[0].valueHashCode) { case MarkupTag.LEFT: // <align=left> m_LineJustification = TextAlignment.MiddleLeft; m_LineJustificationStack.Add(m_LineJustification); return true; case MarkupTag.RIGHT: // <align=right> m_LineJustification = TextAlignment.MiddleRight; m_LineJustificationStack.Add(m_LineJustification); return true; case MarkupTag.CENTER: // <align=center> m_LineJustification = TextAlignment.MiddleCenter; m_LineJustificationStack.Add(m_LineJustification); return true; case MarkupTag.JUSTIFIED: // <align=justified> m_LineJustification = TextAlignment.MiddleJustified; m_LineJustificationStack.Add(m_LineJustification); return true; case MarkupTag.FLUSH: // <align=flush> m_LineJustification = TextAlignment.MiddleFlush; m_LineJustificationStack.Add(m_LineJustification); return true; } return false; case MarkupTag.SLASH_ALIGN: m_LineJustification = m_LineJustificationStack.Remove(); return true; case MarkupTag.WIDTH: value = TextGeneratorUtilities.ConvertToFloat(m_HtmlTag, m_XmlAttribute[0].valueStartIndex, m_XmlAttribute[0].valueLength); // Reject tag if value is invalid. if (value == Int16.MinValue) return false; switch (tagUnitType) { case TagUnitType.Pixels: m_Width = value * (generationSettings.isOrthographic ? 1 : 0.1f); break; case TagUnitType.FontUnits: return false; //break; case TagUnitType.Percentage: m_Width = m_MarginWidth * value / 100; break; } return true; case MarkupTag.SLASH_WIDTH: m_Width = -1; return true; // STYLE tag is now handled inline and replaced by its definition. //case 322689: // <style="name"> //case 233057: // <STYLE> // Style style = StyleSheet.GetStyle(m_XmlAttribute[0].valueHashCode); // if (style == null) return false; // m_StyleStack.Add(style.hashCode); // // Parse Style Macro // for (int i = 0; i < style.styleOpeningTagArray.Length; i++) // { // if (style.styleOpeningTagArray[i] == k_LesserThan) // { // if (ValidateHtmlTag(style.styleOpeningTagArray, i + 1, out i) == false) return false; // } // } // return true; //case 1112618: // </style> //case 1022986: // </STYLE> // style = StyleSheet.GetStyle(m_XmlAttribute[0].valueHashCode); // if (style == null) // { // // Get style from the Style Stack // int styleHashCode = m_StyleStack.CurrentItem(); // style = StyleSheet.GetStyle(styleHashCode); // m_StyleStack.Remove(); // } // if (style == null) return false; // //// Parse Style Macro // for (int i = 0; i < style.styleClosingTagArray.Length; i++) // { // if (style.styleClosingTagArray[i] == k_LesserThan) // ValidateHtmlTag(style.styleClosingTagArray, i + 1, out i); // } // return true; case MarkupTag.COLOR: if (textInfo != null) textInfo.hasMultipleColors = true; // <color=#FFF> 3 Hex (short hand) if (m_HtmlTag[6] == k_NumberSign && tagCharCount == k_LineFeed) { m_HtmlColor = TextGeneratorUtilities.HexCharsToColor(m_HtmlTag, tagCharCount); m_ColorStack.Add(m_HtmlColor); return true; } // <color=#FFF7> 4 Hex (short hand) else if (m_HtmlTag[6] == k_NumberSign && tagCharCount == 11) { m_HtmlColor = TextGeneratorUtilities.HexCharsToColor(m_HtmlTag, tagCharCount); m_ColorStack.Add(m_HtmlColor); return true; } // <color=#FF00FF> 3 Hex pairs if (m_HtmlTag[6] == k_NumberSign && tagCharCount == k_CarriageReturn) { m_HtmlColor = TextGeneratorUtilities.HexCharsToColor(m_HtmlTag, tagCharCount); m_ColorStack.Add(m_HtmlColor); return true; } // <color=#FF00FF00> 4 Hex pairs else if (m_HtmlTag[6] == k_NumberSign && tagCharCount == 15) { m_HtmlColor = TextGeneratorUtilities.HexCharsToColor(m_HtmlTag, tagCharCount); m_ColorStack.Add(m_HtmlColor); return true; } // <color=name> switch (m_XmlAttribute[0].valueHashCode) { case (int)MarkupTag.RED: // <color=red> m_HtmlColor = Color.red; m_ColorStack.Add(m_HtmlColor); return true; case (int)MarkupTag.LIGHTBLUE: // <color=lightblue> m_HtmlColor = new Color32(173, 216, 230, 255); m_ColorStack.Add(m_HtmlColor); return true; case (int)MarkupTag.BLUE: // <color=blue> m_HtmlColor = Color.blue; m_ColorStack.Add(m_HtmlColor); return true; case (int)MarkupTag.GREY: // <color=grey> m_HtmlColor = new Color32(128, 128, 128, 255); m_ColorStack.Add(m_HtmlColor); return true; case (int)MarkupTag.BLACK: // <color=black> m_HtmlColor = Color.black; m_ColorStack.Add(m_HtmlColor); return true; case (int)MarkupTag.GREEN: // <color=green> m_HtmlColor = Color.green; m_ColorStack.Add(m_HtmlColor); return true; case (int)MarkupTag.WHITE: // <color=white> m_HtmlColor = Color.white; m_ColorStack.Add(m_HtmlColor); return true; case (int)MarkupTag.ORANGE: // <color=orange> m_HtmlColor = new Color32(255, 128, 0, 255); m_ColorStack.Add(m_HtmlColor); return true; case (int)MarkupTag.PURPLE: // <color=purple> m_HtmlColor = new Color32(160, 32, 240, 255); m_ColorStack.Add(m_HtmlColor); return true; case (int)MarkupTag.YELLOW: // <color=yellow> m_HtmlColor = Color.yellow; m_ColorStack.Add(m_HtmlColor); return true; } return false; case MarkupTag.GRADIENT: int gradientPresetHashCode = m_XmlAttribute[0].valueHashCode; TextColorGradient tempColorGradientPreset; // Check if Color Gradient Preset has already been loaded. if (MaterialReferenceManager.TryGetColorGradientPreset(gradientPresetHashCode, out tempColorGradientPreset)) { m_ColorGradientPreset = tempColorGradientPreset; } else { // Load Color Gradient Preset if (tempColorGradientPreset == null) { if (!canWriteOnAsset) { isThreadSuccess = false; return false; } tempColorGradientPreset = Resources.Load<TextColorGradient>(textSettings.defaultColorGradientPresetsPath + new string(m_HtmlTag, m_XmlAttribute[0].valueStartIndex, m_XmlAttribute[0].valueLength)); } if (tempColorGradientPreset == null) return false; MaterialReferenceManager.AddColorGradientPreset(gradientPresetHashCode, tempColorGradientPreset); m_ColorGradientPreset = tempColorGradientPreset; } m_ColorGradientPresetIsTinted = false; // Check Attributes for (int i = 1; i < m_XmlAttribute.Length && m_XmlAttribute[i].nameHashCode != 0; i++) { // Get attribute name int nameHashCode = m_XmlAttribute[i].nameHashCode; switch ((MarkupTag)nameHashCode) { case MarkupTag.TINT: m_ColorGradientPresetIsTinted = TextGeneratorUtilities.ConvertToFloat(m_HtmlTag, m_XmlAttribute[i].valueStartIndex, m_XmlAttribute[i].valueLength) != 0; break; } } m_ColorGradientStack.Add(m_ColorGradientPreset); // TODO : Add support for defining preset in the tag itself return true; case MarkupTag.SLASH_GRADIENT: m_ColorGradientPreset = m_ColorGradientStack.Remove(); return true; case MarkupTag.CHARACTER_SPACE: value = TextGeneratorUtilities.ConvertToFloat(m_HtmlTag, m_XmlAttribute[0].valueStartIndex, m_XmlAttribute[0].valueLength); // Reject tag if value is invalid. if (value == Int16.MinValue) return false; switch (tagUnitType) { case TagUnitType.Pixels: m_CSpacing = value * (generationSettings.isOrthographic ? 1 : 0.1f); break; case TagUnitType.FontUnits: m_CSpacing = value * (generationSettings.isOrthographic ? 1 : 0.1f) * m_CurrentFontSize; break; case TagUnitType.Percentage: return false; } return true; case MarkupTag.SLASH_CHARACTER_SPACE: if (!m_isTextLayoutPhase || textInfo == null) return true; // Adjust xAdvance to remove extra space from last character. if (m_CharacterCount > 0) { m_XAdvance -= m_CSpacing; textInfo.textElementInfo[m_CharacterCount - 1].xAdvance = m_XAdvance; } m_CSpacing = 0; return true; case MarkupTag.MONOSPACE: value = TextGeneratorUtilities.ConvertToFloat(m_HtmlTag, m_XmlAttribute[0].valueStartIndex, m_XmlAttribute[0].valueLength); // Reject tag if value is invalid. if (value == Int16.MinValue) return false; switch (m_XmlAttribute[0].unitType) { case TagUnitType.Pixels: m_MonoSpacing = value * (generationSettings.isOrthographic ? 1 : 0.1f); break; case TagUnitType.FontUnits: m_MonoSpacing = value * (generationSettings.isOrthographic ? 1 : 0.1f) * m_CurrentFontSize; break; case TagUnitType.Percentage: return false; } // Check for potential DuoSpace attribute. if (m_XmlAttribute[1].nameHashCode == (int)MarkupTag.DUOSPACE) m_DuoSpace = TextGeneratorUtilities.ConvertToFloat(m_HtmlTag, m_XmlAttribute[1].valueStartIndex, m_XmlAttribute[1].valueLength) != 0; return true; case MarkupTag.SLASH_MONOSPACE: m_MonoSpacing = 0; m_DuoSpace = false; return true; case MarkupTag.CLASS: return false; case MarkupTag.SLASH_COLOR: m_HtmlColor = m_ColorStack.Remove(); return true; case MarkupTag.INDENT: value = TextGeneratorUtilities.ConvertToFloat(m_HtmlTag, m_XmlAttribute[0].valueStartIndex, m_XmlAttribute[0].valueLength); // Reject tag if value is invalid. if (value == Int16.MinValue) return false; switch (tagUnitType) { case TagUnitType.Pixels: m_TagIndent = value * (generationSettings.isOrthographic ? 1 : 0.1f); break; case TagUnitType.FontUnits: m_TagIndent = value * (generationSettings.isOrthographic ? 1 : 0.1f) * m_CurrentFontSize; break; case TagUnitType.Percentage: m_TagIndent = m_MarginWidth * value / 100; break; } m_IndentStack.Add(m_TagIndent); m_XAdvance = m_TagIndent; return true; case MarkupTag.SLASH_INDENT: m_TagIndent = m_IndentStack.Remove(); //m_XAdvance = m_TagIndent; return true; case MarkupTag.LINE_INDENT: value = TextGeneratorUtilities.ConvertToFloat(m_HtmlTag, m_XmlAttribute[0].valueStartIndex, m_XmlAttribute[0].valueLength); // Reject tag if value is invalid. if (value == Int16.MinValue) return false; switch (tagUnitType) { case TagUnitType.Pixels: m_TagLineIndent = value * (generationSettings.isOrthographic ? 1 : 0.1f); break; case TagUnitType.FontUnits: m_TagLineIndent = value * (generationSettings.isOrthographic ? 1 : 0.1f) * m_CurrentFontSize; break; case TagUnitType.Percentage: m_TagLineIndent = m_MarginWidth * value / 100; break; } m_XAdvance += m_TagLineIndent; return true; case MarkupTag.SLASH_LINE_INDENT: m_TagLineIndent = 0; return true; case MarkupTag.SPRITE: int spriteAssetHashCode = m_XmlAttribute[0].valueHashCode; SpriteAsset tempSpriteAsset; m_SpriteIndex = -1; // CHECK TAG FORMAT if (m_XmlAttribute[0].valueType == TagValueType.None || m_XmlAttribute[0].valueType == TagValueType.NumericalValue) { // No Sprite Asset is assigned to the text object if (generationSettings.spriteAsset != null) { m_CurrentSpriteAsset = generationSettings.spriteAsset; } else if (textSettings.defaultSpriteAsset != null) { m_CurrentSpriteAsset = textSettings.defaultSpriteAsset; } else if (TextSettings.s_GlobalSpriteAsset != null) { m_CurrentSpriteAsset = TextSettings.s_GlobalSpriteAsset; } // No valid sprite asset available if (m_CurrentSpriteAsset == null) return false; } else { // A Sprite Asset has been specified if (MaterialReferenceManager.TryGetSpriteAsset(spriteAssetHashCode, out tempSpriteAsset)) { m_CurrentSpriteAsset = tempSpriteAsset; } else { // Load Sprite Asset if (tempSpriteAsset == null) { if (tempSpriteAsset == null) { if (!canWriteOnAsset) { isThreadSuccess = false; return false; } tempSpriteAsset = Resources.Load<SpriteAsset>(textSettings.defaultSpriteAssetPath + new string(m_HtmlTag, m_XmlAttribute[0].valueStartIndex, m_XmlAttribute[0].valueLength)); } } if (tempSpriteAsset == null) return false; MaterialReferenceManager.AddSpriteAsset(spriteAssetHashCode, tempSpriteAsset); m_CurrentSpriteAsset = tempSpriteAsset; } } // Handling of <sprite=index> legacy tag format. if (m_XmlAttribute[0].valueType == TagValueType.NumericalValue) // <sprite=index> { int index = (int)TextGeneratorUtilities.ConvertToFloat(m_HtmlTag, m_XmlAttribute[0].valueStartIndex, m_XmlAttribute[0].valueLength); // Reject tag if value is invalid. if (index == Int16.MinValue) return false; // Check to make sure sprite index is valid if (index > m_CurrentSpriteAsset.spriteCharacterTable.Count - 1) return false; m_SpriteIndex = index; } m_SpriteColor = Color.white; m_TintSprite = false; // Handle Sprite Tag Attributes for (int i = 0; i < m_XmlAttribute.Length && m_XmlAttribute[i].nameHashCode != 0; i++) { int nameHashCode = m_XmlAttribute[i].nameHashCode; int index = 0; switch ((MarkupTag)nameHashCode) { case MarkupTag.NAME: m_CurrentSpriteAsset = SpriteAsset.SearchForSpriteByHashCode(m_CurrentSpriteAsset, m_XmlAttribute[i].valueHashCode, true, out index); if (index == -1) return false; m_SpriteIndex = index; break; case MarkupTag.INDEX: index = (int)TextGeneratorUtilities.ConvertToFloat(m_HtmlTag, m_XmlAttribute[1].valueStartIndex, m_XmlAttribute[1].valueLength); // Reject tag if value is invalid. if (index == Int16.MinValue) return false; // Check to make sure sprite index is valid if (index > m_CurrentSpriteAsset.spriteCharacterTable.Count - 1) return false; m_SpriteIndex = index; break; case MarkupTag.TINT: m_TintSprite = TextGeneratorUtilities.ConvertToFloat(m_HtmlTag, m_XmlAttribute[i].valueStartIndex, m_XmlAttribute[i].valueLength) != 0; break; case MarkupTag.COLOR: m_SpriteColor = TextGeneratorUtilities.HexCharsToColor(m_HtmlTag, m_XmlAttribute[i].valueStartIndex, m_XmlAttribute[i].valueLength); break; case MarkupTag.ANIM: int paramCount = TextGeneratorUtilities.GetAttributeParameters(m_HtmlTag, m_XmlAttribute[i].valueStartIndex, m_XmlAttribute[i].valueLength, ref m_AttributeParameterValues); if (paramCount != 3) return false; m_SpriteIndex = (int)m_AttributeParameterValues[0]; if (m_isTextLayoutPhase) { // It is possible for a sprite to get animated when it ends up being truncated. // Should consider moving the animation of the sprite after text geometry upload. //spriteAnimator.DoSpriteAnimation(m_CharacterCount, m_CurrentSpriteAsset, m_SpriteIndex, (int)m_AttributeParameterValues[1], (int)m_AttributeParameterValues[2]); } break; //case 45545: // size //case 32745: // SIZE // break; default: if (nameHashCode != (int)MarkupTag.SPRITE) return false; break; } } if (m_SpriteIndex == -1) return false; // Material HashCode for the Sprite Asset is the Sprite Asset Hash Code m_CurrentMaterialIndex = MaterialReference.AddMaterialReference(m_CurrentSpriteAsset.material, m_CurrentSpriteAsset, ref m_MaterialReferences, m_MaterialReferenceIndexLookup); m_TextElementType = TextElementType.Sprite; return true; case MarkupTag.LOWERCASE: m_FontStyleInternal |= FontStyles.LowerCase; m_FontStyleStack.Add(FontStyles.LowerCase); return true; case MarkupTag.SLASH_LOWERCASE: if ((generationSettings.fontStyle & FontStyles.LowerCase) != FontStyles.LowerCase) { if (m_FontStyleStack.Remove(FontStyles.LowerCase) == 0) m_FontStyleInternal &= ~FontStyles.LowerCase; } return true; case MarkupTag.ALLCAPS: case MarkupTag.UPPERCASE: m_FontStyleInternal |= FontStyles.UpperCase; m_FontStyleStack.Add(FontStyles.UpperCase); return true; case MarkupTag.SLASH_ALLCAPS: case MarkupTag.SLASH_UPPERCASE: if ((generationSettings.fontStyle & FontStyles.UpperCase) != FontStyles.UpperCase) { if (m_FontStyleStack.Remove(FontStyles.UpperCase) == 0) m_FontStyleInternal &= ~FontStyles.UpperCase; } return true; case MarkupTag.SMALLCAPS: m_FontStyleInternal |= FontStyles.SmallCaps; m_FontStyleStack.Add(FontStyles.SmallCaps); return true; case MarkupTag.SLASH_SMALLCAPS: if ((generationSettings.fontStyle & FontStyles.SmallCaps) != FontStyles.SmallCaps) { if (m_FontStyleStack.Remove(FontStyles.SmallCaps) == 0) m_FontStyleInternal &= ~FontStyles.SmallCaps; } return true; case MarkupTag.MARGIN: // Check value type switch (m_XmlAttribute[0].valueType) { case TagValueType.NumericalValue: value = TextGeneratorUtilities.ConvertToFloat(m_HtmlTag, m_XmlAttribute[0].valueStartIndex, m_XmlAttribute[0].valueLength); // px // Reject tag if value is invalid. if (value == Int16.MinValue) return false; // Determine tag unit type switch (tagUnitType) { case TagUnitType.Pixels: m_MarginLeft = value * (generationSettings.isOrthographic ? 1 : 0.1f); break; case TagUnitType.FontUnits: m_MarginLeft = value * (generationSettings.isOrthographic ? 1 : 0.1f) * m_CurrentFontSize; break; case TagUnitType.Percentage: m_MarginLeft = (m_MarginWidth - (m_Width != -1 ? m_Width : 0)) * value / 100; break; } m_MarginLeft = m_MarginLeft >= 0 ? m_MarginLeft : 0; m_MarginRight = m_MarginLeft; return true; case TagValueType.None: for (int i = 1; i < m_XmlAttribute.Length && m_XmlAttribute[i].nameHashCode != 0; i++) { // Get attribute name int nameHashCode = m_XmlAttribute[i].nameHashCode; switch ((MarkupTag)nameHashCode) { case MarkupTag.LEFT: value = TextGeneratorUtilities.ConvertToFloat(m_HtmlTag, m_XmlAttribute[i].valueStartIndex, m_XmlAttribute[i].valueLength); // px // Reject tag if value is invalid. if (value == Int16.MinValue) return false; switch (m_XmlAttribute[i].unitType) { case TagUnitType.Pixels: m_MarginLeft = value * (generationSettings.isOrthographic ? 1 : 0.1f); break; case TagUnitType.FontUnits: m_MarginLeft = value * (generationSettings.isOrthographic ? 1 : 0.1f) * m_CurrentFontSize; break; case TagUnitType.Percentage: m_MarginLeft = (m_MarginWidth - (m_Width != -1 ? m_Width : 0)) * value / 100; break; } m_MarginLeft = m_MarginLeft >= 0 ? m_MarginLeft : 0; break; case MarkupTag.RIGHT: value = TextGeneratorUtilities.ConvertToFloat(m_HtmlTag, m_XmlAttribute[i].valueStartIndex, m_XmlAttribute[i].valueLength); // px // Reject tag if value is invalid. if (value == Int16.MinValue) return false; switch (m_XmlAttribute[i].unitType) { case TagUnitType.Pixels: m_MarginRight = value * (generationSettings.isOrthographic ? 1 : 0.1f); break; case TagUnitType.FontUnits: m_MarginRight = value * (generationSettings.isOrthographic ? 1 : 0.1f) * m_CurrentFontSize; break; case TagUnitType.Percentage: m_MarginRight = (m_MarginWidth - (m_Width != -1 ? m_Width : 0)) * value / 100; break; } m_MarginRight = m_MarginRight >= 0 ? m_MarginRight : 0; break; } } return true; } return false; case MarkupTag.SLASH_MARGIN: m_MarginLeft = 0; m_MarginRight = 0; return true; case MarkupTag.MARGIN_LEFT: value = TextGeneratorUtilities.ConvertToFloat(m_HtmlTag, m_XmlAttribute[0].valueStartIndex, m_XmlAttribute[0].valueLength); // px // Reject tag if value is invalid. if (value == Int16.MinValue) return false; switch (tagUnitType) { case TagUnitType.Pixels: m_MarginLeft = value * (generationSettings.isOrthographic ? 1 : 0.1f); break; case TagUnitType.FontUnits: m_MarginLeft = value * (generationSettings.isOrthographic ? 1 : 0.1f) * m_CurrentFontSize; break; case TagUnitType.Percentage: m_MarginLeft = (m_MarginWidth - (m_Width != -1 ? m_Width : 0)) * value / 100; break; } m_MarginLeft = m_MarginLeft >= 0 ? m_MarginLeft : 0; return true; case MarkupTag.MARGIN_RIGHT: value = TextGeneratorUtilities.ConvertToFloat(m_HtmlTag, m_XmlAttribute[0].valueStartIndex, m_XmlAttribute[0].valueLength); // px // Reject tag if value is invalid. if (value == Int16.MinValue) return false; switch (tagUnitType) { case TagUnitType.Pixels: m_MarginRight = value * (generationSettings.isOrthographic ? 1 : 0.1f); break; case TagUnitType.FontUnits: m_MarginRight = value * (generationSettings.isOrthographic ? 1 : 0.1f) * m_CurrentFontSize; break; case TagUnitType.Percentage: m_MarginRight = (m_MarginWidth - (m_Width != -1 ? m_Width : 0)) * value / 100; break; } m_MarginRight = m_MarginRight >= 0 ? m_MarginRight : 0; return true; case MarkupTag.LINE_HEIGHT: value = TextGeneratorUtilities.ConvertToFloat(m_HtmlTag, m_XmlAttribute[0].valueStartIndex, m_XmlAttribute[0].valueLength); // Reject tag if value is invalid. if (value == Int16.MinValue) return false; switch (tagUnitType) { case TagUnitType.Pixels: m_LineHeight = value * (generationSettings.isOrthographic ? 1 : 0.1f); break; case TagUnitType.FontUnits: m_LineHeight = value * (generationSettings.isOrthographic ? 1 : 0.1f) * m_CurrentFontSize; break; case TagUnitType.Percentage: fontScale = (m_CurrentFontSize / m_CurrentFontAsset.faceInfo.pointSize * m_CurrentFontAsset.faceInfo.scale * (generationSettings.isOrthographic ? 1 : 0.1f)); m_LineHeight = generationSettings.fontAsset.faceInfo.lineHeight * value / 100 * fontScale; break; } return true; case MarkupTag.SLASH_LINE_HEIGHT: m_LineHeight = k_FloatUnset; return true; case MarkupTag.NO_PARSE: m_TagNoParsing = true; return true; case MarkupTag.ACTION: int actionID = m_XmlAttribute[0].valueHashCode; if (m_isTextLayoutPhase) { m_ActionStack.Add(actionID); Debug.Log("Action ID: [" + actionID + "] First character index: " + m_CharacterCount); } //if (m_isTextLayoutPhase) //{ // TMP_Action action = TMP_Action.GetAction(m_XmlAttribute[0].valueHashCode); //} return true; case MarkupTag.SLASH_ACTION: if (m_isTextLayoutPhase) { Debug.Log("Action ID: [" + m_ActionStack.CurrentItem() + "] Last character index: " + (m_CharacterCount - 1)); } m_ActionStack.Remove(); return true; case MarkupTag.SCALE: value = TextGeneratorUtilities.ConvertToFloat(m_HtmlTag, m_XmlAttribute[0].valueStartIndex, m_XmlAttribute[0].valueLength); // Reject tag if value is invalid. if (value == Int16.MinValue) return false; m_FXScale = new Vector3(value, 1, 1); return true; case MarkupTag.SLASH_SCALE: m_FXScale = Vector3.one; return true; case MarkupTag.ROTATE: // TODO: Add attribute to provide for ability to use Random Rotation value = TextGeneratorUtilities.ConvertToFloat(m_HtmlTag, m_XmlAttribute[0].valueStartIndex, m_XmlAttribute[0].valueLength); // Reject tag if value is invalid. if (value == Int16.MinValue) return false; m_FXRotation = Quaternion.Euler(0, 0, value); return true; case MarkupTag.SLASH_ROTATE: m_FXRotation = Quaternion.identity; return true; case MarkupTag.TABLE: //switch (m_XmlAttribute[1].nameHashCode) //{ // case 327550: // width // float tableWidth = ConvertToFloat(m_HtmlTag, m_XmlAttribute[1].valueStartIndex, m_XmlAttribute[1].valueLength); // // Reject tag if value is invalid. // if (tableWidth == Int16.MinValue) return false; // switch (tagUnitType) // { // case TagUnitType.Pixels: // Debug.Log("Table width = " + tableWidth + "px."); // break; // case TagUnitType.FontUnits: // Debug.Log("Table width = " + tableWidth + "em."); // break; // case TagUnitType.Percentage: // Debug.Log("Table width = " + tableWidth + "%."); // break; // } // break; //} return false; case MarkupTag.SLASH_TABLE: return false; case MarkupTag.TR: return false; case MarkupTag.SLASH_TR: return false; case MarkupTag.TH: // Set style to bold and center alignment return false; case MarkupTag.SLASH_TH: return false; case MarkupTag.TD: // Style options //for (int i = 1; i < m_XmlAttribute.Length && m_XmlAttribute[i].nameHashCode != 0; i++) //{ // switch (m_XmlAttribute[i].nameHashCode) // { // case 327550: // width // float tableWidth = ConvertToFloat(m_HtmlTag, m_XmlAttribute[i].valueStartIndex, m_XmlAttribute[i].valueLength); // switch (tagUnitType) // { // case TagUnitType.Pixels: // Debug.Log("Table width = " + tableWidth + "px."); // break; // case TagUnitType.FontUnits: // Debug.Log("Table width = " + tableWidth + "em."); // break; // case TagUnitType.Percentage: // Debug.Log("Table width = " + tableWidth + "%."); // break; // } // break; // case 275917: // align // switch (m_XmlAttribute[i].valueHashCode) // { // case 3774683: // left // Debug.Log("TD align=\"left\"."); // break; // case 136703040: // right // Debug.Log("TD align=\"right\"."); // break; // case -458210101: // center // Debug.Log("TD align=\"center\"."); // break; // case -523808257: // justified // Debug.Log("TD align=\"justified\"."); // break; // } // break; // } //} return false; case MarkupTag.SLASH_TD: return false; } } #endregion return false; } void ClearMarkupTagAttributes() { int length = m_XmlAttribute.Length; for (int i = 0; i < length; i++) m_XmlAttribute[i] = new RichTextTagAttribute(); } } }
UnityCsReference/Modules/TextCoreTextEngine/Managed/TextGenerator/TextGeneratorHtmlTagValidation.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreTextEngine/Managed/TextGenerator/TextGeneratorHtmlTagValidation.cs", "repo_id": "UnityCsReference", "token_count": 55748 }
475
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; namespace UnityEngine.TextCore.Text { [Serializable] public class UnicodeLineBreakingRules { /// <summary> /// Text file that contains the Unicode line breaking rules defined here https://www.unicode.org/reports/tr14/tr14-22.html /// </summary> public UnityEngine.TextAsset lineBreakingRules { get => m_UnicodeLineBreakingRules; } [SerializeField] #pragma warning disable 0649 UnityEngine.TextAsset m_UnicodeLineBreakingRules; /// <summary> /// Text file that contains the leading characters /// </summary> public UnityEngine.TextAsset leadingCharacters { get => m_LeadingCharacters; } [SerializeField] #pragma warning disable 0649 UnityEngine.TextAsset m_LeadingCharacters; /// <summary> /// Text file that contains the following characters /// </summary> public UnityEngine.TextAsset followingCharacters { get => m_FollowingCharacters; } [SerializeField] #pragma warning disable 0649 UnityEngine.TextAsset m_FollowingCharacters; /// <summary> /// /// </summary> internal HashSet<uint> leadingCharactersLookup { get { if (m_LeadingCharactersLookup == null) LoadLineBreakingRules(); return m_LeadingCharactersLookup; } set => m_LeadingCharactersLookup = value; } /// <summary> /// /// </summary> internal HashSet<uint> followingCharactersLookup { get { if (m_LeadingCharactersLookup == null) LoadLineBreakingRules(); return m_FollowingCharactersLookup; } set => m_FollowingCharactersLookup = value; } /// <summary> /// Determines if Modern or Traditional line breaking rules should be used for Korean text. /// </summary> public bool useModernHangulLineBreakingRules { get => m_UseModernHangulLineBreakingRules; set => m_UseModernHangulLineBreakingRules = value; } [SerializeField] private bool m_UseModernHangulLineBreakingRules; // ============================================= // Private backing fields for public properties. // ============================================= HashSet<uint> m_LeadingCharactersLookup; HashSet<uint> m_FollowingCharactersLookup; /// <summary> /// /// </summary> internal void LoadLineBreakingRules() { if (m_LeadingCharactersLookup == null) { if (m_LeadingCharacters == null) m_LeadingCharacters = Resources.Load<UnityEngine.TextAsset>("LineBreaking Leading Characters"); m_LeadingCharactersLookup = m_LeadingCharacters != null ? GetCharacters(m_LeadingCharacters) : new HashSet<uint>(); if (m_FollowingCharacters == null) m_FollowingCharacters = Resources.Load<UnityEngine.TextAsset>("LineBreaking Following Characters"); m_FollowingCharactersLookup = m_FollowingCharacters != null ? GetCharacters(m_FollowingCharacters) : new HashSet<uint>(); } } internal void LoadLineBreakingRules(UnityEngine.TextAsset leadingRules, UnityEngine.TextAsset followingRules) { if (m_LeadingCharactersLookup == null) { if (leadingRules == null) leadingRules = Resources.Load<UnityEngine.TextAsset>("LineBreaking Leading Characters"); m_LeadingCharactersLookup = leadingRules != null ? GetCharacters(leadingRules) : new HashSet<uint>(); if (followingRules == null) followingRules = Resources.Load<UnityEngine.TextAsset>("LineBreaking Following Characters"); m_FollowingCharactersLookup = followingRules != null ? GetCharacters(followingRules) : new HashSet<uint>(); } } private static HashSet<uint> GetCharacters(UnityEngine.TextAsset file) { HashSet<uint> ruleSet = new HashSet<uint>(); string text = file.text; for (int i = 0; i < text.Length; i++) ruleSet.Add(text[i]); return ruleSet; } } }
UnityCsReference/Modules/TextCoreTextEngine/Managed/UnicodeLineBreakingRules.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreTextEngine/Managed/UnicodeLineBreakingRules.cs", "repo_id": "UnityCsReference", "token_count": 2037 }
476
// 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.TextCore.Text; namespace UnityEditor.TextCore.Text { [CustomPropertyDrawer(typeof(SpriteCharacter))] internal class SpriteCharacterPropertyDrawer : PropertyDrawer { int m_GlyphSelectedForEditing = -1; public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { SerializedProperty prop_SpriteName = property.FindPropertyRelative("m_Name"); SerializedProperty prop_SpriteUnicode = property.FindPropertyRelative("m_Unicode"); SerializedProperty prop_SpriteGlyphIndex = property.FindPropertyRelative("m_GlyphIndex"); SerializedProperty prop_SpriteScale = property.FindPropertyRelative("m_Scale"); GUIStyle style = new GUIStyle(EditorStyles.label); style.richText = true; EditorGUIUtility.labelWidth = 40f; EditorGUIUtility.fieldWidth = 50; Rect rect = new Rect(position.x + 60, position.y, position.width, 49); // Display non-editable fields if (GUI.enabled == false) { // Sprite Character Index int spriteCharacterIndex; int.TryParse(property.displayName.Split(' ')[1], out spriteCharacterIndex); EditorGUI.LabelField(new Rect(rect.x, rect.y, 75f, 18), new GUIContent("Index: <color=#FFFF80>" + spriteCharacterIndex + "</color>"), style); EditorGUI.LabelField(new Rect(rect.x + 75f, rect.y, 120f, 18), new GUIContent("Unicode: <color=#FFFF80>0x" + prop_SpriteUnicode.intValue.ToString("X") + "</color>"), style); EditorGUI.LabelField(new Rect(rect.x + 195f, rect.y, rect.width - 255, 18), new GUIContent("Name: <color=#FFFF80>" + prop_SpriteName.stringValue + "</color>"), style); EditorGUI.LabelField(new Rect(rect.x, rect.y + 18, 120, 18), new GUIContent("Glyph ID: <color=#FFFF80>" + prop_SpriteGlyphIndex.intValue + "</color>"), style); // Draw Sprite Glyph (if exists) DrawSpriteGlyph(position, property); EditorGUI.LabelField(new Rect(rect.x, rect.y + 36, 80, 18), new GUIContent("Scale: <color=#FFFF80>" + prop_SpriteScale.floatValue + "</color>"), style); } else // Display editable fields { // Get a reference to the underlying Sprite Asset SpriteAsset spriteAsset = property.serializedObject.targetObject as SpriteAsset; // Sprite Character Index int spriteCharacterIndex; int.TryParse(property.displayName.Split(' ')[1], out spriteCharacterIndex); EditorGUI.LabelField(new Rect(rect.x, rect.y, 75f, 18), new GUIContent("Index: <color=#FFFF80>" + spriteCharacterIndex + "</color>"), style); EditorGUIUtility.labelWidth = 55f; GUI.SetNextControlName("Unicode Input"); EditorGUI.BeginChangeCheck(); string unicode = EditorGUI.DelayedTextField(new Rect(rect.x + 75f, rect.y, 120, 18), "Unicode:", prop_SpriteUnicode.intValue.ToString("X")); if (GUI.GetNameOfFocusedControl() == "Unicode Input") { //Filter out unwanted characters. char chr = Event.current.character; if ((chr < '0' || chr > '9') && (chr < 'a' || chr > 'f') && (chr < 'A' || chr > 'F')) { Event.current.character = '\0'; } } if (EditorGUI.EndChangeCheck()) { // Update Unicode value prop_SpriteUnicode.intValue = (int)TextUtilities.StringHexToInt(unicode); spriteAsset.m_IsSpriteAssetLookupTablesDirty = true; } EditorGUIUtility.labelWidth = 41f; EditorGUI.BeginChangeCheck(); EditorGUI.DelayedTextField(new Rect(rect.x + 195f, rect.y, rect.width - 255, 18), prop_SpriteName, new GUIContent("Name:")); if (EditorGUI.EndChangeCheck()) { spriteAsset.m_IsSpriteAssetLookupTablesDirty = true; } EditorGUIUtility.labelWidth = 59f; EditorGUI.BeginChangeCheck(); EditorGUI.DelayedIntField(new Rect(rect.x, rect.y + 18, 100, 18), prop_SpriteGlyphIndex, new GUIContent("Glyph ID:")); if (EditorGUI.EndChangeCheck()) { spriteAsset.m_IsSpriteAssetLookupTablesDirty = true; } // Draw Sprite Glyph (if exists) DrawSpriteGlyph(position, property); int glyphIndex = prop_SpriteGlyphIndex.intValue; // Reset glyph selection if new character has been selected. if (GUI.enabled && m_GlyphSelectedForEditing != glyphIndex) m_GlyphSelectedForEditing = -1; // Display button to edit the glyph data. if (GUI.Button(new Rect(rect.x + 120, rect.y + 18, 75, 18), new GUIContent("Edit Glyph"))) { if (m_GlyphSelectedForEditing == -1) m_GlyphSelectedForEditing = glyphIndex; else m_GlyphSelectedForEditing = -1; // Button clicks should not result in potential change. GUI.changed = false; } // Show the glyph property drawer if selected if (glyphIndex == m_GlyphSelectedForEditing && GUI.enabled) { if (spriteAsset != null) { // Lookup glyph and draw glyph (if available) int elementIndex = spriteAsset.spriteGlyphTable.FindIndex(item => item.index == glyphIndex); if (elementIndex != -1) { // Get a reference to the Sprite Glyph Table SerializedProperty prop_SpriteGlyphTable = property.serializedObject.FindProperty("m_SpriteGlyphTable"); SerializedProperty prop_SpriteGlyph = prop_SpriteGlyphTable.GetArrayElementAtIndex(elementIndex); SerializedProperty prop_GlyphMetrics = prop_SpriteGlyph.FindPropertyRelative("m_Metrics"); SerializedProperty prop_GlyphRect = prop_SpriteGlyph.FindPropertyRelative("m_GlyphRect"); Rect newRect = EditorGUILayout.GetControlRect(false, 115); EditorGUI.DrawRect(new Rect(newRect.x + 62, newRect.y - 20, newRect.width - 62, newRect.height - 5), new Color(0.1f, 0.1f, 0.1f, 0.45f)); EditorGUI.DrawRect(new Rect(newRect.x + 63, newRect.y - 19, newRect.width - 64, newRect.height - 7), new Color(0.3f, 0.3f, 0.3f, 0.8f)); // Display GlyphRect newRect.x += 65; newRect.y -= 18; newRect.width += 5; EditorGUI.PropertyField(newRect, prop_GlyphRect); // Display GlyphMetrics newRect.y += 45; EditorGUI.PropertyField(newRect, prop_GlyphMetrics); rect.y += 120; } } } EditorGUIUtility.labelWidth = 39f; EditorGUI.PropertyField(new Rect(rect.x, rect.y + 36, 80, 18), prop_SpriteScale, new GUIContent("Scale:")); } } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return 58; } void DrawSpriteGlyph(Rect position, SerializedProperty property) { // Get a reference to the sprite glyph table SpriteAsset spriteAsset = property.serializedObject.targetObject as SpriteAsset; if (spriteAsset == null) return; int glyphIndex = property.FindPropertyRelative("m_GlyphIndex").intValue; // Lookup glyph and draw glyph (if available) int elementIndex = spriteAsset.spriteGlyphTable.FindIndex(item => item.index == glyphIndex); if (elementIndex != -1) { // Get a reference to the Sprite Glyph Table SerializedProperty prop_SpriteGlyphTable = property.serializedObject.FindProperty("m_SpriteGlyphTable"); SerializedProperty prop_SpriteGlyph = prop_SpriteGlyphTable.GetArrayElementAtIndex(elementIndex); SerializedProperty prop_GlyphRect = prop_SpriteGlyph.FindPropertyRelative("m_GlyphRect"); // Get a reference to the sprite texture Texture tex = spriteAsset.spriteSheet; // Return if we don't have a texture assigned to the sprite asset. if (tex == null) { Debug.LogWarning("Please assign a valid Sprite Atlas texture to the [" + spriteAsset.name + "] Sprite Asset.", spriteAsset); return; } Vector2 spriteTexPosition = new Vector2(position.x, position.y); Vector2 spriteSize = new Vector2(48, 48); Vector2 alignmentOffset = new Vector2((58 - spriteSize.x) / 2, (58 - spriteSize.y) / 2); float x = prop_GlyphRect.FindPropertyRelative("m_X").intValue; float y = prop_GlyphRect.FindPropertyRelative("m_Y").intValue; float spriteWidth = prop_GlyphRect.FindPropertyRelative("m_Width").intValue; float spriteHeight = prop_GlyphRect.FindPropertyRelative("m_Height").intValue; if (spriteWidth >= spriteHeight) { spriteSize.y = spriteHeight * spriteSize.x / spriteWidth; spriteTexPosition.y += (spriteSize.x - spriteSize.y) / 2; } else { spriteSize.x = spriteWidth * spriteSize.y / spriteHeight; spriteTexPosition.x += (spriteSize.y - spriteSize.x) / 2; } // Compute the normalized texture coordinates Rect texCoords = new Rect(x / tex.width, y / tex.height, spriteWidth / tex.width, spriteHeight / tex.height); GUI.DrawTextureWithTexCoords(new Rect(spriteTexPosition.x + alignmentOffset.x, spriteTexPosition.y + alignmentOffset.y, spriteSize.x, spriteSize.y), tex, texCoords, true); } } } }
UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/PropertyDrawers/SpriteCharacterPropertyDrawer.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/PropertyDrawers/SpriteCharacterPropertyDrawer.cs", "repo_id": "UnityCsReference", "token_count": 5338 }
477
// 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.TextCore.Text; namespace UnityEditor.TextCore.Text { public class TextCoreShaderGUISDF : TextCoreShaderGUI { static ShaderFeature s_OutlineFeature, s_UnderlayFeature, s_BevelFeature, s_GlowFeature, s_MaskFeature; static bool s_Face = true, s_Outline = true, s_Outline2 = true, s_Outline3 = true, s_Underlay = true, s_Lighting = true, s_Glow, s_Bevel, s_Light, s_Bump, s_Env; static string[] s_FaceUVSpeedName = { "_FaceUVSpeed" }, s_FaceUvSpeedNames = { "_FaceUVSpeedX", "_FaceUVSpeedY" }, s_OutlineUvSpeedNames = { "_OutlineUVSpeedX", "_OutlineUVSpeedY" }, s_OutlineUvSpeedName = { "_OutlineUVSpeed" }; static TextCoreShaderGUISDF() { s_OutlineFeature = new ShaderFeature() { undoLabel = "Outline", keywords = new[] { "OUTLINE_ON" } }; s_UnderlayFeature = new ShaderFeature() { undoLabel = "Underlay", keywords = new[] { "UNDERLAY_ON", "UNDERLAY_INNER" }, label = new GUIContent("Underlay Type"), keywordLabels = new[] { new GUIContent("None"), new GUIContent("Normal"), new GUIContent("Inner") } }; s_BevelFeature = new ShaderFeature() { undoLabel = "Bevel", keywords = new[] { "BEVEL_ON" } }; s_GlowFeature = new ShaderFeature() { undoLabel = "Glow", keywords = new[] { "GLOW_ON" } }; s_MaskFeature = new ShaderFeature() { undoLabel = "Mask", keywords = new[] { "MASK_HARD", "MASK_SOFT" }, label = new GUIContent("Mask"), keywordLabels = new[] { new GUIContent("Mask Off"), new GUIContent("Mask Hard"), new GUIContent("Mask Soft") } }; } protected override void DoGUI() { bool isSRPMaterial = m_Material.HasProperty(TextShaderUtilities.ID_IsoPerimeter); s_Face = BeginPanel("Face", s_Face); if (s_Face) { DoFacePanel(); } EndPanel(); // Outline panels if (isSRPMaterial) { DoOutlinePanels(); } else { s_Outline = m_Material.HasProperty(TextShaderUtilities.ID_OutlineTex) ? BeginPanel("Outline", s_Outline) : BeginPanel("Outline", s_OutlineFeature, s_Outline); if (s_Outline) { DoOutlinePanel(); } EndPanel(); if (m_Material.HasProperty(TextShaderUtilities.ID_Outline2Color)) { s_Outline2 = BeginPanel("Outline 2", s_OutlineFeature, s_Outline2); if (s_Outline2) { DoOutline2Panel(); } EndPanel(); } } // Underlay panel if (m_Material.HasProperty(TextShaderUtilities.ID_UnderlayColor)) { if (isSRPMaterial) { s_Underlay = BeginPanel("Underlay", s_Underlay); if (s_Underlay) { DoUnderlayPanel(); } EndPanel(); } else { s_Underlay = BeginPanel("Underlay", s_UnderlayFeature, s_Underlay); if (s_Underlay) { DoUnderlayPanel(); } EndPanel(); } } // Lighting panel if (m_Material.HasProperty("_SpecularColor")) { if (isSRPMaterial) DrawLightingPanelSRP(); else DrawLightingPanelLegacy(); } else if (m_Material.HasProperty("_SpecColor")) { s_Bevel = BeginPanel("Bevel", s_Bevel); if (s_Bevel) { DoBevelPanel(); } EndPanel(); s_Light = BeginPanel("Surface Lighting", s_Light); if (s_Light) { DoSurfaceLightingPanel(); } EndPanel(); s_Bump = BeginPanel("Bump Map", s_Bump); if (s_Bump) { DoBumpMapPanel(); } EndPanel(); s_Env = BeginPanel("Environment Map", s_Env); if (s_Env) { DoEnvMapPanel(); } EndPanel(); } if (m_Material.HasProperty(TextShaderUtilities.ID_GlowColor)) { s_Glow = BeginPanel("Glow", s_GlowFeature, s_Glow); if (s_Glow) { DoGlowPanel(); } EndPanel(); } s_DebugExtended = BeginPanel("Debug Settings", s_DebugExtended); if (s_DebugExtended) { if (isSRPMaterial) DoDebugPanelSRP(); else DoDebugPanel(); } EndPanel(); EditorGUILayout.Space(); EditorGUILayout.Space(); if (isSRPMaterial) { m_Editor.RenderQueueField(); m_Editor.EnableInstancingField(); m_Editor.DoubleSidedGIField(); m_Editor.EmissionEnabledProperty(); } } private void DrawLightingPanelSRP() { s_Lighting = BeginPanel("Lighting", s_Lighting); if (s_Lighting) { s_Bevel = BeginPanel("Bevel", s_Bevel); if (s_Bevel) { DoBevelPanelSRP(); } EndPanel(); s_Light = BeginPanel("Local Lighting", s_Light); if (s_Light) { DoLocalLightingPanel(); } EndPanel(); } EndPanel(); } private void DrawLightingPanelLegacy() { s_Lighting = BeginPanel("Lighting", s_BevelFeature, s_Lighting); if (s_Lighting) { s_Bevel = BeginPanel("Bevel", s_Bevel); if (s_Bevel) { DoBevelPanel(); } EndPanel(); s_Light = BeginPanel("Local Lighting", s_Light); if (s_Light) { DoLocalLightingPanel(); } EndPanel(); s_Bump = BeginPanel("Bump Map", s_Bump); if (s_Bump) { DoBumpMapPanel(); } EndPanel(); s_Env = BeginPanel("Environment Map", s_Env); if (s_Env) { DoEnvMapPanel(); } EndPanel(); } EndPanel(); } void DoFacePanel() { EditorGUI.indentLevel += 1; DoColor("_FaceColor", "Color"); if (m_Material.HasProperty(TextShaderUtilities.ID_FaceTex)) { if (m_Material.HasProperty("_FaceUVSpeedX")) { DoTexture2D("_FaceTex", "Texture", true, s_FaceUvSpeedNames); } else if (m_Material.HasProperty("_FaceUVSpeed")) { DoTexture2D("_FaceTex", "Texture", true, s_FaceUVSpeedName); } else { DoTexture2D("_FaceTex", "Texture", true); } } if (m_Material.HasProperty("_Softness")) { DoSlider("_Softness", "X", new Vector2(0, 1), "Softness"); } if (m_Material.HasProperty("_OutlineSoftness")) { DoSlider("_OutlineSoftness", "Softness"); } if (m_Material.HasProperty(TextShaderUtilities.ID_FaceDilate)) { DoSlider("_FaceDilate", "Dilate"); if (m_Material.HasProperty(TextShaderUtilities.ID_Shininess)) { DoSlider("_FaceShininess", "Gloss"); } } if (m_Material.HasProperty(TextShaderUtilities.ID_IsoPerimeter)) { DoSlider("_IsoPerimeter", "X", new Vector2(-1, 1), "Dilate"); } EditorGUI.indentLevel -= 1; EditorGUILayout.Space(); } void DoOutlinePanel() { EditorGUI.indentLevel += 1; DoColor("_OutlineColor", "Color"); if (m_Material.HasProperty(TextShaderUtilities.ID_OutlineTex)) { if (m_Material.HasProperty("_OutlineUVSpeedX")) { DoTexture2D("_OutlineTex", "Texture", true, s_OutlineUvSpeedNames); } else if (m_Material.HasProperty("_OutlineUVSpeed")) { DoTexture2D("_OutlineTex", "Texture", true, s_OutlineUvSpeedName); } else { DoTexture2D("_OutlineTex", "Texture", true); } } DoSlider("_OutlineWidth", "Thickness"); if (m_Material.HasProperty("_OutlineShininess")) { DoSlider("_OutlineShininess", "Gloss"); } EditorGUI.indentLevel -= 1; EditorGUILayout.Space(); } void DoOutlinePanel(int outlineID, string propertyField, string label) { EditorGUI.indentLevel += 1; DoColor("_OutlineColor" + outlineID, label); if (outlineID != 3) DoOffset("_OutlineOffset" + outlineID, "Offset"); else { if (m_Material.GetFloat(TextShaderUtilities.ID_OutlineMode) == 0) DoOffset("_OutlineOffset" + outlineID, "Offset"); } DoSlider("_Softness", propertyField, new Vector2(0, 1), "Softness"); DoSlider("_IsoPerimeter", propertyField, new Vector2(-1, 1), "Dilate"); if (outlineID == 3) { DoToggle("_OutlineMode", "Outline Mode"); } if (m_Material.HasProperty("_OutlineShininess")) { //DoSlider("_OutlineShininess", "Gloss"); } EditorGUI.indentLevel -= 1; EditorGUILayout.Space(); } void DoOutlinePanelWithTexture(int outlineID, string propertyField, string label) { EditorGUI.indentLevel += 1; DoColor("_OutlineColor" + outlineID, label); if (m_Material.HasProperty(TextShaderUtilities.ID_OutlineTex)) { if (m_Material.HasProperty("_OutlineUVSpeedX")) { DoTexture2D("_OutlineTex", "Texture", true, s_OutlineUvSpeedNames); } else if (m_Material.HasProperty("_OutlineUVSpeed")) { DoTexture2D("_OutlineTex", "Texture", true, s_OutlineUvSpeedName); } else { DoTexture2D("_OutlineTex", "Texture", true); } } DoOffset("_OutlineOffset" + outlineID, "Offset"); DoSlider("_Softness", propertyField, new Vector2(0, 1), "Softness"); DoSlider("_IsoPerimeter", propertyField, new Vector2(-1, 1), "Dilate"); if (m_Material.HasProperty("_OutlineShininess")) { //DoSlider("_OutlineShininess", "Gloss"); } EditorGUI.indentLevel -= 1; EditorGUILayout.Space(); } void DoOutline2Panel() { EditorGUI.indentLevel += 1; DoColor("_Outline2Color", "Color"); //if (m_Material.HasProperty(TextShaderUtilities.ID_OutlineTex)) //{ // if (m_Material.HasProperty("_OutlineUVSpeedX")) // { // DoTexture2D("_OutlineTex", "Texture", true, s_OutlineUvSpeedNames); // } // else // { // DoTexture2D("_OutlineTex", "Texture", true); // } //} DoSlider("_Outline2Width", "Thickness"); //if (m_Material.HasProperty("_OutlineShininess")) //{ // DoSlider("_OutlineShininess", "Gloss"); //} EditorGUI.indentLevel -= 1; EditorGUILayout.Space(); } void DoOutlinePanels() { s_Outline = BeginPanel("Outline 1", s_Outline); if (s_Outline) DoOutlinePanelWithTexture(1, "Y", "Color"); EndPanel(); s_Outline2 = BeginPanel("Outline 2", s_Outline2); if (s_Outline2) DoOutlinePanel(2, "Z", "Color"); EndPanel(); s_Outline3 = BeginPanel("Outline 3", s_Outline3); if (s_Outline3) DoOutlinePanel(3, "W", "Color"); EndPanel(); } void DoUnderlayPanel() { EditorGUI.indentLevel += 1; if (m_Material.HasProperty(TextShaderUtilities.ID_IsoPerimeter)) { DoColor("_UnderlayColor", "Color"); DoSlider("_UnderlayOffset", "X", new Vector2(-1, 1), "Offset X"); DoSlider("_UnderlayOffset", "Y", new Vector2(-1, 1), "Offset Y"); DoSlider("_UnderlayDilate", new Vector2(-1, 1), "Dilate"); DoSlider("_UnderlaySoftness", new Vector2(0, 1), "Softness"); } else { s_UnderlayFeature.DoPopup(m_Editor, m_Material); DoColor("_UnderlayColor", "Color"); DoSlider("_UnderlayOffsetX", "Offset X"); DoSlider("_UnderlayOffsetY", "Offset Y"); DoSlider("_UnderlayDilate", "Dilate"); DoSlider("_UnderlaySoftness", "Softness"); } EditorGUI.indentLevel -= 1; EditorGUILayout.Space(); } static GUIContent[] s_BevelTypeLabels = { new GUIContent("Outer Bevel"), new GUIContent("Inner Bevel") }; void DoBevelPanel() { EditorGUI.indentLevel += 1; DoPopup("_ShaderFlags", "Type", s_BevelTypeLabels); DoSlider("_Bevel", "Amount"); DoSlider("_BevelOffset", "Offset"); DoSlider("_BevelWidth", "Width"); DoSlider("_BevelRoundness", "Roundness"); DoSlider("_BevelClamp", "Clamp"); EditorGUI.indentLevel -= 1; EditorGUILayout.Space(); } void DoBevelPanelSRP() { EditorGUI.indentLevel += 1; DoPopup("_BevelType", "Type", s_BevelTypeLabels); DoSlider("_BevelAmount", "Amount"); DoSlider("_BevelOffset", "Offset"); DoSlider("_BevelWidth", "Width"); DoSlider("_BevelRoundness", "Roundness"); DoSlider("_BevelClamp", "Clamp"); EditorGUI.indentLevel -= 1; EditorGUILayout.Space(); } void DoLocalLightingPanel() { EditorGUI.indentLevel += 1; DoSlider("_LightAngle", "Light Angle"); DoColor("_SpecularColor", "Specular Color"); DoSlider("_SpecularPower", "Specular Power"); DoSlider("_Reflectivity", "Reflectivity Power"); DoSlider("_Diffuse", "Diffuse Shadow"); DoSlider("_Ambient", "Ambient Shadow"); EditorGUI.indentLevel -= 1; EditorGUILayout.Space(); } void DoSurfaceLightingPanel() { EditorGUI.indentLevel += 1; DoColor("_SpecColor", "Specular Color"); EditorGUI.indentLevel -= 1; EditorGUILayout.Space(); } void DoBumpMapPanel() { EditorGUI.indentLevel += 1; DoTexture2D("_BumpMap", "Texture"); DoSlider("_BumpFace", "Face"); DoSlider("_BumpOutline", "Outline"); EditorGUI.indentLevel -= 1; EditorGUILayout.Space(); } void DoEnvMapPanel() { EditorGUI.indentLevel += 1; DoColor("_ReflectFaceColor", "Face Color"); DoColor("_ReflectOutlineColor", "Outline Color"); DoCubeMap("_Cube", "Texture"); DoVector3("_EnvMatrixRotation", "Rotation"); EditorGUI.indentLevel -= 1; EditorGUILayout.Space(); } void DoGlowPanel() { EditorGUI.indentLevel += 1; DoColor("_GlowColor", "Color"); DoSlider("_GlowOffset", "Offset"); DoSlider("_GlowInner", "Inner"); DoSlider("_GlowOuter", "Outer"); DoSlider("_GlowPower", "Power"); EditorGUI.indentLevel -= 1; EditorGUILayout.Space(); } void DoDebugPanel() { EditorGUI.indentLevel += 1; DoTexture2D("_MainTex", "Font Atlas"); DoFloat("_GradientScale", "Gradient Scale"); DoFloat("_TextureWidth", "Texture Width"); DoFloat("_TextureHeight", "Texture Height"); EditorGUILayout.Space(); DoFloat("_ScaleX", "Scale X"); DoFloat("_ScaleY", "Scale Y"); if (m_Material.HasProperty(TextShaderUtilities.ID_Sharpness)) DoSlider("_Sharpness", "Sharpness"); DoSlider("_PerspectiveFilter", "Perspective Filter"); EditorGUILayout.Space(); DoFloat("_VertexOffsetX", "Offset X"); DoFloat("_VertexOffsetY", "Offset Y"); if (m_Material.HasProperty(TextShaderUtilities.ID_MaskCoord)) { EditorGUILayout.Space(); s_MaskFeature.ReadState(m_Material); s_MaskFeature.DoPopup(m_Editor, m_Material); if (s_MaskFeature.Active) { DoMaskSubgroup(); } EditorGUILayout.Space(); DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels); } else if (m_Material.HasProperty("_MaskTex")) { DoMaskTexSubgroup(); } else if (m_Material.HasProperty(TextShaderUtilities.ID_MaskSoftnessX)) { EditorGUILayout.Space(); DoFloat("_MaskSoftnessX", "Softness X"); DoFloat("_MaskSoftnessY", "Softness Y"); DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels); } if (m_Material.HasProperty(TextShaderUtilities.ID_StencilID)) { EditorGUILayout.Space(); DoFloat("_Stencil", "Stencil ID"); DoFloat("_StencilComp", "Stencil Comp"); } EditorGUILayout.Space(); EditorGUI.BeginChangeCheck(); bool useRatios = EditorGUILayout.Toggle("Use Ratios", !m_Material.IsKeywordEnabled("RATIOS_OFF")); if (EditorGUI.EndChangeCheck()) { m_Editor.RegisterPropertyChangeUndo("Use Ratios"); if (useRatios) { m_Material.DisableKeyword("RATIOS_OFF"); } else { m_Material.EnableKeyword("RATIOS_OFF"); } } if (m_Material.HasProperty(TextShaderUtilities.ShaderTag_CullMode)) { EditorGUILayout.Space(); DoPopup("_CullMode", "Cull Mode", s_CullingTypeLabels); } EditorGUILayout.Space(); EditorGUI.BeginDisabledGroup(true); DoFloat("_ScaleRatioA", "Scale Ratio A"); DoFloat("_ScaleRatioB", "Scale Ratio B"); DoFloat("_ScaleRatioC", "Scale Ratio C"); EditorGUI.EndDisabledGroup(); EditorGUI.indentLevel -= 1; EditorGUILayout.Space(); } void DoDebugPanelSRP() { EditorGUI.indentLevel += 1; DoTexture2D("_MainTex", "Font Atlas"); DoFloat("_GradientScale", "Gradient Scale"); //DoFloat("_TextureWidth", "Texture Width"); //DoFloat("_TextureHeight", "Texture Height"); EditorGUILayout.Space(); /* DoFloat("_ScaleX", "Scale X"); DoFloat("_ScaleY", "Scale Y"); if (m_Material.HasProperty(TextShaderUtilities.ID_Sharpness)) DoSlider("_Sharpness", "Sharpness"); DoSlider("_PerspectiveFilter", "Perspective Filter"); EditorGUILayout.Space(); DoFloat("_VertexOffsetX", "Offset X"); DoFloat("_VertexOffsetY", "Offset Y"); if (m_Material.HasProperty(TextShaderUtilities.ID_MaskCoord)) { EditorGUILayout.Space(); s_MaskFeature.ReadState(m_Material); s_MaskFeature.DoPopup(m_Editor, m_Material); if (s_MaskFeature.Active) { DoMaskSubgroup(); } EditorGUILayout.Space(); DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels); } else if (m_Material.HasProperty("_MaskTex")) { DoMaskTexSubgroup(); } else if (m_Material.HasProperty(TextShaderUtilities.ID_MaskSoftnessX)) { EditorGUILayout.Space(); DoFloat("_MaskSoftnessX", "Softness X"); DoFloat("_MaskSoftnessY", "Softness Y"); DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels); } if (m_Material.HasProperty(TextShaderUtilities.ID_StencilID)) { EditorGUILayout.Space(); DoFloat("_Stencil", "Stencil ID"); DoFloat("_StencilComp", "Stencil Comp"); } EditorGUILayout.Space(); EditorGUI.BeginChangeCheck(); bool useRatios = EditorGUILayout.Toggle("Use Ratios", !m_Material.IsKeywordEnabled("RATIOS_OFF")); if (EditorGUI.EndChangeCheck()) { m_Editor.RegisterPropertyChangeUndo("Use Ratios"); if (useRatios) { m_Material.DisableKeyword("RATIOS_OFF"); } else { m_Material.EnableKeyword("RATIOS_OFF"); } } */ if (m_Material.HasProperty(TextShaderUtilities.ShaderTag_CullMode)) { EditorGUILayout.Space(); DoPopup("_CullMode", "Cull Mode", s_CullingTypeLabels); } EditorGUILayout.Space(); /* EditorGUI.BeginDisabledGroup(true); DoFloat("_ScaleRatioA", "Scale Ratio A"); DoFloat("_ScaleRatioB", "Scale Ratio B"); DoFloat("_ScaleRatioC", "Scale Ratio C"); EditorGUI.EndDisabledGroup(); */ EditorGUI.indentLevel -= 1; EditorGUILayout.Space(); } void DoMaskSubgroup() { DoVector("_MaskCoord", "Mask Bounds", s_XywhVectorLabels); if (Selection.activeGameObject != null) { Renderer renderer = Selection.activeGameObject.GetComponent<Renderer>(); if (renderer != null) { Rect rect = EditorGUILayout.GetControlRect(); rect.x += EditorGUIUtility.labelWidth; rect.width -= EditorGUIUtility.labelWidth; if (GUI.Button(rect, "Match Renderer Bounds")) { FindProperty("_MaskCoord", m_Properties).vectorValue = new Vector4( 0, 0, Mathf.Round(renderer.bounds.extents.x * 1000) / 1000, Mathf.Round(renderer.bounds.extents.y * 1000) / 1000 ); } } } if (s_MaskFeature.State == 1) { DoFloat("_MaskSoftnessX", "Softness X"); DoFloat("_MaskSoftnessY", "Softness Y"); } } void DoMaskTexSubgroup() { EditorGUILayout.Space(); DoTexture2D("_MaskTex", "Mask Texture"); DoToggle("_MaskInverse", "Inverse Mask"); DoColor("_MaskEdgeColor", "Edge Color"); DoSlider("_MaskEdgeSoftness", "Edge Softness"); DoSlider("_MaskWipeControl", "Wipe Position"); DoFloat("_MaskSoftnessX", "Softness X"); DoFloat("_MaskSoftnessY", "Softness Y"); DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels); } } }
UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/TextCoreShaderGUISDF.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/TextCoreShaderGUISDF.cs", "repo_id": "UnityCsReference", "token_count": 14843 }
478
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine.Scripting; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; namespace UnityEngine.Tilemaps { [RequiredByNativeCode] public class ITilemap { internal static ITilemap s_Instance; internal Tilemap m_Tilemap; internal bool m_AddToList; internal int m_RefreshCount; internal NativeArray<Vector3Int> m_RefreshPos; internal ITilemap() { } public ITilemap(Tilemap tilemap) { if (tilemap == null) throw new ArgumentNullException("Argument tilemap cannot be null"); m_Tilemap = tilemap; } public static implicit operator ITilemap(Tilemap tilemap) { return new ITilemap(tilemap); } internal void SetTilemapInstance(Tilemap tilemap) { m_Tilemap = tilemap; } // Tilemap public Vector3Int origin { get { return m_Tilemap.origin; } } public Vector3Int size { get { return m_Tilemap.size; } } public Bounds localBounds { get { return m_Tilemap.localBounds; } } public BoundsInt cellBounds { get { return m_Tilemap.cellBounds; } } // Tile public virtual Sprite GetSprite(Vector3Int position) { return m_Tilemap.GetSprite(position); } public virtual Color GetColor(Vector3Int position) { return m_Tilemap.GetColor(position); } public virtual Matrix4x4 GetTransformMatrix(Vector3Int position) { return m_Tilemap.GetTransformMatrix(position); } public virtual TileFlags GetTileFlags(Vector3Int position) { return m_Tilemap.GetTileFlags(position); } // Tile Assets public virtual TileBase GetTile(Vector3Int position) { return m_Tilemap.GetTile(position); } public virtual T GetTile<T>(Vector3Int position) where T : TileBase { return m_Tilemap.GetTile<T>(position); } public void RefreshTile(Vector3Int position) { if (m_AddToList) { if (m_RefreshCount >= m_RefreshPos.Length) { var refreshPos = new NativeArray<Vector3Int>(Math.Max(1, m_RefreshCount * 2), Allocator.Temp); NativeArray<Vector3Int>.Copy(m_RefreshPos, refreshPos, m_RefreshPos.Length); m_RefreshPos.Dispose(); m_RefreshPos = refreshPos; } m_RefreshPos[m_RefreshCount++] = position; } else m_Tilemap.RefreshTile(position); } public T GetComponent<T>() { if (typeof(T) == typeof(Tilemap)) { return (T)(System.Object)m_Tilemap; } return m_Tilemap.GetComponent<T>(); } [RequiredByNativeCode] private static ITilemap CreateInstance() { s_Instance = new ITilemap(); return s_Instance; } [RequiredByNativeCode] private static unsafe void FindAllRefreshPositions(ITilemap tilemap, int count, IntPtr oldTilesIntPtr, IntPtr newTilesIntPtr, IntPtr positionsIntPtr) { tilemap.m_AddToList = true; if (tilemap.m_RefreshPos == null || !tilemap.m_RefreshPos.IsCreated || tilemap.m_RefreshPos.Length < count) tilemap.m_RefreshPos = new NativeArray<Vector3Int>(Math.Max(16, count), Allocator.Temp); tilemap.m_RefreshCount = 0; var oldTilesPtr = oldTilesIntPtr.ToPointer(); var newTilesPtr = newTilesIntPtr.ToPointer(); var positionsPtr = positionsIntPtr.ToPointer(); var oldTilesIds = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<int>(oldTilesPtr, count, Allocator.Invalid); var newTilesIds = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<int>(newTilesPtr, count, Allocator.Invalid); var positions = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<Vector3Int>(positionsPtr, count, Allocator.Invalid); var ash1 = AtomicSafetyHandle.Create(); var ash2 = AtomicSafetyHandle.Create(); var ash3 = AtomicSafetyHandle.Create(); NativeArrayUnsafeUtility.SetAtomicSafetyHandle<int>(ref oldTilesIds, ash1); NativeArrayUnsafeUtility.SetAtomicSafetyHandle<int>(ref newTilesIds, ash2); NativeArrayUnsafeUtility.SetAtomicSafetyHandle<Vector3Int>(ref positions, ash3); for (int i = 0; i < count; ++i) { var oldTileId = oldTilesIds[i]; var newTileId = newTilesIds[i]; var position = positions[i]; if (oldTileId != 0) { var tile = (TileBase)Object.ForceLoadFromInstanceID(oldTileId); tile.RefreshTile(position, tilemap); } if (newTileId != 0) { var tile = (TileBase)Object.ForceLoadFromInstanceID(newTileId); tile.RefreshTile(position, tilemap); } } tilemap.m_Tilemap.RefreshTilesNative(tilemap.m_RefreshPos.m_Buffer, tilemap.m_RefreshCount); tilemap.m_RefreshPos.Dispose(); tilemap.m_AddToList = false; AtomicSafetyHandle.Release(ash1); AtomicSafetyHandle.Release(ash2); AtomicSafetyHandle.Release(ash3); } [RequiredByNativeCode] private unsafe static void GetAllTileData(ITilemap tilemap, int count, IntPtr tilesIntPtr, IntPtr positionsIntPtr, IntPtr outTileDataIntPtr) { void* tilesPtr = tilesIntPtr.ToPointer(); void* positionsPtr = positionsIntPtr.ToPointer(); void* outTileDataPtr = outTileDataIntPtr.ToPointer(); var tiles = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<int>(tilesPtr, count, Allocator.Invalid); var positions = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<Vector3Int>(positionsPtr, count, Allocator.Invalid); var tileDataArray = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<TileData>(outTileDataPtr, count, Allocator.Invalid); var ash1 = AtomicSafetyHandle.Create(); var ash2 = AtomicSafetyHandle.Create(); var ash3 = AtomicSafetyHandle.Create(); NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref tiles, ash1); NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref positions, ash2); NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref tileDataArray, ash3); for (int i = 0; i < count; ++i) { TileData tileData = TileData.Default; var tileId = tiles[i]; if (tileId != 0) { TileBase tile = (TileBase)Object.ForceLoadFromInstanceID(tileId); tile.GetTileData(positions[i], tilemap, ref tileData); } tileDataArray[i] = tileData; } AtomicSafetyHandle.Release(ash1); AtomicSafetyHandle.Release(ash2); AtomicSafetyHandle.Release(ash3); } } }
UnityCsReference/Modules/Tilemap/Managed/ITilemap.cs/0
{ "file_path": "UnityCsReference/Modules/Tilemap/Managed/ITilemap.cs", "repo_id": "UnityCsReference", "token_count": 3527 }
479
// 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 TreeEditor { public class TreeAOSphere { public bool flag; public float area; public float radius; public float density = 1.0f; public Vector3 position; public TreeAOSphere(Vector3 pos, float radius, float density) { this.position = pos; this.radius = radius; this.area = radius * radius; // PI factored out.. this.density = density; } public float PointOcclusion(Vector3 pos, Vector3 nor) { Vector3 delta = position - pos; float ds = delta.sqrMagnitude; float d2 = Mathf.Max(0.0f, ds - area); if (ds > Mathf.Epsilon) { delta.Normalize(); } return (1.0f - (1.0f / Mathf.Sqrt(area / d2 + 1))) * Mathf.Clamp01(4.0f * Vector3.Dot(nor, delta)); } } }
UnityCsReference/Modules/TreeEditor/Includes/TreeAOSphere.cs/0
{ "file_path": "UnityCsReference/Modules/TreeEditor/Includes/TreeAOSphere.cs", "repo_id": "UnityCsReference", "token_count": 517 }
480
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine.Bindings; namespace UnityEngine { [NativeHeader("Runtime/Camera/Camera.h"), NativeHeader("Modules/UI/Canvas.h"), NativeHeader("Modules/UI/RectTransformUtil.h"), NativeHeader("Runtime/Transform/RectTransform.h"), StaticAccessor("UI", StaticAccessorType.DoubleColon)] partial class RectTransformUtility { public static extern Vector2 PixelAdjustPoint(Vector2 point, Transform elementTransform, Canvas canvas); public static extern Rect PixelAdjustRect(RectTransform rectTransform, Canvas canvas); private static extern bool PointInRectangle(Vector2 screenPoint, RectTransform rect, Camera cam, Vector4 offset); } }
UnityCsReference/Modules/UI/ScriptBindings/RectTransformUtil.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/UI/ScriptBindings/RectTransformUtil.bindings.cs", "repo_id": "UnityCsReference", "token_count": 264 }
481
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Reflection; using UnityEditor; using UnityEngine; using UnityEngine.UIElements; using UnityEngine.UIElements.StyleSheets; namespace Unity.UI.Builder { internal enum BuilderSelectionType { Nothing, Element, StyleSheet, StyleSelector, ParentStyleSelector, ElementInTemplateInstance, ElementInControlInstance, VisualTreeAsset, ElementInParentDocument } [Flags] internal enum BuilderHierarchyChangeType { ChildrenAdded = 1 << 0, ChildrenRemoved = 1 << 1, Attributes = 1 << 2, ElementName = 1 << 3, ClassList = 1 << 4, InlineStyle = 1 << 5, FullRefresh = 1 << 6, // Skip this flag if you want to avoid expensive refresh during changes (ex. on drag operations) All = ~0 } internal enum BuilderStylingChangeType { Default, RefreshOnly } internal interface IBuilderSelectionNotifier { void SelectionChanged(); void HierarchyChanged(VisualElement element, BuilderHierarchyChangeType changeType); void StylingChanged(List<string> styles, BuilderStylingChangeType changeType); } internal class BuilderSelection { static readonly StylePropertyReader s_StylePropertyReader = new StylePropertyReader(); List<IBuilderSelectionNotifier> m_Notifiers; IBuilderSelectionNotifier m_CurrentNotifier; List<string> m_CurrentStyleList; BuilderStylingChangeType m_CurrentChangeType; Action m_NextPostStylingAction; VisualElement m_Root; BuilderPaneWindow m_PaneWindow; VisualElement m_DocumentRootElement; VisualElement m_DummyElementForStyleChangeNotifications; public BuilderSelectionType selectionType { get { if (m_Selection.Count == 0) return BuilderSelectionType.Nothing; var selectedElement = m_Selection[0]; if (BuilderSharedStyles.IsDocumentElement(selectedElement)) return BuilderSelectionType.VisualTreeAsset; if (BuilderSharedStyles.IsParentSelectorElement(selectedElement)) return BuilderSelectionType.ParentStyleSelector; if (BuilderSharedStyles.IsSelectorElement(selectedElement)) return BuilderSelectionType.StyleSelector; if (BuilderSharedStyles.IsStyleSheetElement(selectedElement)) return BuilderSelectionType.StyleSheet; if (selectedElement.GetVisualElementAsset() == null) { if (selectedElement.HasProperty(VisualTreeAsset.LinkedVEAInTemplatePropertyName) && BuilderAssetUtilities.GetVisualElementRootTemplate(selectedElement) != null && !BuilderAssetUtilities.HasDynamicallyCreatedTemplateAncestor(selectedElement)) { return BuilderSelectionType.ElementInTemplateInstance; } return BuilderSelectionType.ElementInControlInstance; } if (selectedElement.IsPartOfActiveVisualTreeAsset(m_PaneWindow.document)) return BuilderSelectionType.Element; return BuilderSelectionType.ElementInParentDocument; } } List<VisualElement> m_Selection; public int selectionCount => m_Selection.Count; public IEnumerable<VisualElement> selection => m_Selection; public VisualElement documentRootElement { get { return m_DocumentRootElement; } set { m_DocumentRootElement = value; } } public bool isEmpty { get { return m_Selection.Count == 0; } } public BuilderSelection(VisualElement root, BuilderPaneWindow paneWindow) { m_Notifiers = new List<IBuilderSelectionNotifier>(); m_Selection = new List<VisualElement>(); m_Root = root; m_PaneWindow = paneWindow; m_DummyElementForStyleChangeNotifications = new VisualElement(); m_DummyElementForStyleChangeNotifications.name = "unity-dummy-element-for-style-change-notifications"; m_DummyElementForStyleChangeNotifications.style.position = Position.Absolute; m_DummyElementForStyleChangeNotifications.style.top = -1000; m_DummyElementForStyleChangeNotifications.style.left = -1000; m_DummyElementForStyleChangeNotifications.style.width = 1; m_DummyElementForStyleChangeNotifications.RegisterCallback<GeometryChangedEvent>(AfterPanelUpdaterChange); m_Root.Add(m_DummyElementForStyleChangeNotifications); } public void AssignNotifiers(IEnumerable<IBuilderSelectionNotifier> notifiers) { m_Notifiers.Clear(); foreach (var notifier in notifiers) m_Notifiers.Add(notifier); } public void AddNotifier(IBuilderSelectionNotifier notifier) { if (!m_Notifiers.Contains(notifier)) m_Notifiers.Add(notifier); } public void RemoveNotifier(IBuilderSelectionNotifier notifier) { m_Notifiers.Remove(notifier); } public void ForceReselection(IBuilderSelectionNotifier source = null) { NotifyOfSelectionChange(source); } public void Select(IBuilderSelectionNotifier source, VisualElement ve) { if (ve == null) return; foreach (var sel in m_Selection) { if (sel == null) continue; BuilderAssetUtilities.RemoveElementFromSelectionInAsset(m_PaneWindow.document, sel); } m_Selection.Clear(); m_Selection.Add(ve); BuilderAssetUtilities.AddElementToSelectionInAsset(m_PaneWindow.document, ve); NotifyOfSelectionChange(source); } public void AddToSelection(IBuilderSelectionNotifier source, VisualElement ve) { AddToSelection(source, ve, true, true); } void AddToSelection(IBuilderSelectionNotifier source, VisualElement ve, bool undo, bool sort) { if (ve == null) return; m_Selection.Add(ve); if (sort) SortSelection(); if (undo) BuilderAssetUtilities.AddElementToSelectionInAsset(m_PaneWindow.document, ve); NotifyOfSelectionChange(source); } public void RemoveFromSelection(IBuilderSelectionNotifier source, VisualElement ve) { m_Selection.Remove(ve); BuilderAssetUtilities.RemoveElementFromSelectionInAsset(m_PaneWindow.document, ve); NotifyOfSelectionChange(source); } public void ClearSelection(IBuilderSelectionNotifier source, bool undo = true) { if (isEmpty) return; if (undo) foreach (var sel in m_Selection) BuilderAssetUtilities.RemoveElementFromSelectionInAsset(m_PaneWindow.document, sel); m_Selection.Clear(); NotifyOfSelectionChange(source); } public void RestoreSelectionFromDocument(VisualElement sharedStylesAndDocumentElement) { ClearSelection(null, false); var selectedElements = sharedStylesAndDocumentElement.FindSelectedElements(); foreach (var selectedElement in selectedElements) AddToSelection(null, selectedElement, false, false); SortSelection(); } public void NotifyOfHierarchyChange( IBuilderSelectionNotifier source = null, VisualElement element = null, BuilderHierarchyChangeType changeType = BuilderHierarchyChangeType.All) { ForceVisualAssetUpdateWithoutSave(element, changeType); // This is so anyone interested can refresh their use of this UXML with // the latest (unsaved to disk) changes. EditorUtility.SetDirty(m_PaneWindow.document.visualTreeAsset); foreach (var notifier in m_Notifiers) if (notifier != source) notifier.HierarchyChanged(element, changeType); if (hasUnsavedChanges && !isAnonymousDocument) { var liveReloadChanges = ((changeType & BuilderHierarchyChangeType.InlineStyle) != 0 ? BuilderAssetUtilities.LiveReloadChanges.Styles : 0) | ((changeType & ~BuilderHierarchyChangeType.InlineStyle) != 0 ? BuilderAssetUtilities.LiveReloadChanges.Hierarchy : 0); BuilderAssetUtilities.LiveReload(liveReloadChanges); } } internal void ForceVisualAssetUpdateWithoutSave( VisualElement element = null, BuilderHierarchyChangeType changeType = BuilderHierarchyChangeType.All) { if (m_Notifiers == null || m_Notifiers.Count == 0) return; VisualElementAsset vea = element?.GetVisualElementAsset(); if (vea != null && vea.ruleIndex >= 0 && changeType.HasFlag(BuilderHierarchyChangeType.InlineStyle)) { var vta = m_PaneWindow.document.visualTreeAsset; var rule = vta.GetOrCreateInlineStyleRule(vea); element.UpdateInlineRule(vta.inlineSheet, rule); // Need to enforce this specific style is updated. element.IncrementVersion(VersionChangeType.Opacity | VersionChangeType.Overflow | VersionChangeType.StyleSheet); } else if (m_DocumentRootElement != null) { m_PaneWindow.document.RefreshStyle(m_DocumentRootElement); } } public void NotifyOfStylingChange(IBuilderSelectionNotifier source = null, List<string> styles = null, BuilderStylingChangeType changeType = BuilderStylingChangeType.Default) { if (m_Notifiers == null || m_Notifiers.Count == 0) return; if (m_DocumentRootElement != null) m_PaneWindow.document.RefreshStyle(m_DocumentRootElement); m_CurrentNotifier = source; m_CurrentStyleList = styles; m_CurrentChangeType = changeType; QueueUpPostPanelUpdaterChangeAction(NotifyOfStylingChangePostStylingUpdate); } void NotifyOfSelectionChange(IBuilderSelectionNotifier source) { if (m_Notifiers == null || m_Notifiers.Count == 0) return; if (m_DocumentRootElement != null) m_PaneWindow.document.RefreshStyle(m_DocumentRootElement); foreach (var notifier in m_Notifiers) if (notifier != source) notifier.SelectionChanged(); } public void NotifyOfStylingChangePostStylingUpdate() { // This is so anyone interested can refresh their use of this USS with // the latest (unsaved to disk) changes. //RetainedMode.FlagStyleSheetChange(); // Works but TOO SLOW. m_PaneWindow.document.MarkStyleSheetsDirty(); foreach (var notifier in m_Notifiers) if (notifier != m_CurrentNotifier) notifier.StylingChanged(m_CurrentStyleList, m_CurrentChangeType); if (hasUnsavedChanges && !isAnonymousDocument) { BuilderAssetUtilities.LiveReload(BuilderAssetUtilities.LiveReloadChanges.Styles); } m_CurrentNotifier = null; m_CurrentStyleList = null; } void QueueUpPostPanelUpdaterChangeAction(Action action) { m_NextPostStylingAction = action; if (m_DummyElementForStyleChangeNotifications.resolvedStyle.width > 0) m_DummyElementForStyleChangeNotifications.style.width = -1; else m_DummyElementForStyleChangeNotifications.style.width = 1; } void AfterPanelUpdaterChange(GeometryChangedEvent evt) { if (m_NextPostStylingAction == null) return; m_NextPostStylingAction(); m_NextPostStylingAction = null; } int GetSelectedItemOrder(VisualElement element) { var vea = element.GetVisualElementAsset(); if (vea != null) return vea.orderInDocument; var selector = element.GetStyleComplexSelector(); if (selector != null) { var styleSheetElement = element.parent; var styleSheetIndex = styleSheetElement.parent.IndexOf(styleSheetElement); var elementIndex = styleSheetElement.IndexOf(element); return (styleSheetIndex * 10000) + elementIndex; } return 0; } void SortSelection() { if (m_Selection.Count <= 1) return; m_Selection.Sort((left, right) => { var leftOrder = GetSelectedItemOrder(left); var rightOrder = GetSelectedItemOrder(right); return leftOrder.CompareTo(rightOrder); }); } public bool hasUnsavedChanges { get { return m_PaneWindow.document.hasUnsavedChanges; } private set { m_PaneWindow.document.hasUnsavedChanges = value; } } public void ResetUnsavedChanges() { hasUnsavedChanges = false; } private bool isAnonymousDocument { get { return m_PaneWindow.document.activeOpenUXMLFile.isAnonymousDocument; } } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/BuilderSelection.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/BuilderSelection.cs", "repo_id": "UnityCsReference", "token_count": 6562 }
482
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine.UIElements; namespace Unity.UI.Builder { internal static class BuilderHierarchyUtilities { public static bool OpenAsSubDocument(BuilderPaneWindow paneWindow, VisualTreeAsset vta, TemplateAsset vea = null) { bool didSaveChanges = paneWindow.document.CheckForUnsavedChanges(); if (!didSaveChanges) return false; // This is important because if the user chose to not save changes to the // parent document, we restore the VTA from backup. The problem with that // is that the backup VTA was made before we fixed any USS assignments on // root elements. This is fine when simply restoring the backup before a // File > New or switching documents (just prior to closing the current document), // but this is not ok here because we need the parent document to continue // staying open and usable in the UI Builder. paneWindow.document.activeOpenUXMLFile.PostLoadDocumentStyleSheetCleanup(); paneWindow.document.AddSubDocument(vea); paneWindow.LoadDocument(vta, false); return true; } // Specific to ToggleButtonGroup for now, but the idea is to be able to retrieve specific content containers // for those controls that are designed to group a specific type(s) of control(s). public static VisualElement GetToggleButtonGroupContentContainer(VisualElement element) { // Once we have a better way to do this, we should enhance and make this more generic as other control that // act as containers would benefit greatly from this. This is also specific for the builder authoring // workflow. if (element is ToggleButtonGroup toggleButtonGroup) return toggleButtonGroup.Q<VisualElement>(className: ToggleButtonGroup.buttonGroupClassName); return null; } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Explorer/BuilderHierarchyUtilities.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Explorer/BuilderHierarchyUtilities.cs", "repo_id": "UnityCsReference", "token_count": 746 }
483
// Unity 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 UnityEditor.UIElements; using UnityEngine; using UnityEngine.UIElements; using Object = UnityEngine.Object; using UIEHelpBox = UnityEngine.UIElements.HelpBox; namespace Unity.UI.Builder { /// <summary> /// Provides a view to the data source, data source type and binding path property of a VisualElement and a Binding. /// </summary> internal class BuilderDataSourceAndPathView : BuilderUxmlAttributesView { internal const string k_BindingAttr_DataSource = "data-source"; internal const string k_BindingAttr_DataSourceType = "data-source-type"; internal const string k_BindingAttr_DataSourcePath = "data-source-path"; internal const string k_DataSourceObjectTooltip = "Add an object to use as the data source for this binding."; internal const string k_DataSourceTypeTooltip = "If a source is not yet available, a data source type can be defined. It may provide assistance while authoring by populating the data source path field with options."; internal struct TestAccess { public BuilderObjectField dataSourceField; public BaseField<string> dataSourceTypeField; public TextField dataSourcePathField; public BuilderDataSourcePathCompleter dataSourcePathCompleter; public UIEHelpBox dataSourceWarningBox; public UIEHelpBox pathWarningBox; } // Note: They are internal only to be accessible in tests internal TestAccess testAccess => new() { dataSourceField = m_DataSourceField, dataSourceTypeField = m_DataSourceTypeField, dataSourcePathField = m_DataSourcePathField, dataSourcePathCompleter = m_DataSourcePathCompleter, dataSourceWarningBox = m_DataSourceWarningBox, pathWarningBox = m_PathWarningBox, }; PersistedFoldout m_BindingsFoldout; ToggleButtonGroup m_ButtonStrip; VisualElement m_SourceWidgetContainer; VisualElement m_AssetFieldContainer; VisualElement m_TypeFieldContainer; VisualElement m_PathFieldContainer; protected BuilderObjectField m_DataSourceField; protected BaseField<string> m_DataSourceTypeField; protected TextField m_DataSourcePathField; BuilderDataSourcePathCompleter m_DataSourcePathCompleter; UIEHelpBox m_DataSourceWarningBox; UIEHelpBox m_PathWarningBox; private IVisualElementScheduledItem m_UpdateControlsScheduledItem; /// <summary> /// The data source to bind. /// </summary> public Object dataSource => m_DataSourceField?.value; /// <summary> /// Gets data source inherited from the selected VisualElement. /// </summary> public object inheritedDataSource { get { var startingElement = isBinding ? Builder.ActiveWindow.inspector.attributesSection.currentElement : currentElement.parent; if (startingElement == null) return null; DataBindingUtility.TryGetRelativeDataSourceFromHierarchy(startingElement, out var source); return source; } } /// <summary> /// The type of the possible data source to bind. /// </summary> public Type dataSourceType { get { var fullTypeName = m_DataSourceTypeField?.value; if (!string.IsNullOrEmpty(fullTypeName)) return Type.GetType(fullTypeName); return null; } } /// <summary> /// Gets data source type inherited from the selected VisualElement. /// </summary> public Type inheritedDataSourceType { get { var startingElement = isBinding ? Builder.ActiveWindow.inspector.attributesSection.currentElement : currentElement.parent; if (startingElement == null) return null; DataBindingUtility.TryGetRelativeDataSourceTypeFromHierarchy(startingElement, out var sourceType); return sourceType; } } /// <summary> /// The data source path to property of the data source to bind. /// </summary> public string dataSourcePath => m_DataSourcePathField?.text; public string bindingSerializedPropertyPathRoot { get; set; } public UxmlSerializedDataDescription bindingUxmlSerializedDataDescription { get; set; } public UxmlSerializedDataDescription uxmlSerializedDataDescription => bindingUxmlSerializedDataDescription ?? m_SerializedDataDescription; protected bool isBinding => bindingUxmlSerializedDataDescription != null; /// <summary> /// Notifies attributes have changed. /// </summary> public Action onNotifyAttributesChanged; /// <inheritdoc/> protected override bool IsAttributeIgnored(UxmlAttributeDescription attribute) => true; protected override BindableElement CreateTraitsAttributeField(UxmlAttributeDescription attribute) { var field = base.CreateTraitsAttributeField(attribute); UpdateAttribute(field, attribute.name); return field; } protected override BuilderStyleRow CreateSerializedAttributeRow(UxmlSerializedAttributeDescription attribute, string propertyPath, VisualElement parent = null) { var row = base.CreateSerializedAttributeRow(attribute, propertyPath, parent); row.Q<PropertyField>()?.RegisterCallback<SerializedPropertyBindEvent, string>(OnPropertyFieldBound, attribute.name); return row; } void OnPropertyFieldBound(SerializedPropertyBindEvent evt, string attributeName) { var target = evt.elementTarget; var bindingAttribute = attributeName; fieldsContainer.schedule.Execute(() => { UpdateAttribute(target, bindingAttribute); if (target?.panel == null) return; UpdateFieldStatus(target); }); } /// <inheritdoc/> protected override object GetAttributeValue(UxmlAttributeDescription attribute) { var attributeValue = base.GetAttributeValue(attribute); if (attribute.name is k_BindingAttr_DataSource) { return attributeValue ?? inheritedDataSource; } if (attribute.name is k_BindingAttr_DataSourceType) { return attributeValue ?? inheritedDataSourceType; } return attributeValue; } protected virtual void UpdateAttribute(VisualElement target, string bindingAttribute) { switch (bindingAttribute) { case k_BindingAttr_DataSource: m_DataSourceField = target.Q<BuilderObjectField>(); if (m_DataSourceField.value == null) { m_DataSourceField.SetObjectWithoutNotify(inheritedDataSource); } UpdateWarningBox(); UpdateCompleter(); UpdateFoldoutOverride(); break; case k_BindingAttr_DataSourceType: m_DataSourceTypeField = target.Q<BaseField<string>>(); if (string.IsNullOrEmpty(m_DataSourceTypeField.value)) { var type = inheritedDataSourceType; if (type != null) { m_DataSourceTypeField.SetValueWithoutNotify(type.GetFullNameWithAssembly()); } } UpdateCompleter(); UpdateFoldoutOverride(); break; case k_BindingAttr_DataSourcePath: m_DataSourcePathField = target.Q<TextField>(); m_DataSourcePathField.isDelayed = true; m_DataSourcePathCompleter = new BuilderDataSourcePathCompleter(m_DataSourcePathField); UpdateCompleter(); UpdateFoldoutOverride(); break; } } /// <inheritdoc/> protected override void GenerateUxmlTraitsAttributeFields() { GenerateDataBindingFields(fieldsContainer); UpdateControls(); } /// <inheritdoc/> protected override void GenerateSerializedAttributeFields() { var path = bindingSerializedPropertyPathRoot == null ? serializedRootPath : bindingSerializedPropertyPathRoot + "."; var root = new UxmlAssetSerializedDataRoot { dataDescription = uxmlSerializedDataDescription, rootPath = path, classList = { InspectorElement.ussClassName }}; fieldsContainer.Add(root); GenerateDataBindingFields(root); } void GenerateDataBindingFields(VisualElement root) { if (m_BindingsFoldout == null) { m_BindingsFoldout = new PersistedFoldout() { text = "Bindings", classList = { PersistedFoldout.unindentedUssClassName } }; m_ButtonStrip = new ToggleButtonGroup("Data Source"); m_ButtonStrip.Add(new Button { text = "Object", style = { flexGrow = 1 }, tooltip = k_DataSourceObjectTooltip }); m_ButtonStrip.Add(new Button { text = "Type", style = { flexGrow = 1 }, tooltip = k_DataSourceTypeTooltip}); m_ButtonStrip.isMultipleSelection = false; m_ButtonStrip.AddToClassList(ToggleButtonGroup.alignedFieldUssClassName); m_ButtonStrip.RegisterValueChangedCallback(evt => SetSourceVisibility(evt.newValue[0])); m_BindingsFoldout.Add(m_ButtonStrip); m_BindingsFoldout.Add(m_SourceWidgetContainer = new VisualElement() { style = { flexGrow = 1 } }); } else { m_DataSourceField = null; m_DataSourceTypeField = null; m_DataSourcePathField = null; m_DataSourcePathCompleter = null; m_SourceWidgetContainer?.Clear(); m_PathFieldContainer?.RemoveFromHierarchy(); m_DataSourceWarningBox?.RemoveFromHierarchy(); } if (isBinding) { root.Add(m_SourceWidgetContainer); } else { root.Add(m_BindingsFoldout); } // We create a style row and share it between the two data source fields (hackish) var styleRow = CreateAttributeRow(k_BindingAttr_DataSource, m_SourceWidgetContainer); m_AssetFieldContainer = styleRow.GetLinkedFieldElements()[0]; m_AssetFieldContainer.parent.Insert(0, m_ButtonStrip); // Only create the field and link it to the builder style row created above m_TypeFieldContainer = CreateAttributeField(k_BindingAttr_DataSourceType); m_AssetFieldContainer.parent.Add(m_TypeFieldContainer); var attribute = uxmlSerializedDataDescription?.FindAttributeWithUxmlName(k_BindingAttr_DataSourceType) ?? FindAttribute(k_BindingAttr_DataSourceType); SetupStyleRow(styleRow, m_TypeFieldContainer, attribute); // Show Asset by default. m_ButtonStrip.value = new ToggleButtonGroupState(0b01, 2); SetSourceVisibility(true); if (isBinding) { m_DataSourceWarningBox ??= new UIEHelpBox(BuilderConstants.BindingWindowMissingDataSourceErrorMessage, HelpBoxMessageType.Warning); m_DataSourceWarningBox.style.display = DisplayStyle.None; // Insert the warning box right after the data source field. m_BindingsFoldout.Add(m_DataSourceWarningBox); m_PathFieldContainer = CreateAttributeRow(k_BindingAttr_DataSourcePath, root); } else { m_PathFieldContainer = CreateAttributeRow(k_BindingAttr_DataSourcePath, m_BindingsFoldout); } m_PathWarningBox ??= new UIEHelpBox("", HelpBoxMessageType.Warning); m_PathWarningBox.style.display = DisplayStyle.None; root.Add(m_PathWarningBox); } BuilderStyleRow CreateAttributeRow(string attribute, VisualElement parent) { if (currentFieldSource == AttributeFieldSource.UxmlTraits) { return CreateTraitsAttributeRow(FindAttribute(attribute), parent); } var attributeDesc = uxmlSerializedDataDescription.FindAttributeWithUxmlName(attribute); var path = (bindingSerializedPropertyPathRoot == null ? serializedRootPath : bindingSerializedPropertyPathRoot + ".") + attributeDesc.serializedField.Name; return CreateSerializedAttributeRow(attributeDesc, path, parent); } VisualElement CreateAttributeField(string attribute) { if (currentFieldSource == AttributeFieldSource.UxmlTraits) { return CreateTraitsAttributeField(FindAttribute(attribute)); } var fieldElement = new UxmlSerializedDataAttributeField(); var attributeDesc = uxmlSerializedDataDescription.FindAttributeWithUxmlName(attribute); var path = (bindingSerializedPropertyPathRoot == null ? serializedRootPath : bindingSerializedPropertyPathRoot + ".") + attributeDesc.serializedField.Name; var propertyField = new PropertyField { name = builderSerializedPropertyFieldName, bindingPath = path, label = BuilderNameUtilities.ConvertDashToHuman(attribute) }; propertyField.Bind(m_CurrentElementSerializedObject); if (!readOnly) { TrackElementPropertyValue(propertyField, path); } propertyField.RegisterCallback<SerializedPropertyBindEvent, string>(OnPropertyFieldBound, attribute); fieldElement.Add(propertyField); return fieldElement; } void SetSourceVisibility(bool showAsset) { m_AssetFieldContainer.style.display = showAsset ? DisplayStyle.Flex : DisplayStyle.None; m_TypeFieldContainer.style.display = showAsset ? DisplayStyle.None : DisplayStyle.Flex; } /// <inheritdoc/> protected override void ResetAttributeFieldToDefault(VisualElement fieldElement, UxmlAttributeDescription attribute) { if (m_DataSourceField == fieldElement) { m_DataSourceField.SetObjectWithoutNotify(inheritedDataSource); return; } if (m_DataSourceTypeField == fieldElement) { var type = inheritedDataSourceType; if (type != null) { m_DataSourceTypeField.SetValueWithoutNotify(type.GetFullNameWithAssembly()); return; } } base.ResetAttributeFieldToDefault(fieldElement, attribute); UpdateFieldStatus(fieldElement); } /// <inheritdoc/> protected override void NotifyAttributesChanged(string attributeName = null) { ScheduleUpdateControls(); onNotifyAttributesChanged?.Invoke(); } internal override void UpdateAttributeOverrideStyle(VisualElement fieldElement) { base.UpdateAttributeOverrideStyle(fieldElement); UpdateFoldoutOverride(); } void UpdateFoldoutOverride() { if (m_DataSourceField?.panel == null || m_DataSourceTypeField?.panel == null || m_DataSourcePathField?.panel == null) return; m_BindingsFoldout.EnableInClassList(BuilderConstants.InspectorFoldoutOverrideClassName, IsAttributeOverriden(m_DataSourceField) || IsAttributeOverriden(m_DataSourceTypeField) || IsAttributeOverriden(m_DataSourcePathField)); } /// <inheritdoc/> protected override FieldValueInfo GetValueInfo(VisualElement field) { var valueInfo = base.GetValueInfo(field); var dataSourceIsInherited = false; var dataSourceTypeIsInherited = false; var attributeIsOverriden = IsAttributeOverriden(field); if (!attributeIsOverriden) { var dataSourceRootElement = GetRootFieldElement(m_DataSourceField); var dataSourceTypeRootElement = GetRootFieldElement(m_DataSourceTypeField); // if the data source or the data source type of the target binding is inherited from its VisualElement owner then show the Inherited icon if (dataSourceRootElement == field || dataSourceTypeRootElement == field) { var startingElement = isBinding ? Builder.ActiveWindow.inspector.attributesSection.currentElement : currentElement; if (DataBindingUtility.TryGetDataSourceOrDataSourceTypeFromHierarchy(startingElement, out var dataSource, out var dataSourceType, out _)) { // If the current element is not the one providing the data source, // If the data source set or if the binding path is specified, // and If the data source type is null, then show the inherited status dataSourceIsInherited = dataSource != null && startingElement.dataSource != dataSource && dataSourceType == null; dataSourceTypeIsInherited = dataSource == null && dataSourceType != null; } } if (dataSourceIsInherited || dataSourceTypeIsInherited) { valueInfo.valueSource = new FieldValueSourceInfo(FieldValueSourceInfoType.Inherited); } } return valueInfo; } protected override void BuildAttributeFieldContextualMenu(DropdownMenu menu, BuilderStyleRow styleRow) { var fieldElement = styleRow.GetLinkedFieldElements()[0]; var desc = fieldElement.GetLinkedAttributeDescription(); var currentUxmlAttributeOwner = attributesUxmlOwner; var result = SynchronizePath(bindingSerializedPropertyPathRoot, false); if (isBinding && result.success) { currentUxmlAttributeOwner = result.uxmlAsset; } if (desc.name is k_BindingAttr_DataSource or k_BindingAttr_DataSourceType) { menu.AppendAction( BuilderConstants.ContextMenuUnsetObjectMessage, (a) => UnsetAttributeProperty(m_DataSourceField, false), action => { var attributeName = k_BindingAttr_DataSource; var bindingProperty = GetRemapAttributeNameToCSProperty(k_BindingAttr_DataSource); var isAttributeOverrideAttribute = isInTemplateInstance && BuilderAssetUtilities.HasAttributeOverrideInRootTemplate(currentElement, attributeName); var canUnsetBinding = !isInTemplateInstance && DataBindingUtility.TryGetBinding(currentElement, new PropertyPath(bindingProperty), out _); return (attributesUxmlOwner != null && currentUxmlAttributeOwner.HasAttribute(attributeName)) || isAttributeOverrideAttribute || canUnsetBinding ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled; }, styleRow); menu.AppendAction( BuilderConstants.ContextMenuUnsetTypeMessage, (a) => UnsetAttributeProperty(m_DataSourceTypeField, false), action => { var bindingProperty = GetRemapAttributeNameToCSProperty(k_BindingAttr_DataSourceType); var isAttributeOverrideAttribute = isInTemplateInstance && BuilderAssetUtilities.HasAttributeOverrideInRootTemplate(currentElement, k_BindingAttr_DataSourceType); var canUnsetBinding = !isInTemplateInstance && DataBindingUtility.TryGetBinding(currentElement, new PropertyPath(bindingProperty), out _); return (attributesUxmlOwner != null && currentUxmlAttributeOwner.HasAttribute(k_BindingAttr_DataSourceType)) || isAttributeOverrideAttribute || canUnsetBinding ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled; }, styleRow); } else { base.BuildAttributeFieldContextualMenu(menu, styleRow); } } void ScheduleUpdateControls() { if (m_UpdateControlsScheduledItem == null) { m_UpdateControlsScheduledItem = fieldsContainer.schedule.Execute(UpdateControls); } else { m_UpdateControlsScheduledItem.Pause(); m_UpdateControlsScheduledItem.Resume(); } } /// <summary> /// Updates the state of controls. /// </summary> void UpdateControls() { UpdateCompleter(); UpdateWarningBox(); } void UpdateCompleter() { if (m_DataSourcePathCompleter == null || m_DataSourceField == null || m_DataSourceTypeField == null) return; m_DataSourcePathCompleter.element = currentElement; m_DataSourcePathCompleter.bindingDataSource = dataSource ? dataSource : inheritedDataSource; m_DataSourcePathCompleter.bindingDataSourceType = dataSourceType ?? inheritedDataSourceType; if (bindingSerializedPropertyPathRoot != null) { CallDeserializeOnElement(); using (new DisableUndoScope(this)) { var result = SynchronizePath(bindingSerializedPropertyPathRoot, true); m_DataSourcePathCompleter.binding = result.attributeOwner as DataBinding; } } m_DataSourcePathCompleter.UpdateResults(); } void UpdateWarningBox() { if (m_DataSourceField == null) return; if (m_DataSourceWarningBox != null) m_DataSourceWarningBox.style.display = dataSource == null && dataSourceType == null ? DisplayStyle.Flex : DisplayStyle.None; if (m_PathWarningBox == null) return; string pathWarningMessage = null; if (dataSource != null) { object source = dataSource; if (source is BuilderObjectField.NonUnityObjectValue value) source = value.data; if (!string.IsNullOrEmpty(dataSourcePath) && DataBindingUtility.IsPathValid(source, dataSourcePath).returnCode != VisitReturnCode.Ok) { pathWarningMessage = BuilderConstants.BindingWindowNotResolvedPathErrorMessage; } } else if (dataSourceType != null) { if (string.IsNullOrEmpty(dataSourcePath)) { if (isBinding) pathWarningMessage = BuilderConstants.BindingWindowMissingPathErrorMessage; } else { if (DataBindingUtility.IsPathValid(dataSourceType, dataSourcePath).returnCode != VisitReturnCode.Ok) { pathWarningMessage = BuilderConstants.BindingWindowNotResolvedPathErrorMessage; } } } if (!string.IsNullOrEmpty(pathWarningMessage)) { m_PathWarningBox.text = pathWarningMessage; m_PathWarningBox.style.display = DisplayStyle.Flex; } else { m_PathWarningBox.style.display = DisplayStyle.None; } } public BuilderDataSourceAndPathView(BuilderInspector inspector) : base(inspector) { } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Inspector/Binding/BuilderDataSourceAndPathView.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Inspector/Binding/BuilderDataSourceAndPathView.cs", "repo_id": "UnityCsReference", "token_count": 11403 }
484
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine.UIElements; using UnityEditor; namespace Unity.UI.Builder { internal class BuilderInspectorStyleSheet : IBuilderInspectorSection { BuilderInspector m_Inspector; BuilderSelection m_Selection; VisualElement m_StyleSheetSection; TextField m_NewSelectorNameNameField; Button m_AddNewSelectorButton; private VisualElement m_NewSelectorHelpTipsContainer; static readonly string kHelpTooltipPath = BuilderConstants.UIBuilderPackagePath + "/Explorer/BuilderStyleSheetsNewSelectorHelpTips.uxml"; private static readonly string kNewSelectorHelpTipsContainerName = "new-selector-help-tips-container"; public VisualElement root => m_StyleSheetSection; StyleSheet styleSheet => m_Inspector.styleSheet; VisualElement currentVisualElement => m_Inspector.currentVisualElement; public BuilderInspectorStyleSheet(BuilderInspector inspector) { m_Inspector = inspector; m_Selection = inspector.selection; m_StyleSheetSection = m_Inspector.Q("shared-styles-controls"); m_NewSelectorNameNameField = m_Inspector.Q<TextField>("add-new-selector-field"); m_AddNewSelectorButton = m_Inspector.Q<Button>("add-new-selector-button"); m_NewSelectorHelpTipsContainer = m_Inspector.Q<VisualElement>(kNewSelectorHelpTipsContainerName); m_AddNewSelectorButton.clickable.clicked += CreateNewSelector; m_NewSelectorNameNameField.RegisterValueChangedCallback(OnCreateNewSelector); m_NewSelectorNameNameField.isDelayed = true; var helpTooltipTemplate = BuilderPackageUtilities.LoadAssetAtPath<VisualTreeAsset>(kHelpTooltipPath); var helpTooltipContainer = helpTooltipTemplate.CloneTree(); m_NewSelectorHelpTipsContainer.Add(helpTooltipContainer); } void OnCreateNewSelector(ChangeEvent<string> evt) { CreateNewSelector(evt.newValue); } void CreateNewSelector() { if (string.IsNullOrEmpty(m_NewSelectorNameNameField.value)) return; CreateNewSelector(m_NewSelectorNameNameField.value); } void CreateNewSelector(string newSelectorString) { m_NewSelectorNameNameField.SetValueWithoutNotify(string.Empty); Undo.RegisterCompleteObjectUndo( styleSheet, BuilderConstants.AddNewSelectorUndoMessage); BuilderSharedStyles.CreateNewSelector( currentVisualElement.parent, styleSheet, newSelectorString); m_Selection.NotifyOfHierarchyChange(m_Inspector); m_Selection.NotifyOfStylingChange(m_Inspector); } public void Refresh() { // Do nothing. } public void Enable() { // Do nothing. } public void Disable() { // Do nothing. } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Inspector/BuilderInspectorStyleSheet.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Inspector/BuilderInspectorStyleSheet.cs", "repo_id": "UnityCsReference", "token_count": 1329 }
485
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEngine.UIElements; namespace Unity.UI.Builder { class BuilderPlacementIndicator : VisualElement { static readonly string s_UssClassName = "unity-builder-placement-indicator"; const int k_IndicatorSize = 4; const int k_IndicatorHalfSize = 2; const int k_DistanceFromElementEdge = 10; public VisualElement parentElement { get; private set; } public int indexWithinParent { get; private set; } public VisualElement documentRootElement { get; set; } [Serializable] public new class UxmlSerializedData : VisualElement.UxmlSerializedData { public override object CreateInstance() => new BuilderPlacementIndicator(); } public BuilderPlacementIndicator() { var builderTemplate = BuilderPackageUtilities.LoadAssetAtPath<VisualTreeAsset>( BuilderConstants.UIBuilderPackagePath + "/Manipulators/BuilderPlacementIndicator.uxml"); builderTemplate.CloneTree(this); AddToClassList(s_UssClassName); } public void Activate(VisualElement hierarchyParentElement, int hierarchyIndex) { Reset(); if (hierarchyParentElement.childCount == 0 || hierarchyParentElement == documentRootElement) return; var mouseOverElement = hierarchyIndex > -1 && hierarchyIndex < hierarchyParentElement.childCount - 1 ? hierarchyParentElement.ElementAt(hierarchyIndex) : hierarchyParentElement.ElementAt(hierarchyParentElement.childCount - 1); var mouseOverElementCanvasRect = BuilderTracker.GetRelativeRectFromTargetElement(mouseOverElement, this.hierarchy.parent); var shouldGoLast = hierarchyIndex >= hierarchyParentElement.childCount; var isRow = hierarchyParentElement.resolvedStyle.flexDirection == FlexDirection.Row || hierarchyParentElement.resolvedStyle.flexDirection == FlexDirection.RowReverse; var reverseOrder = hierarchyParentElement.resolvedStyle.flexDirection == FlexDirection.ColumnReverse || hierarchyParentElement.resolvedStyle.flexDirection == FlexDirection.RowReverse; if (isRow) { if (!reverseOrder && !shouldGoLast) { style.top = mouseOverElementCanvasRect.y; style.left = mouseOverElementCanvasRect.x - k_IndicatorHalfSize; style.width = k_IndicatorSize; style.height = mouseOverElementCanvasRect.height; } else if (reverseOrder || shouldGoLast) { style.top = mouseOverElementCanvasRect.y; style.left = mouseOverElementCanvasRect.xMax - k_IndicatorHalfSize; style.width = k_IndicatorSize; style.height = mouseOverElementCanvasRect.height; } } else if (!isRow) { if (!reverseOrder && !shouldGoLast) { style.top = mouseOverElementCanvasRect.y - k_IndicatorHalfSize; style.left = mouseOverElementCanvasRect.x; style.width = mouseOverElementCanvasRect.width; style.height = k_IndicatorSize; } else if (reverseOrder || shouldGoLast) { style.top = mouseOverElementCanvasRect.yMax - k_IndicatorHalfSize; style.left = mouseOverElementCanvasRect.x; style.width = mouseOverElementCanvasRect.width; style.height = k_IndicatorSize; } } else { return; } style.display = DisplayStyle.Flex; } public void Activate(VisualElement mouseOverElement, Vector2 mousePosition) { Reset(); parentElement = mouseOverElement; if (mouseOverElement == documentRootElement) return; var mouseOverElementMouse = mouseOverElement.WorldToLocal(mousePosition); var mouseOverElementRect = mouseOverElement.rect; var mouseOverElementCanvasRect = BuilderTracker.GetRelativeRectFromTargetElement(mouseOverElement, this.hierarchy.parent); var isCloseToLeftEdge = mouseOverElementMouse.x < k_DistanceFromElementEdge; var isCloseToRightEdge = mouseOverElementMouse.x > mouseOverElementRect.xMax - k_DistanceFromElementEdge; var isCloseToTopEdge = mouseOverElementMouse.y < k_DistanceFromElementEdge; var isCloseToBottomEdge = mouseOverElementMouse.y > mouseOverElementRect.yMax - k_DistanceFromElementEdge; var reverseOrder = mouseOverElement.parent.resolvedStyle.flexDirection == FlexDirection.ColumnReverse || mouseOverElement.parent.resolvedStyle.flexDirection == FlexDirection.RowReverse; int indexOffset; if (isCloseToLeftEdge) { style.top = mouseOverElementCanvasRect.y; style.left = mouseOverElementCanvasRect.x - k_IndicatorHalfSize; style.width = k_IndicatorSize; style.height = mouseOverElementCanvasRect.height; indexOffset = reverseOrder ? 1 : 0; } else if (isCloseToRightEdge) { style.top = mouseOverElementCanvasRect.y; style.left = mouseOverElementCanvasRect.xMax - k_IndicatorHalfSize; style.width = k_IndicatorSize; style.height = mouseOverElementCanvasRect.height; indexOffset = reverseOrder ? 0 : 1; } else if (isCloseToTopEdge) { style.top = mouseOverElementCanvasRect.y - k_IndicatorHalfSize; style.left = mouseOverElementCanvasRect.x; style.width = mouseOverElementCanvasRect.width; style.height = k_IndicatorSize; indexOffset = reverseOrder ? 1 : 0; } else if (isCloseToBottomEdge) { style.top = mouseOverElementCanvasRect.yMax - k_IndicatorHalfSize; style.left = mouseOverElementCanvasRect.x; style.width = mouseOverElementCanvasRect.width; style.height = k_IndicatorSize; indexOffset = reverseOrder ? 0 : 1; } else { return; } style.display = DisplayStyle.Flex; parentElement = mouseOverElement.parent; // We don't want to store the old parent into parentElement, otherwise there will be some consequences when // overriding contentContainer. We instead store it in a local copy and fetch it around when needed. var correctedParentElement = BuilderHierarchyUtilities.GetToggleButtonGroupContentContainer(parentElement) ?? parentElement; indexWithinParent = correctedParentElement.IndexOf(mouseOverElement) + indexOffset; } public void Deactivate() { Reset(); } void Reset() { style.display = DisplayStyle.None; parentElement = null; indexWithinParent = -1; } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Manipulators/BuilderPlacementIndicator.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Manipulators/BuilderPlacementIndicator.cs", "repo_id": "UnityCsReference", "token_count": 3484 }
486
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using UnityEditor; using UnityEditor.UIElements; using UnityEditor.UIElements.StyleSheets; using UnityEngine; using UnityEngine.UIElements; using Object = UnityEngine.Object; namespace Unity.UI.Builder { internal static class BuilderAssetUtilities { public static string assetsPath { get; } = Application.dataPath; public static string projectPath { get; } = assetsPath.Substring(0, Application.dataPath.Length - "/Assets".Length); public static string packagesPath { get; } = projectPath + "/Packages"; public const string defaultRuntimeThemeContent = "@import url(\"" + ThemeRegistry.kThemeScheme + "://default\");\nVisualElement {}"; internal static bool IsProjectDefaultRuntimeAsset(string path) { if (path == ThemeRegistry.k_DefaultStyleSheetPath) { return false; } if (!File.Exists(path)) { return false; } var assetString = File.ReadAllText(path); if (!string.IsNullOrEmpty(assetString)) { assetString = DeleteNewlinesAndWhitespaces(assetString); } return assetString == DeleteNewlinesAndWhitespaces(defaultRuntimeThemeContent) || assetString == DeleteNewlinesAndWhitespaces(PanelSettingsCreator.GetTssTemplateContent()); } private static string DeleteNewlinesAndWhitespaces(string str) { return Regex.Replace(str, @"[\r\n\s]+", string.Empty); } static string GetFullPath(string path) { return Path.GetFullPath(path).Replace("\\", "/"); } public static bool IsPathInProject(string path) { var fullPath = GetFullPath(path); return fullPath.StartsWith(assetsPath, StringComparison.InvariantCultureIgnoreCase) || fullPath.StartsWith(packagesPath, StringComparison.InvariantCultureIgnoreCase); } public static string GetPathRelativeToProject(string path) { if (!IsPathInProject(path)) return null; var fullPath = GetFullPath(path); return fullPath.Substring(projectPath.Length + 1); // "/" } public static string GetResourcesPathForAsset(Object asset) { var assetPath = AssetDatabase.GetAssetPath(asset); return GetResourcesPathForAsset(assetPath); } public static string GetResourcesPathForAsset(string assetPath) { if (string.IsNullOrWhiteSpace(assetPath)) return null; // Start by trying to find a "Resources" folder in the middle of the path. var resourcesFolder = "/Resources/"; var lastResourcesFolderIndex = assetPath.LastIndexOf(resourcesFolder, StringComparison.Ordinal); // Otherwise check if the "Resources" path is at the start. if (lastResourcesFolderIndex < 0) { if (assetPath.StartsWith("Resources/")) { lastResourcesFolderIndex = 0; resourcesFolder = "Resources/"; } else return null; } var lastResourcesSubstring = lastResourcesFolderIndex + resourcesFolder.Length; assetPath = assetPath.Substring(lastResourcesSubstring); var lastExtDot = assetPath.LastIndexOf(".", StringComparison.Ordinal); if (lastExtDot == -1) return null; assetPath = assetPath.Substring(0, lastExtDot); return assetPath; } public static bool IsBuiltinPath(string assetPath) { return assetPath == "Resources/unity_builtin_extra"; } public static bool ValidateAsset(VisualTreeAsset asset, string path) { string errorMessage = null; string errorTitle = null; if (asset == null) { if (string.IsNullOrEmpty(path)) path = "<unspecified>"; if (path.StartsWith("Packages/")) errorMessage = $"The asset at path {path} is not a UXML Document.\nNote, for assets inside Packages folder, the folder name for the package needs to match the actual official package name (ie. com.example instead of Example)."; else errorMessage = $"The asset at path {path} is not a UXML Document."; errorTitle = "Invalid Asset Type"; } else if (asset.importedWithErrors) { if (string.IsNullOrEmpty(path)) path = AssetDatabase.GetAssetPath(asset); if (string.IsNullOrEmpty(path)) path = "<unspecified>"; errorMessage = string.Format(BuilderConstants.InvalidUXMLDialogMessage, path); errorTitle = BuilderConstants.InvalidUXMLDialogTitle; } if (errorMessage != null) { BuilderDialogsUtility.DisplayDialog(errorTitle, errorMessage, "Ok"); Debug.LogError(errorMessage); return false; } return true; } public static bool AddStyleSheetToAsset( BuilderDocument document, string ussPath) { var styleSheet = BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(ussPath); string errorMessage = null; string errorTitle = null; if (styleSheet == null) { if (ussPath.StartsWith("Packages/")) errorMessage = $"Asset at path {ussPath} is not a StyleSheet.\nNote, for assets inside Packages folder, the folder name for the package needs to match the actual official package name (ie. com.example instead of Example)."; else errorMessage = $"Asset at path {ussPath} is not a StyleSheet."; errorTitle = "Invalid Asset Type"; } else if (styleSheet.importedWithErrors) { errorMessage = string.Format(BuilderConstants.InvalidUSSDialogMessage, ussPath); errorTitle = BuilderConstants.InvalidUSSDialogTitle; } if (errorMessage != null) { BuilderDialogsUtility.DisplayDialog(errorTitle, errorMessage, "Ok"); Debug.LogError(errorMessage); return false; } Undo.RegisterCompleteObjectUndo( document.visualTreeAsset, "Add StyleSheet to UXML"); document.AddStyleSheetToDocument(styleSheet, ussPath); return true; } public static void RemoveStyleSheetFromAsset( BuilderDocument document, int ussIndex) { Undo.RegisterCompleteObjectUndo( document.visualTreeAsset, "Remove StyleSheet from UXML"); document.RemoveStyleSheetFromDocument(ussIndex); } public static void RemoveStyleSheetsFromAsset( BuilderDocument document, int[] indexes) { Undo.RegisterCompleteObjectUndo( document.visualTreeAsset, "Remove StyleSheets from UXML"); foreach (var index in indexes) { document.RemoveStyleSheetFromDocument(index); } } public static void ReorderStyleSheetsInAsset( BuilderDocument document, VisualElement styleSheetsContainerElement) { Undo.RegisterCompleteObjectUndo( document.visualTreeAsset, "Reorder StyleSheets in UXML"); var reorderedUSSList = new List<StyleSheet>(); foreach (var ussElement in styleSheetsContainerElement.Children()) reorderedUSSList.Add(ussElement.GetStyleSheet()); var openUXMLFile = document.activeOpenUXMLFile; openUXMLFile.openUSSFiles.Sort((left, right) => { var leftOrder = reorderedUSSList.IndexOf(left.styleSheet); var rightOrder = reorderedUSSList.IndexOf(right.styleSheet); return leftOrder.CompareTo(rightOrder); }); var rootElement = openUXMLFile.visualTreeAsset.GetRootUxmlElement(); if (rootElement != null && rootElement.stylesheets != null) { rootElement.stylesheets.Sort((left, right) => { var leftOrder = reorderedUSSList.IndexOf(left); var rightOrder = reorderedUSSList.IndexOf(right); return leftOrder.CompareTo(rightOrder); }); } } public static VisualElementAsset AddElementToAsset( BuilderDocument document, VisualElement ve, int index = -1) { Undo.RegisterCompleteObjectUndo( document.visualTreeAsset, BuilderConstants.CreateUIElementUndoMessage); var veParent = ve.parent; VisualElementAsset veaParent = null; /* If the current parent element is linked to a VisualTreeAsset, it could mean that our parent is the TemplateContainer belonging to our parent document and the current open document is a sub-document opened in-place. In such a case, we don't want to use our parent's VisualElementAsset, as that belongs to our parent document. So instead, we just use no parent, indicating that we are adding this new element to the root of our document.*/ if (veParent != null && veParent.GetVisualTreeAsset() != document.visualTreeAsset) { // We must revisit this once we finalize how we want our container controls to work with accepting // specific types of controls. For now we're only applying this for ToggleButtonGroup but other controls // like RadioButtonGroup would also be applicable. if (veParent.parent is ToggleButtonGroup control) veParent = control; veaParent = veParent.GetVisualElementAsset(); } if (veaParent == null) veaParent = document.visualTreeAsset.GetRootUxmlElement(); // UXML Root Element var vea = document.visualTreeAsset.AddElement(veaParent, ve); if (index >= 0) document.visualTreeAsset.ReparentElement(vea, veaParent, index); return vea; } public static VisualElementAsset AddElementToAsset( BuilderDocument document, VisualElement ve, Func<VisualTreeAsset, VisualElementAsset, VisualElement, VisualElementAsset> makeVisualElementAsset, int index = -1, bool registerUndo = true) { if (registerUndo) { Undo.RegisterCompleteObjectUndo( document.visualTreeAsset, BuilderConstants.CreateUIElementUndoMessage); } var veParent = ve.parent; VisualElementAsset veaParent = null; /* If the current parent element is linked to a VisualTreeAsset, it could mean that our parent is the TemplateContainer belonging to our parent document and the current open document is a sub-document opened in-place. In such a case, we don't want to use our parent's VisualElementAsset, as that belongs to our parent document. So instead, we just use no parent, indicating that we are adding this new element to the root of our document.*/ if (veParent != null && veParent.GetVisualTreeAsset() != document.visualTreeAsset) veaParent = veParent.GetVisualElementAsset(); if (veaParent == null) veaParent = document.visualTreeAsset.GetRootUxmlElement(); // UXML Root Element var vea = makeVisualElementAsset(document.visualTreeAsset, veaParent, ve); ve.SetVisualElementAsset(vea); ve.SetProperty(BuilderConstants.ElementLinkedBelongingVisualTreeAssetVEPropertyName, document.visualTreeAsset); if (index >= 0) document.visualTreeAsset.ReparentElement(vea, veaParent, index); return vea; } public static void SortElementsByTheirVisualElementInAsset(VisualElement parentVE) { var parentVEA = parentVE.GetVisualElementAsset(); if (parentVEA == null) return; if (parentVE.childCount <= 1) return; var correctOrderForElementAssets = new List<VisualElementAsset>(); var correctOrdersInDocument = new List<int>(); foreach (var ve in parentVE.Children()) { var vea = ve.GetVisualElementAsset(); if (vea == null) continue; correctOrderForElementAssets.Add(vea); correctOrdersInDocument.Add(vea.orderInDocument); } if (correctOrderForElementAssets.Count <= 1) return; correctOrdersInDocument.Sort(); for (int i = 0; i < correctOrderForElementAssets.Count; ++i) correctOrderForElementAssets[i].orderInDocument = correctOrdersInDocument[i]; } public static void ReparentElementInAsset( BuilderDocument document, VisualElement veToReparent, VisualElement newParent, int index = -1, bool undo = true) { var veaToReparent = veToReparent.GetVisualElementAsset(); if (veaToReparent == null) return; if (undo) Undo.RegisterCompleteObjectUndo( document.visualTreeAsset, BuilderConstants.ReparentUIElementUndoMessage); VisualElementAsset veaNewParent = null; if (newParent != null) veaNewParent = newParent.GetVisualElementAsset(); if (veaNewParent == null) veaNewParent = document.visualTreeAsset.GetRootUxmlElement(); // UXML Root Element document.visualTreeAsset.ReparentElement(veaToReparent, veaNewParent, index); } public static void ApplyAttributeOverridesToTreeAsset(List<TemplateAsset.AttributeOverride> attributeOverrides, VisualTreeAsset visualTreeAsset) { foreach (var attributeOverride in attributeOverrides) { var overwrittenElements = visualTreeAsset.FindElementsByName(attributeOverride.m_ElementName); foreach (var overwrittenElement in overwrittenElements) { overwrittenElement.SetAttribute(attributeOverride.m_AttributeName, attributeOverride.m_Value); } } } public static void CopyAttributeOverridesToChildTemplateAssets(List<TemplateAsset.AttributeOverride> attributeOverrides, VisualTreeAsset visualTreeAsset) { foreach (var templateAsset in visualTreeAsset.templateAssets) { foreach (var attributeOverride in attributeOverrides) { templateAsset.SetAttributeOverride(attributeOverride.m_ElementName, attributeOverride.m_AttributeName, attributeOverride.m_Value); } } } public static void AddStyleSheetsFromTreeAsset(VisualElementAsset visualElementAsset, VisualTreeAsset visualTreeAsset) { foreach (var styleSheet in visualTreeAsset.stylesheets) { var styleSheetPath = AssetDatabase.GetAssetPath(styleSheet); visualElementAsset.AddStyleSheet(styleSheet); visualElementAsset.AddStyleSheetPath(styleSheetPath); } } public static void DeleteElementFromAsset(BuilderDocument document, VisualElement ve, bool registerUndo = true) { var vea = ve.GetVisualElementAsset(); if (vea == null) return; if (registerUndo) { Undo.RegisterCompleteObjectUndo( document.visualTreeAsset, BuilderConstants.DeleteUIElementUndoMessage); } foreach (var child in ve.Children()) { DeleteElementFromAsset(document, child, false); } document.visualTreeAsset.RemoveElement(vea); } public static void TransferAssetToAsset( BuilderDocument document, VisualElementAsset parent, VisualTreeAsset otherVta, bool registerUndo = true) { if (registerUndo) { Undo.RegisterCompleteObjectUndo( document.visualTreeAsset, BuilderConstants.CreateUIElementUndoMessage); } document.visualTreeAsset.Swallow(parent, otherVta); } public static void TransferAssetToAsset( BuilderDocument document, StyleSheet styleSheet, StyleSheet otherStyleSheet) { Undo.RegisterCompleteObjectUndo( styleSheet, BuilderConstants.AddNewSelectorUndoMessage); styleSheet.Swallow(otherStyleSheet); } public static void AddStyleClassToElementInAsset(BuilderDocument document, VisualElement ve, string className) { Undo.RegisterCompleteObjectUndo( document.visualTreeAsset, BuilderConstants.AddStyleClassUndoMessage); var vea = ve.GetVisualElementAsset(); vea.AddStyleClass(className); } public static void RemoveStyleClassFromElementInAsset(BuilderDocument document, VisualElement ve, string className) { Undo.RegisterCompleteObjectUndo( document.visualTreeAsset, BuilderConstants.RemoveStyleClassUndoMessage); var vea = ve.GetVisualElementAsset(); vea.RemoveStyleClass(className); } public static void AddStyleComplexSelectorToSelection(StyleSheet styleSheet, StyleComplexSelector scs) { var selectionProp = styleSheet.AddProperty( scs, BuilderConstants.SelectedStyleRulePropertyName, BuilderConstants.ChangeSelectionUndoMessage); // Need to add at least one dummy value because lots of code will die // if it encounters a style property with no values. styleSheet.AddValue( selectionProp, 42.0f, BuilderConstants.ChangeSelectionUndoMessage); } public static void AddElementToSelectionInAsset(BuilderDocument document, VisualElement ve) { if (BuilderSharedStyles.IsStyleSheetElement(ve)) { var styleSheet = ve.GetStyleSheet(); styleSheet.AddSelector( BuilderConstants.SelectedStyleSheetSelectorName, BuilderConstants.ChangeSelectionUndoMessage); } else if (BuilderSharedStyles.IsSelectorElement(ve)) { var styleSheet = ve.GetClosestStyleSheet(); var scs = ve.GetStyleComplexSelector(); AddStyleComplexSelectorToSelection(styleSheet, scs); } else if (BuilderSharedStyles.IsDocumentElement(ve)) { Undo.RegisterCompleteObjectUndo( document.visualTreeAsset, BuilderConstants.ChangeSelectionUndoMessage); var vta = ve.GetVisualTreeAsset(); var vtaRoot = vta.GetRootUxmlElement(); var vea = vta.AddElement(vtaRoot, BuilderConstants.SelectedVisualTreeAssetSpecialElementTypeName); // We don't want this element to be cloned. vea.skipClone = true; } else if (ve.GetVisualElementAsset() != null) { Undo.RegisterCompleteObjectUndo( document.visualTreeAsset, BuilderConstants.ChangeSelectionUndoMessage); var vea = ve.GetVisualElementAsset(); vea.Select(); } } public static void RemoveElementFromSelectionInAsset(BuilderDocument document, VisualElement ve) { if (BuilderSharedStyles.IsStyleSheetElement(ve)) { var styleSheet = ve.GetStyleSheet(); styleSheet.RemoveSelector( BuilderConstants.SelectedStyleSheetSelectorName, BuilderConstants.ChangeSelectionUndoMessage); } else if (BuilderSharedStyles.IsSelectorElement(ve)) { var styleSheet = ve.GetClosestStyleSheet(); var scs = ve.GetStyleComplexSelector(); styleSheet.RemoveProperty( scs, BuilderConstants.SelectedStyleRulePropertyName, BuilderConstants.ChangeSelectionUndoMessage); } else if (BuilderSharedStyles.IsDocumentElement(ve)) { Undo.RegisterCompleteObjectUndo( document.visualTreeAsset, BuilderConstants.ChangeSelectionUndoMessage); var vta = ve.GetVisualTreeAsset(); var selectedElement = vta.FindElementByType(BuilderConstants.SelectedVisualTreeAssetSpecialElementTypeName); vta.RemoveElementAndDependencies(selectedElement); } else if (ve.GetVisualElementAsset() != null) { Undo.RegisterCompleteObjectUndo( document.visualTreeAsset, BuilderConstants.ChangeSelectionUndoMessage); var vea = ve.GetVisualElementAsset(); vea.Deselect(); } } public static string GetVisualTreeAssetAssetName(VisualTreeAsset visualTreeAsset, bool hasUnsavedChanges) => GetAssetName(visualTreeAsset, BuilderConstants.UxmlExtension, hasUnsavedChanges); public static string GetStyleSheetAssetName(StyleSheet styleSheet, bool hasUnsavedChanges) => GetAssetName(styleSheet, BuilderConstants.UssExtension, hasUnsavedChanges); public static string GetAssetName(ScriptableObject asset, string extension, bool hasUnsavedChanges) { if (asset == null) { if (extension == BuilderConstants.UxmlExtension) return BuilderConstants.ToolbarUnsavedFileDisplayText + extension; else return string.Empty; } var assetPath = AssetDatabase.GetAssetPath(asset); if (string.IsNullOrEmpty(assetPath)) return BuilderConstants.ToolbarUnsavedFileDisplayText + extension; return Path.GetFileName(assetPath) + (hasUnsavedChanges ? BuilderConstants.ToolbarUnsavedFileSuffix : ""); } public static TemplateContainer GetVisualElementRootTemplate(VisualElement visualElement) { TemplateContainer templateContainerParent = null; var parent = visualElement.parent; while (parent != null) { if (parent is TemplateContainer templateContainer && templateContainer.GetVisualElementAsset() != null) { templateContainerParent = templateContainer; break; } if (BuilderSharedStyles.IsDocumentElement(parent)) { break; } parent = parent.parent; } return templateContainerParent; } public static bool HasDynamicallyCreatedTemplateAncestor(VisualElement visualElement) { var parent = visualElement.parent; while (parent != null) { if (BuilderSharedStyles.IsDocumentElement(parent)) { return false; } if (parent is TemplateContainer && !parent.HasProperty(VisualTreeAsset.LinkedVEAInTemplatePropertyName) && parent.GetVisualElementAsset() == null) { return true; } parent = parent.parent; } return false; } public static bool HasAttributeOverrideInRootTemplate(VisualElement visualElement, string attributeName) { var templateContainer = GetVisualElementRootTemplate(visualElement); var templateAsset = templateContainer?.GetVisualElementAsset() as TemplateAsset; return templateAsset?.attributeOverrides.Count(x => x.m_ElementName == visualElement.name && x.m_AttributeName == attributeName) > 0; } public static List<CreationContext.AttributeOverrideRange> GetAccumulatedAttributeOverrides(VisualElement visualElement) { VisualElement parent = visualElement.parent; List<CreationContext.AttributeOverrideRange> attributeOverrideRanges = new(); while (parent != null) { if (parent is TemplateContainer) { TemplateAsset templateAsset; if (parent.HasProperty(VisualTreeAsset.LinkedVEAInTemplatePropertyName)) { templateAsset = parent.GetProperty(VisualTreeAsset.LinkedVEAInTemplatePropertyName) as TemplateAsset; } else { templateAsset = parent.GetVisualElementAsset() as TemplateAsset; } if (templateAsset != null) { VisualTreeAsset visualTreeAsset = parent.GetVisualTreeAsset(); if (visualTreeAsset != null) { attributeOverrideRanges.Add(new CreationContext.AttributeOverrideRange(visualTreeAsset, templateAsset.attributeOverrides)); } } // We reached the root template if (parent.GetVisualElementAsset() != null) { break; } } parent = parent.parent; } // Parent attribute overrides have higher priority attributeOverrideRanges.Reverse(); return attributeOverrideRanges; } public static bool WriteTextFileToDisk(string path, string content) { bool success = FileUtil.WriteTextFileToDisk(path, content, out string message); if (!success) { Debug.LogError(message); BuilderDialogsUtility.DisplayDialog("Save - " + path, message, "Ok"); } return success; } // Refresh GameView preview with the latest (unsaved to disk) changes. [Flags] public enum LiveReloadChanges { Hierarchy = 1, Styles = 2 } public static void LiveReload(LiveReloadChanges changes) { if ((changes & LiveReloadChanges.Hierarchy) != 0) UIElementsUtility.InMemoryAssetsHierarchyHaveBeenChanged(); if ((changes & LiveReloadChanges.Styles) != 0) UIElementsUtility.InMemoryAssetsStyleHaveBeenChanged(); } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Utilities/BuilderAssetUtilities.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Utilities/BuilderAssetUtilities.cs", "repo_id": "UnityCsReference", "token_count": 12730 }
487
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine.UIElements; namespace Unity.UI.Builder { /// <summary> /// Creates a ui field based on uxml attributes. /// </summary> internal interface IBuilderUxmlAttributeFieldFactory { /// <summary> /// Indicates whether this factory can create a field for the specified uxml attribute. /// </summary> /// <param name="attributeOwner">An instance created from the uxml element that owns the related xml attribute.</param> /// <param name="attributeUxmlOwner">The uxml element that owns the uxml attribute related to evaluate.</param> /// <param name="attribute">The uxml attribute to evaluate.</param> /// <returns>Return true if the factory can create field for the specified attribute.</returns> bool CanCreateField(object attributeOwner, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute); /// <summary> /// Creates a ui field based on uxml attributes. /// </summary> /// <param name="attributeOwner">An instance created from the uxml element that owns the related xml attribute.</param> /// <param name="attributeUxmlOwner">The uxml element that owns the uxml attribute related to field to create.</param> /// <param name="attribute">The uxml attribute.</param> /// <param name="onValueChange">The callback to invoke whenever the value of the create field changes.</param> /// <returns>The field created for the specified uxml attribute.</returns> VisualElement CreateField(object attributeOwner, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute, Action<VisualElement, UxmlAttributeDescription, object, string> onValueChange); /// <summary> /// Sets the value of the specified field created from the specified uxml attribute. /// </summary> /// <param name="field">The field to update</param> /// <param name="attributeOwner">An instance created from the uxml element that owns the related xml attribute.</param> /// <param name="uxmlDocument">The uxml document that contains the uxml attribute owner.</param> /// <param name="attributeUxmlOwner">The uxml element that owns the uxml attribute related to field to update.</param> /// <param name="attribute">The uxml attribute related to the field to update.</param> /// <param name="value">The new value to set</param> void SetFieldValue(VisualElement field, object attributeOwner, VisualTreeAsset uxmlDocument, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute, object value); /// <summary> /// Resets the value of the specified field created from the specified uxml attribute to its default value. /// </summary> /// <param name="field">The field to reset.</param> /// <param name="attributeOwner">An instance created from the uxml element that owns the related xml attribute.</param> /// <param name="uxmlDocument">The uxml document that contains the uxml attribute owner.</param> /// <param name="attributeUxmlOwner">The uxml element that owns the uxml attribute related to field to reset.</param> /// <param name="attribute">The uxml attribute related to the field to reset.</param> void ResetFieldValue(VisualElement field, object attributeOwner, VisualTreeAsset uxmlDocument, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute); void ResetFieldValueToInline(VisualElement field, object attributeOwner, VisualTreeAsset uxmlDocument, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute); } /// <summary> /// Base factory to create a ui field based on a TypedUxmlAttributeDescription . /// </summary> /// <typeparam name="T">The value type of TypedUxmlAttributeDescription for which this factory can create fields</typeparam> /// <typeparam name="TFieldType">The class of fields created by this factory</typeparam> internal abstract class BuilderTypedUxmlAttributeFieldFactoryBase<T, TFieldType> : IBuilderUxmlAttributeFieldFactory where TFieldType : BaseField<T> { public virtual bool CanCreateField(object attributeOwner, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute) { return attribute is TypedUxmlAttributeDescription<T>; } /// <summary> /// Instantiates a ui field based on the specified uxml attribute. /// </summary> /// <param name="attributeOwner">An instance created from the uxml element that owns the related xml attribute.</param> /// <param name="attributeUxmlOwner">The uxml element that owns the uxml attribute related to field to instantiate.</param> /// <param name="attribute">The uxml attribute.</param> /// <returns></returns> protected abstract TFieldType InstantiateField(object attributeOwner, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute); public VisualElement CreateField(object attributeOwner, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute, Action<VisualElement, UxmlAttributeDescription, object, string> onValueChange) { var fieldLabel = BuilderNameUtilities.ConvertDashToHuman(attribute.name); var field = InstantiateField(attributeOwner, attributeUxmlOwner, attribute); field.label = fieldLabel; if (attribute.name.Equals("multiline") && attributeOwner is TextField) { field.RegisterValueChangedCallback(evt => { OnMultilineToggleValueChange(evt, attributeUxmlOwner); NotifyValueChanged(evt, field, attributeOwner, attributeUxmlOwner, attribute, ValueToUxml.Convert(evt.newValue), onValueChange); }); return field; } field.RegisterValueChangedCallback((evt) => { NotifyValueChanged(evt, field, attributeOwner, attributeUxmlOwner, attribute, ValueToUxml.Convert(evt.newValue), onValueChange); }); return field; } public virtual void SetFieldValue(VisualElement field, object attributeOwner, VisualTreeAsset uxmlDocument, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute, object value) { (field as TFieldType).SetValueWithoutNotify((T)value); } public virtual void ResetFieldValue(VisualElement field, object attributeOwner, VisualTreeAsset uxmlDocument, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute) { var typedAttribute = attribute as TypedUxmlAttributeDescription<T>; (field as TFieldType).SetValueWithoutNotify(typedAttribute.defaultValue); } public virtual void ResetFieldValueToInline(VisualElement field, object attributeOwner, VisualTreeAsset uxmlDocument, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute) { var typedAttribute = attribute as TypedUxmlAttributeDescription<T>; var value = typedAttribute.GetValueFromBag(attributeUxmlOwner, CreationContext.Default); SetFieldValue(field, attributeOwner, uxmlDocument, attributeUxmlOwner, attribute, value); } /// <summary> /// Notifies that the value of the specified field has changed. /// </summary> /// <param name="evt">The event emitted when the value of the field changed.</param> /// <param name="field">The field created by this factory of which value has changed.</param> /// <param name="attributeOwner">An instance created from the uxml element that owns the related xml attribute.</param> /// <param name="attributeUxmlOwner">The uxml element that owns the uxml attribute related to the field.</param> /// <param name="attribute">The uxml attribute edited by the target field.</param> /// <param name="uxmlValue">The new value formatted to uxml.</param> /// <param name="onValueChange">The callback to invoke.</param> protected virtual void NotifyValueChanged(ChangeEvent<T> evt, TFieldType field , object attributeOwner , UxmlAsset attributeUxmlOwner , UxmlAttributeDescription attribute , string uxmlValue , Action<VisualElement, UxmlAttributeDescription, object, string> onValueChange) { onValueChange?.Invoke(field, attribute, evt.newValue, uxmlValue); } void OnMultilineToggleValueChange(ChangeEvent<T> evt, UxmlAsset attributeUxmlOwner) { if (evt.target is not Toggle target) return; if (evt is not ChangeEvent<bool> boolEvt) return; var valueFieldInInspector = target?.GetFirstAncestorOfType<BuilderInspector>().Query<TextField>().Where(x => x.bindingPath is "value").First(); if (valueFieldInInspector == null) return; valueFieldInInspector.multiline = boolEvt.newValue; valueFieldInInspector.EnableInClassList(BuilderConstants.InspectorMultiLineTextFieldClassName, boolEvt.newValue); } } /// <summary> /// Creates a ui field based on a TypedUxmlAttributeDescription. /// </summary> /// <typeparam name="T">The value type of TypedUxmlAttributeDescription for which this factory can create fields.</typeparam> /// <typeparam name="TFieldType">The class of fields created by this factory.</typeparam> internal class BuilderTypedUxmlAttributeFieldFactory<T, TFieldType> : BuilderTypedUxmlAttributeFieldFactoryBase<T, TFieldType> where TFieldType : BaseField<T>, new () { protected override TFieldType InstantiateField(object attributeOwner, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute) { return new TFieldType(); } } internal sealed class BuilderDefaultUxmlAttributeFieldFactory : BuilderTypedUxmlAttributeFieldFactory<string, TextField> { public override bool CanCreateField(object attributeOwner, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute) { return true; } public override void ResetFieldValue(VisualElement field, object attributeOwner, VisualTreeAsset uxmlDocument, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute) { (field as TextField).SetValueWithoutNotify(string.Empty); } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/UxmlAttributesView/Fields/BuilderUxmlAttributeFieldFactory.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/UxmlAttributesView/Fields/BuilderUxmlAttributeFieldFactory.cs", "repo_id": "UnityCsReference", "token_count": 3592 }
488
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.UIElements; namespace Unity.UI.Builder { internal class BuilderZoomer : PointerManipulator { private const int MinScaleStart = 25; // This is the minimum scale (25%), increment in small steps private const int MiddleScaleStart = 150; // At 150%, let's increment in larger steps private const int MaxScaleStart = 500; // At 500%, let's increment in even larger steps private const int MaxScaleEnd = 10000; // until we reach the max scale (500%) private const int LowScaleIncrement = 5; // Low scale increment step (5%) private const int MiddleScaleIncrement = 25; // Middle scale increment step (25%) private const int HighScaleIncrement = 250; // High scale increment step (100%) private List<float> m_ZoomScaleValues; private const float DefaultScale = 1; private const float ZoomStepDistance = 10; // Full zoom scale list available with the Zoomer manipulator public List<float> zoomScaleValues { get { if (m_ZoomScaleValues == null) { m_ZoomScaleValues = new List<float>(); for (var val = MinScaleStart; val < MiddleScaleStart; val += LowScaleIncrement) m_ZoomScaleValues.Add((float)Math.Round(val/100.0, 2)); for (var val = MiddleScaleStart; val < MaxScaleStart; val += MiddleScaleIncrement) m_ZoomScaleValues.Add((float)Math.Round(val / 100.0, 2)); for (var val = MaxScaleStart; val <= MaxScaleEnd; val += HighScaleIncrement) m_ZoomScaleValues.Add((float)Math.Round(val/100.0, 2)); } return m_ZoomScaleValues; } } // Short list of zoom scales for the Zoom menu public List<float> zoomMenuScaleValues { get; } = new() { 0.25f, 0.5f, 0.75f, 1f, 1.25f, 1.5f, 1.75f, 2f, 2.5f, 4f, 5f, 10f, 25f, 50f, 75f, 100f }; bool m_Zooming; Vector2 m_PressPos; Vector2 m_LastZoomPos; readonly BuilderViewport m_Viewport; public BuilderZoomer(BuilderViewport viewport) { m_Viewport = viewport; m_Viewport.Q("viewport").AddManipulator(this); activators.Add(new ManipulatorActivationFilter { button = MouseButton.RightMouse, modifiers = EventModifiers.Alt}); } protected override void RegisterCallbacksOnTarget() { target.RegisterCallback<PointerDownEvent>(OnPointerDown); target.RegisterCallback<PointerMoveEvent>(OnPointerMove); target.RegisterCallback<PointerUpEvent>(OnPointerUp); target.RegisterCallback<WheelEvent>(OnWheel); } protected override void UnregisterCallbacksFromTarget() { target.UnregisterCallback<PointerDownEvent>(OnPointerDown); target.UnregisterCallback<PointerMoveEvent>(OnPointerMove); target.UnregisterCallback<PointerUpEvent>(OnPointerUp); target.UnregisterCallback<WheelEvent>(OnWheel); } private static float CalculateNewZoom(float currentZoom, float wheelDelta, List<float> zoomValues) { if (Mathf.Approximately(wheelDelta, 0)) { return currentZoom; } // If the current zoom is not in the bounds of the zoom values list, return the closest zoom value. if (currentZoom < zoomValues[0]) return zoomValues[0]; if (currentZoom > zoomValues[^1]) return zoomValues[^1]; // Find the closest zoom value var currentZoomIndex = 0; for (int i = 0; i < zoomValues.Count; ++i) { if (zoomValues[i] <= currentZoom) currentZoomIndex = i; else break; } currentZoomIndex = Mathf.Clamp(currentZoomIndex + ((wheelDelta > 0) ? 1 : -1), 0, zoomValues.Count - 1); return zoomValues[currentZoomIndex]; } void OnPointerDown(PointerDownEvent evt) { if (CanStartManipulation(evt)) { m_Zooming = true; m_PressPos = evt.localPosition; m_LastZoomPos = m_PressPos; target.CaptureMouse(); evt.StopImmediatePropagation(); } } void OnPointerUp(PointerUpEvent evt) { if (!m_Zooming || !CanStopManipulation(evt)) return; m_Zooming = false; target.ReleaseMouse(); evt.StopPropagation(); } void OnPointerMove(PointerMoveEvent evt) { if (!m_Zooming || Mathf.Abs(evt.localPosition.y - m_LastZoomPos.y) < ZoomStepDistance) return; Zoom(evt.deltaPosition.y, m_PressPos); m_LastZoomPos = evt.localPosition; evt.StopPropagation(); } void OnWheel(WheelEvent evt) { if (MouseCaptureController.IsMouseCaptured()) return; Zoom(-evt.delta.y, evt.localMousePosition); evt.StopPropagation(); } void Zoom(float delta, Vector2 zoomCenter) { if (BuilderProjectSettings.disableMouseWheelZooming) return; m_Viewport.SetTargetZoomScale(CalculateNewZoom(m_Viewport.targetZoomScale, delta, zoomScaleValues), (_, v) => { var oldScale = m_Viewport.zoomScale; m_Viewport.targetZoomScale = v; m_Viewport.targetContentOffset = (zoomCenter + (v / oldScale) * (m_Viewport.contentOffset - zoomCenter)); }); } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Viewport/BuilderZoomer.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Viewport/BuilderZoomer.cs", "repo_id": "UnityCsReference", "token_count": 2884 }
489
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine.UIElements; namespace Unity.UI.Builder { class FoldoutWithCheckbox : PersistedFoldout { [Serializable] public new class UxmlSerializedData : PersistedFoldout.UxmlSerializedData { public override object CreateInstance() => new FoldoutWithCheckbox(); } const string k_UssPath = BuilderConstants.UtilitiesPath + "/FoldoutWithCheckbox/FoldoutWithCheckbox.uss"; const string k_CheckboxClassName = "unity-foldout__checkbox"; const string k_LabelClassName = "unity-foldout-with-checkbox__label"; readonly Toggle m_Checkbox; readonly Label m_Label; public FoldoutWithCheckbox() { m_Toggle.text = string.Empty; m_Toggle.visualInput.style.flexGrow = 0; m_Checkbox = new Toggle(); m_Checkbox.style.flexGrow = 0; m_Checkbox.AddToClassList(k_CheckboxClassName); m_Checkbox.RegisterValueChangedCallback(e => SetCheckboxValueWithoutNotify(e.newValue)); m_Toggle.hierarchy.Add(m_Checkbox); m_Label = new Label(); m_Label.AddToClassList(k_LabelClassName); m_Label.AddManipulator(new Clickable(evt => { if ((evt as MouseUpEvent)?.button == (int)MouseButton.LeftMouse) { m_Toggle.value = !m_Toggle.value; } })); m_Toggle.hierarchy.Add(m_Label); styleSheets.Add(BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(k_UssPath)); } public override string text { get => m_Label.text; set => m_Label.text = value; } public void SetCheckboxValueWithoutNotify(bool newValue) { m_Checkbox.SetValueWithoutNotify(newValue); contentContainer.SetEnabled(newValue); } public void RegisterCheckboxValueChangedCallback(EventCallback<ChangeEvent<bool>> callback) { m_Checkbox.RegisterCallback(callback); } } }
UnityCsReference/Modules/UIBuilder/Editor/Utilities/FoldoutWithCheckbox/FoldoutWithCheckbox.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/FoldoutWithCheckbox/FoldoutWithCheckbox.cs", "repo_id": "UnityCsReference", "token_count": 1045 }
490
// 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 Unity.UI.Builder { internal class BoxModelStyleField : DimensionStyleField { static readonly string k_LabelClassName = "unity-box-model__style-field__label"; private Label m_Label; private bool m_ShowUnit; public bool showUnit { get => m_ShowUnit; set { m_ShowUnit = value; UpdateLabel(); } } public BoxModelStyleField() { m_Label = new Label(ComposeValue()); m_Label.AddToClassList(k_LabelClassName); Insert(0, m_Label); // remove focus on enter RegisterCallback<KeyUpEvent>(OnKeyUp); draggerIntegerField.labelElement.RegisterCallback<PointerUpEvent>(OnDraggerPointerUp, TrickleDown.TrickleDown); } void OnKeyUp(KeyUpEvent e) { if (e.keyCode is KeyCode.Return or KeyCode.KeypadEnter or KeyCode.Escape) { Blur(); } } void OnDraggerPointerUp(PointerUpEvent e) { if (!isUsingLabelDragger) { textField.Focus(); return; } Blur(); } public override void SetValueWithoutNotify(string newValue) { base.SetValueWithoutNotify(newValue); UpdateLabel(); } public void UpdateLabel() { ((INotifyValueChanged<string>)m_Label).SetValueWithoutNotify(showUnit ? ComposeValue() : GetTextFromValue()); } } }
UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/BoxModelStyleField.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/BoxModelStyleField.cs", "repo_id": "UnityCsReference", "token_count": 891 }
491
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Linq; using UnityEditor; using UnityEngine.UIElements; namespace Unity.UI.Builder { class SpacingBoxModelView : VisualElement { static readonly string k_UssPathNoExt = BuilderConstants.UtilitiesPath + "/StyleField/StyleSectionsBoxModel"; private static readonly string k_MouseOverClassName = "mouse-over"; static readonly string k_BoxModelClassName = "unity-box-model"; static readonly string k_ViewClassName = k_BoxModelClassName + "__view"; static readonly string k_ContainerClassName = k_BoxModelClassName + "__view__container"; static readonly string k_ContainerMarginClassName = k_BoxModelClassName + "__container__margin"; static readonly string k_ContainerPaddingClassName = k_BoxModelClassName + "__container__padding"; static readonly string k_ContainerBorderClassName = k_BoxModelClassName + "__container__border"; static readonly string k_ContainerContentClassName = k_BoxModelClassName + "__container__content"; static readonly string k_TextfieldClassName = k_BoxModelClassName + "__textfield"; static readonly string k_TextfieldContentClassName = k_TextfieldClassName + "__content-center"; static readonly string k_TextfieldSpacerClassName = k_TextfieldClassName + "__spacer"; static readonly string k_TextfieldCenterSpacerClassName = k_TextfieldClassName + "__center-spacer"; static readonly string k_CheckerboardClassName = k_BoxModelClassName + "__checkerboard-background"; private VisualElement m_Container; private VisualElement m_Layer1; private VisualElement m_Layer2; private BoxModelElement<string, BoxModelStyleField> m_MarginBox; private BoxModelElement<string, BoxModelStyleField> m_PaddingBox; private VisualElement m_ContentBox; private VisualElement m_BorderBox; // margin containers private VisualElement m_TopTextFieldMarginContainer = new VisualElement(); private VisualElement m_BottomTextFieldMarginContainer = new VisualElement(); private VisualElement m_LeftTextFieldMarginContainer = new VisualElement(); private VisualElement m_RightTextFieldMarginContainer = new VisualElement(); // padding containers private VisualElement m_TopTextFieldPaddingContainer = new VisualElement(); private VisualElement m_BottomTextFieldPaddingContainer = new VisualElement(); private VisualElement m_LeftTextFieldPaddingContainer = new VisualElement(); private VisualElement m_RightTextFieldPaddingContainer = new VisualElement(); private VisualElement m_ContentCenter = new VisualElement(); private VisualElement m_CenterSpacer = new VisualElement(); private BuilderInspector m_Inspector; [Serializable] public new class UxmlSerializedData : VisualElement.UxmlSerializedData { public override object CreateInstance() => new SpacingBoxModelView(); } public SpacingBoxModelView() { styleSheets.Add(BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(k_UssPathNoExt + (EditorGUIUtility.isProSkin ? "Dark" : "Light") + ".uss")); styleSheets.Add(BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(k_UssPathNoExt + ".uss")); AddToClassList(k_ViewClassName); AddToClassList(BuilderConstants.InspectorCompositeStyleRowElementClassName); m_Container = new VisualElement(); m_Container.AddToClassList(k_ContainerClassName); m_Container.AddToClassList(BuilderConstants.InspectorCompositeStyleRowElementClassName); m_Layer1 = new VisualElement() { name = "BoxModelViewLayer1", classList = { BuilderConstants.InspectorCompositeStyleRowElementClassName } }; m_Layer2 = new VisualElement() { name = "BoxModelViewLayer2", classList = { BuilderConstants.InspectorCompositeStyleRowElementClassName } }; m_Layer2.pickingMode = PickingMode.Ignore; m_Layer2.StretchToParentSize(); StyleContainers(); m_ContentCenter.pickingMode = PickingMode.Ignore; m_ContentCenter.AddToClassList(k_TextfieldContentClassName); m_ContentCenter.AddToClassList(BuilderConstants.InspectorCompositeStyleRowElementClassName); m_CenterSpacer.pickingMode = PickingMode.Ignore; m_CenterSpacer.AddToClassList(k_TextfieldCenterSpacerClassName); m_ContentCenter.Add(m_LeftTextFieldMarginContainer); m_ContentCenter.Add(m_LeftTextFieldPaddingContainer); m_ContentCenter.Add(m_CenterSpacer); m_ContentCenter.Add(m_RightTextFieldPaddingContainer); m_ContentCenter.Add(m_RightTextFieldMarginContainer); m_Layer2.Add(m_TopTextFieldMarginContainer); m_Layer2.Add(m_TopTextFieldPaddingContainer); m_Layer2.Add(m_ContentCenter); m_Layer2.Add(m_BottomTextFieldPaddingContainer); m_Layer2.Add(m_BottomTextFieldMarginContainer); m_ContentBox = new VisualElement() { classList = { BuilderConstants.InspectorCompositeStyleRowElementClassName, k_BoxModelClassName, k_ContainerContentClassName } }; m_ContentBox.tooltip = "Size"; m_ContentBox.RegisterCallback<MouseOverEvent, BoxType>(OnMouseOver, BoxType.Content); m_PaddingBox = new BoxModelElement<string, BoxModelStyleField>(BoxType.Padding, true, m_ContentBox, m_TopTextFieldPaddingContainer, m_BottomTextFieldPaddingContainer, m_LeftTextFieldPaddingContainer, m_RightTextFieldPaddingContainer); m_PaddingBox.tooltip = BoxType.Padding.ToString(); m_PaddingBox.AddToClassList(k_BoxModelClassName); m_PaddingBox.AddToClassList(k_ContainerPaddingClassName); m_PaddingBox.AddToClassList(BuilderConstants.InspectorCompositeStyleRowElementClassName); m_PaddingBox.RegisterCallback<MouseOverEvent, BoxType>(OnMouseOver, BoxType.Padding); m_BorderBox = new VisualElement(); m_BorderBox.tooltip = BoxType.Border.ToString(); m_BorderBox.AddToClassList(k_BoxModelClassName); m_BorderBox.AddToClassList(k_ContainerBorderClassName); m_BorderBox.AddToClassList(BuilderConstants.InspectorCompositeStyleRowElementClassName); m_BorderBox.RegisterCallback<MouseOverEvent, BoxType>(OnMouseOver, BoxType.Border); m_BorderBox.Add(m_PaddingBox); m_MarginBox = new BoxModelElement<string, BoxModelStyleField>(BoxType.Margin, true, m_BorderBox, m_TopTextFieldMarginContainer, m_BottomTextFieldMarginContainer, m_LeftTextFieldMarginContainer, m_RightTextFieldMarginContainer); // checkerboard background for margin var checkerboardBackground = new CheckerboardBackground(); checkerboardBackground.AddToClassList(k_CheckerboardClassName); m_MarginBox.AddBackground(checkerboardBackground); m_MarginBox.tooltip = BoxType.Margin.ToString(); m_MarginBox.AddToClassList(k_BoxModelClassName); m_MarginBox.AddToClassList(k_ContainerMarginClassName); m_MarginBox.AddToClassList(BuilderConstants.InspectorCompositeStyleRowElementClassName); m_MarginBox.RegisterCallback<MouseOverEvent, BoxType>(OnMouseOver, BoxType.Margin); m_Layer1.Add(m_MarginBox); m_Container.Add(m_Layer1); m_Container.Add(m_Layer2); Add(m_Container); RegisterCallback<MouseOutEvent>(OnMouseOut); RegisterCallback<GeometryChangedEvent>(OnFirstDisplay); // overlay events RegisterCallback<MouseEnterEvent>(OnMouseEnter); RegisterCallback<MouseLeaveEvent>(OnMouseLeave); } private void StyleContainers() { foreach (var container in new[] { m_TopTextFieldMarginContainer, m_TopTextFieldPaddingContainer, m_BottomTextFieldMarginContainer, m_BottomTextFieldPaddingContainer, m_LeftTextFieldMarginContainer, m_LeftTextFieldPaddingContainer, m_RightTextFieldMarginContainer, m_RightTextFieldPaddingContainer }) { container.pickingMode = PickingMode.Ignore; container.AddToClassList(k_TextfieldSpacerClassName); container.AddToClassList(BuilderConstants.InspectorCompositeStyleRowElementClassName); } } private void OnMouseOver(MouseOverEvent evt, BoxType boxType) { m_MarginBox.EnableInClassList(k_MouseOverClassName, boxType == BoxType.Margin); m_BorderBox.EnableInClassList(k_MouseOverClassName, boxType == BoxType.Border); m_PaddingBox.EnableInClassList(k_MouseOverClassName, boxType == BoxType.Padding); m_ContentBox.EnableInClassList(k_MouseOverClassName, boxType == BoxType.Content); m_MarginBox.background.visible = boxType != BoxType.Margin; evt.StopPropagation(); } private void OnMouseOut(MouseOutEvent evt) { m_MarginBox.background.visible = true; m_MarginBox.EnableInClassList(k_MouseOverClassName, false); m_BorderBox.EnableInClassList(k_MouseOverClassName, false); m_PaddingBox.EnableInClassList(k_MouseOverClassName, false); m_ContentBox.EnableInClassList(k_MouseOverClassName, false); evt.StopPropagation(); } private void OnMouseEnter(MouseEnterEvent evt) { m_Inspector.highlightOverlayPainter.ClearOverlay(); if (m_Inspector.selection.selection.Any()) m_Inspector.highlightOverlayPainter.AddOverlay(m_Inspector.selection.selection.First()); } private void OnMouseLeave(MouseLeaveEvent evt) { m_Inspector.highlightOverlayPainter.ClearOverlay(); } void OnFirstDisplay(GeometryChangedEvent evt) { m_Inspector = GetFirstAncestorOfType<BuilderInspector>(); UnregisterCallback<GeometryChangedEvent>(OnFirstDisplay); } } }
UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/SpacingBoxModelView.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/SpacingBoxModelView.cs", "repo_id": "UnityCsReference", "token_count": 4516 }
492
// 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; using UnityEngine.UIElements.StyleSheets; namespace Unity.UI.Builder { static class TransitionsExtensions { public static bool IsTransitionId(this StylePropertyId id) { switch (id) { case StylePropertyId.Transition: case StylePropertyId.TransitionDelay: case StylePropertyId.TransitionDuration: case StylePropertyId.TransitionProperty: case StylePropertyId.TransitionTimingFunction: return true; } return false; } public static int MaxCount(this TransitionData data) { return Mathf.Max(data.transitionProperty.Count, Mathf.Max(data.transitionDuration.Count, Mathf.Max(data.transitionTimingFunction.Count, data.transitionDelay.Count))); } public static Dimension ToDimension(this TimeValue timeValue) { return new Dimension(timeValue.value, timeValue.unit == TimeUnit.Millisecond ? Dimension.Unit.Millisecond : Dimension.Unit.Second); } public static bool IsTimeUnit(this Dimension.Unit unit) { return unit == Dimension.Unit.Millisecond || unit == Dimension.Unit.Second; } public static string UssName(this StylePropertyId id) { return StylePropertyUtil.stylePropertyIdToPropertyName.TryGetValue(id, out var name) ? name : id.ToString(); } // TODO: Move this to codegen public static StylePropertyId GetShorthandProperty(this StylePropertyId id) { switch (id) { case StylePropertyId.BorderBottomColor: case StylePropertyId.BorderLeftColor: case StylePropertyId.BorderRightColor: case StylePropertyId.BorderTopColor: return StylePropertyId.BorderColor; case StylePropertyId.BorderBottomLeftRadius: case StylePropertyId.BorderBottomRightRadius: case StylePropertyId.BorderTopLeftRadius: case StylePropertyId.BorderTopRightRadius: return StylePropertyId.BorderRadius; case StylePropertyId.BorderBottomWidth: case StylePropertyId.BorderLeftWidth: case StylePropertyId.BorderRightWidth: case StylePropertyId.BorderTopWidth: return StylePropertyId.BorderWidth; case StylePropertyId.FlexBasis: case StylePropertyId.FlexGrow: case StylePropertyId.FlexShrink: return StylePropertyId.Flex; case StylePropertyId.MarginBottom: case StylePropertyId.MarginLeft: case StylePropertyId.MarginRight: case StylePropertyId.MarginTop: return StylePropertyId.Margin; case StylePropertyId.PaddingBottom: case StylePropertyId.PaddingLeft: case StylePropertyId.PaddingRight: case StylePropertyId.PaddingTop: return StylePropertyId.Padding; case StylePropertyId.TransitionProperty: case StylePropertyId.TransitionDuration: case StylePropertyId.TransitionTimingFunction: case StylePropertyId.TransitionDelay: return StylePropertyId.Transition; case StylePropertyId.UnityTextOutlineColor: case StylePropertyId.UnityTextOutlineWidth: return StylePropertyId.UnityTextOutline; default: return StylePropertyId.Unknown; } } } }
UnityCsReference/Modules/UIBuilder/Editor/Utilities/Transitions/TransitionsExtensions.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/Transitions/TransitionsExtensions.cs", "repo_id": "UnityCsReference", "token_count": 1910 }
493
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using UnityEngine.UIElements.UIR; namespace UnityEngine.UIElements { abstract class AtlasBase { public virtual bool TryGetAtlas(VisualElement ctx, Texture2D src, out TextureId atlas, out RectInt atlasRect) { atlas = TextureId.invalid; atlasRect = new RectInt(); return false; } public virtual void ReturnAtlas(VisualElement ctx, Texture2D src, TextureId atlas) {} public virtual void Reset() {} protected virtual void OnAssignedToPanel(IPanel panel) {} protected virtual void OnRemovedFromPanel(IPanel panel) {} protected virtual void OnUpdateDynamicTextures(IPanel panel) {} // Called just before rendering occurs. internal void InvokeAssignedToPanel(IPanel panel) { OnAssignedToPanel(panel); } internal void InvokeRemovedFromPanel(IPanel panel) { OnRemovedFromPanel(panel); } internal void InvokeUpdateDynamicTextures(IPanel panel) { OnUpdateDynamicTextures(panel); } protected static void RepaintTexturedElements(IPanel panel) { var p = panel as Panel; var updater = p?.GetUpdater(VisualTreeUpdatePhase.Repaint) as UIRRepaintUpdater; updater?.renderChain?.RepaintTexturedElements(); } protected TextureId AllocateDynamicTexture() { return textureRegistry.AllocAndAcquireDynamic(); } protected void FreeDynamicTexture(TextureId id) { textureRegistry.Release(id); } protected void SetDynamicTexture(TextureId id, Texture texture) { textureRegistry.UpdateDynamic(id, texture); } // Overridable for tests internal TextureRegistry textureRegistry = TextureRegistry.instance; } /// <summary> /// Options to enable or disable filters for the dynamic atlas. /// </summary> /// <remarks> /// Filters exclude individual textures from the texture atlas based on specific criteria. /// </remarks> [Flags] public enum DynamicAtlasFilters { /// <summary> /// No filtering is performed. /// </summary> None = 0, /// <summary> /// Excludes readable textures.<br/><br/> /// /// Readable textures are textures that are readable from scripts, which means they are also writable or editable. /// Another way to think of this filter is as a way to exclude textures that are not read-only. /// </summary> Readability = 1 << 0, /// <summary> /// Excludes textures whose size exceeds the maximum sub-texture size specified in the dynamic atlas settings. /// </summary> Size = 1 << 1, /// <summary> /// Excludes textures that, because of their format, would lose precision, or be truncated when the system adds them to the atlas. <br/><br/> /// /// The dynamic atlas system accepts non-HDR texture formats that have 8 bits or less per component, before compression<br/><br/> /// /// You can add a compressed texture to a dynamic atlas. However, doing so might cause additional image loss because the system must first decompress /// the image in order to store it in the atlas. Decompression can yield values that are impossible to represent precisely in 8-bits per /// component. For example, a value of 1/256 in the compressed image might decompress to 3/512. The system cannot store 3/512 /// in the atlas, so it stores the value as either 1/256 or 2/256.<br/><br/> /// /// This creates potential differences between the source texture and the version stored in the atlas. These differences are /// noticeable in the following scenarios:<br/><br/> /// 1. Blending Operations: 3/512, 1/256, and 2/256 each produce a different result when you use them in a blending operation. /// 2. Rendering to high precision render targets (for example, 16 bits per component). /// /// In most cases, the performance benefits of allowing compressed textures into the atlas outweigh the inconvenience of /// introducing small errors. /// </summary> Format = 1 << 2, /// <summary> /// Excludes textures whose color space does not match the color space of the atlas. /// </summary> ColorSpace = 1 << 3, /// <summary> /// Excludes textures that use a filter mode that the atlas does not support.<br/><br/> /// /// This filter is disabled by default. You can enable it to prevent artifacts that might occur when /// the atlas does not support the texture's filter mode, and cannot sample the texture correctly. However, /// because excluding textures from the atlas can reduce performance, the default behavior is preferable in most cases.<br/><br/> /// /// On GLES3 (and later) devices, the atlas supports more than one filter mode, so you should not need /// to enable this filter. /// </summary> FilterMode = 1 << 4, } /// <summary> /// Delegate that can be used as a custom filter for the dynamic atlas. /// </summary> /// <param name="texture">The texture to filter.</param> /// <param name="filtersToApply">The filters the dynamic atlas applies when the delegate returns <c>true</c>. /// by default, this value is equal to <see cref="DynamicAtlasSettings.activeFilters"/>.</param> /// <returns> /// When <c>false</c>, the texture cannot be added to the atlas. When <c>true</c> the texture is added to the atlas, /// as long as it is not excluded by filtersToApply. /// </returns> public delegate bool DynamicAtlasCustomFilter(Texture2D texture, ref DynamicAtlasFilters filtersToApply); class DynamicAtlas : AtlasBase { internal class TextureInfo : LinkedPoolItem<TextureInfo> { public DynamicAtlasPage page; public int counter; public Allocator2D.Alloc2D alloc; public RectInt rect; public static readonly LinkedPool<TextureInfo> pool = new LinkedPool<TextureInfo>(Create, Reset, 1024); [MethodImpl(MethodImplOptionsEx.AggressiveInlining)] static TextureInfo Create() => new TextureInfo(); [MethodImpl(MethodImplOptionsEx.AggressiveInlining)] static void Reset(TextureInfo info) { info.page = null; info.counter = 0; info.alloc = new Allocator2D.Alloc2D(); info.rect = new RectInt(); } } Dictionary<Texture, TextureInfo> m_Database = new Dictionary<Texture, TextureInfo>(); internal Dictionary<Texture, TextureInfo> Database => m_Database; DynamicAtlasPage m_PointPage; DynamicAtlasPage m_BilinearPage; internal DynamicAtlasPage PointPage => m_PointPage; internal DynamicAtlasPage BilinearPage => m_BilinearPage; ColorSpace m_ColorSpace; List<IPanel> m_Panels = new List<IPanel>(1); internal bool isInitialized => m_PointPage != null || m_BilinearPage != null; protected override void OnAssignedToPanel(IPanel panel) { base.OnAssignedToPanel(panel); m_Panels.Add(panel); if (m_Panels.Count == 1) m_ColorSpace = QualitySettings.activeColorSpace; } protected override void OnRemovedFromPanel(IPanel panel) { m_Panels.Remove(panel); if (m_Panels.Count == 0 && isInitialized) DestroyPages(); base.OnRemovedFromPanel(panel); } public override void Reset() { if (isInitialized) { DestroyPages(); for (int i = 0, count = m_Panels.Count; i < count; ++i) RepaintTexturedElements(m_Panels[i]); } } void InitPages() { // Sanitize the parameters int cleanMaxSubTextureSize = Mathf.Max(m_MaxSubTextureSize, 1); cleanMaxSubTextureSize = Mathf.NextPowerOfTwo(cleanMaxSubTextureSize); int cleanMaxAtlasSize = Mathf.Max(m_MaxAtlasSize, 1); cleanMaxAtlasSize = Mathf.NextPowerOfTwo(cleanMaxAtlasSize); cleanMaxAtlasSize = Mathf.Min(cleanMaxAtlasSize, SystemInfo.maxRenderTextureSize); int cleanMinAtlasSize = Mathf.Max(m_MinAtlasSize, 1); cleanMinAtlasSize = Mathf.NextPowerOfTwo(cleanMinAtlasSize); cleanMinAtlasSize = Mathf.Min(cleanMinAtlasSize, cleanMaxAtlasSize); var cleanMinSize = new Vector2Int(cleanMinAtlasSize, cleanMinAtlasSize); var cleanMaxSize = new Vector2Int(cleanMaxAtlasSize, cleanMaxAtlasSize); m_PointPage = new DynamicAtlasPage(RenderTextureFormat.ARGB32, FilterMode.Point, cleanMinSize, cleanMaxSize); m_BilinearPage = new DynamicAtlasPage(RenderTextureFormat.ARGB32, FilterMode.Bilinear, cleanMinSize, cleanMaxSize); } void DestroyPages() { m_PointPage.Dispose(); m_PointPage = null; m_BilinearPage.Dispose(); m_BilinearPage = null; m_Database.Clear(); } public override bool TryGetAtlas(VisualElement ve, Texture2D src, out TextureId atlas, out RectInt atlasRect) { if (m_Panels.Count == 0 || src == null) { atlas = TextureId.invalid; atlasRect = new RectInt(); return false; } if (!isInitialized) InitPages(); if (m_Database.TryGetValue(src, out TextureInfo info)) { atlas = info.page.textureId; atlasRect = info.rect; ++info.counter; return true; } // For the time being, we don't have a trilinear page. If users keep the filterMode check enabled, a // mip-mapped texture will NOT enter any of our pages. However, if they disable this check, we should try // to put it in the bilinear atlas first, because it will provide some interpolation, unlike the Point page. Allocator2D.Alloc2D alloc; if (IsTextureValid(src, FilterMode.Bilinear) && m_BilinearPage.TryAdd(src, out alloc, out atlasRect)) { info = TextureInfo.pool.Get(); info.alloc = alloc; info.counter = 1; info.page = m_BilinearPage; info.rect = atlasRect; m_Database[src] = info; atlas = m_BilinearPage.textureId; return true; } if (IsTextureValid(src, FilterMode.Point) && m_PointPage.TryAdd(src, out alloc, out atlasRect)) { info = TextureInfo.pool.Get(); info.alloc = alloc; info.counter = 1; info.page = m_PointPage; info.rect = atlasRect; m_Database[src] = info; atlas = m_PointPage.textureId; return true; } atlas = TextureId.invalid; atlasRect = new RectInt(); return false; } public override void ReturnAtlas(VisualElement ve, Texture2D src, TextureId atlas) { if (m_Database.TryGetValue(src, out TextureInfo info)) { --info.counter; if (info.counter == 0) { info.page.Remove(info.alloc); m_Database.Remove(src); TextureInfo.pool.Return(info); } } } protected override void OnUpdateDynamicTextures(IPanel panel) { if (m_PointPage != null) { m_PointPage.Commit(); SetDynamicTexture(m_PointPage.textureId, m_PointPage.atlas); } if (m_BilinearPage != null) { m_BilinearPage.Commit(); SetDynamicTexture(m_BilinearPage.textureId, m_BilinearPage.atlas); } } /// <summary> /// The dynamic atlas system accepts non-HDR texture formats that have 8 bits or less per component, before compression. /// </summary> /// <remarks> /// If you add a compressed texture to a dynamic atlas, you might see additional image loss. The system must first decompress /// the image in order to store it in the atlas, which can yield values that are impossible to represent precisely in 8-bits per /// channel. For example, a value of 1/256 in the compressed image might decompress to 3/512. The system cannot store 3/512 /// in the atlas, so it stores the value as either 1/256 or 2/256. /// /// This creates potential differences between the source texture and the version stored in the atlas. These differences are /// noticeable in the following scenarios: /// 1) Blending Operations: you get different results if you blend 3/512 than you get if you blend with 1/256 or 2/256. /// 2) Rendering to high precision render targets (for example, 16 bits per component). /// /// In most cases, the performance benefits of allowing compressed textures into the atlas outweigh the inconvenience of /// introducing a small error. /// </remarks> internal static bool IsTextureFormatSupported(TextureFormat format) { switch (format) { case TextureFormat.Alpha8: case TextureFormat.ARGB4444: case TextureFormat.RGB24: case TextureFormat.RGBA32: case TextureFormat.ARGB32: case TextureFormat.RGB565: case TextureFormat.R16: case TextureFormat.DXT1: // (BC1) Source is 5/6/5 bits per component case TextureFormat.DXT5: // (BC3) Source is 5/6/5/8 bits per component case TextureFormat.RGBA4444: case TextureFormat.BGRA32: case TextureFormat.BC7: // Source is typically 8 bits per component (BUT COULD BE MORE) case TextureFormat.BC4: // Source is 1 components per color, 8 bits per component case TextureFormat.BC5: // Source is 2 components per color, 8 bits per component case TextureFormat.DXT1Crunched: // See DXT1 case TextureFormat.DXT5Crunched: // See DXT5 case TextureFormat.PVRTC_RGB2: // Source is 8 bits per component or less case TextureFormat.PVRTC_RGBA2: // Source is 8 bits per component or less case TextureFormat.PVRTC_RGB4: // Source is 8 bits per component or less case TextureFormat.PVRTC_RGBA4: // Source is 8 bits per component or less case TextureFormat.ETC_RGB4: // Source is 8 bits per component case TextureFormat.EAC_R: // Source is 8 bits per component case TextureFormat.EAC_R_SIGNED: // Source is 8 bits per component case TextureFormat.EAC_RG: // Source is 8 bits per component case TextureFormat.EAC_RG_SIGNED: // Source is 8 bits per component case TextureFormat.ETC2_RGB: // Source is 8 bits per component case TextureFormat.ETC2_RGBA1: // Source is 8 bits per component case TextureFormat.ETC2_RGBA8: // Source is 8 bits per component case TextureFormat.ASTC_4x4: // Source is 8 bits per component case TextureFormat.ASTC_5x5: // Source is 8 bits per component case TextureFormat.ASTC_6x6: // Source is 8 bits per component case TextureFormat.ASTC_8x8: // Source is 8 bits per component case TextureFormat.ASTC_10x10: // Source is 8 bits per component case TextureFormat.ASTC_12x12: // Source is 8 bits per component case TextureFormat.RG16: // Source is 8 bits per component case TextureFormat.R8: // Source is 8 bits per component case TextureFormat.ETC_RGB4Crunched: // See ETC case TextureFormat.ETC2_RGBA8Crunched: // See ETC2 return true; case TextureFormat.RHalf: // HDR case TextureFormat.RGHalf: // HDR case TextureFormat.RGBAHalf: // HDR case TextureFormat.RFloat: // HDR case TextureFormat.RGFloat: // HDR case TextureFormat.RGBAFloat: // HDR case TextureFormat.YUY2: // Video Content case TextureFormat.RGB9e5Float: // HDR case TextureFormat.BC6H: // HDR case TextureFormat.ASTC_HDR_4x4: // HDR case TextureFormat.ASTC_HDR_5x5: // HDR case TextureFormat.ASTC_HDR_6x6: // HDR case TextureFormat.ASTC_HDR_8x8: // HDR case TextureFormat.ASTC_HDR_10x10: // HDR case TextureFormat.ASTC_HDR_12x12: // HDR case TextureFormat.RG32: // HDR case TextureFormat.RGB48: // HDR case TextureFormat.RGBA64: // HDR case TextureFormat.R8_SIGNED: // Signed case TextureFormat.RG16_SIGNED: // Signed case TextureFormat.RGB24_SIGNED: // Signed case TextureFormat.RGBA32_SIGNED: // Signed case TextureFormat.R16_SIGNED: // Signed case TextureFormat.RG32_SIGNED: // Signed case TextureFormat.RGB48_SIGNED: // Signed case TextureFormat.RGBA64_SIGNED: // Signed return false; default: // This exception is required if we want to be able to detect new enum values in test // UIRAtlasManagerTests.AllTextureFormatsAreHandled. throw new NotImplementedException($"The support of texture format '{format}' is undefined."); } } public virtual bool IsTextureValid(Texture2D texture, FilterMode atlasFilterMode) { var filters = m_ActiveFilters; if (m_CustomFilter != null && !m_CustomFilter(texture, ref filters)) return false; bool filterReadability = (filters & DynamicAtlasFilters.Readability) != 0; bool filterSize = (filters & DynamicAtlasFilters.Size) != 0; bool filterFormat = (filters & DynamicAtlasFilters.Format) != 0; bool filterColorSpace = (filters & DynamicAtlasFilters.ColorSpace) != 0; bool filterFilterMode = (filters & DynamicAtlasFilters.FilterMode) != 0; if (filterReadability && texture.isReadable) return false; if (filterSize && (texture.width > maxSubTextureSize || texture.height > maxSubTextureSize)) return false; if (filterFormat && !IsTextureFormatSupported(texture.format)) return false; // When in linear color space, the atlas will have sRGB read/write enabled. This means we can't store // linear data without potentially causing banding. if (filterColorSpace && m_ColorSpace == ColorSpace.Linear && texture.activeTextureColorSpace != ColorSpace.Gamma) return false; if (filterFilterMode && texture.filterMode != atlasFilterMode) return false; return true; } public void SetDirty(Texture2D tex) // This API will be used later. { if (tex == null) return; if (m_Database.TryGetValue(tex, out TextureInfo info)) info.page.Update(tex, info.rect); } #region Atlas Settings int m_MinAtlasSize = 64; int m_MaxAtlasSize = 4096; public int minAtlasSize { get { return m_MinAtlasSize; } set { if (m_MinAtlasSize == value) return; m_MinAtlasSize = value; Reset(); } } public int maxAtlasSize { get { return m_MaxAtlasSize; } set { if (m_MaxAtlasSize == value) return; m_MaxAtlasSize = value; Reset(); } } #endregion // Atlas Settings #region Filter Settings int m_MaxSubTextureSize = 64; DynamicAtlasFilters m_ActiveFilters = defaultFilters; DynamicAtlasCustomFilter m_CustomFilter; public static DynamicAtlasFilters defaultFilters => DynamicAtlasFilters.Readability | DynamicAtlasFilters.Size | DynamicAtlasFilters.Format | DynamicAtlasFilters.ColorSpace | DynamicAtlasFilters.FilterMode; public DynamicAtlasFilters activeFilters { get { return m_ActiveFilters; } set { if (m_ActiveFilters == value) return; m_ActiveFilters = value; Reset(); } } public int maxSubTextureSize { get { return m_MaxSubTextureSize; } set { if (m_MaxSubTextureSize == value) return; m_MaxSubTextureSize = value; Reset(); } } public DynamicAtlasCustomFilter customFilter { get { return m_CustomFilter; } set { if (m_CustomFilter == value) return; m_CustomFilter = value; Reset(); } } #endregion // Filter Settings } }
UnityCsReference/Modules/UIElements/Core/Atlas.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Atlas.cs", "repo_id": "UnityCsReference", "token_count": 10448 }
494
// Unity 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; namespace UnityEngine.UIElements { /// <summary> /// A type to hold information about a conversion registry used locally on bindings. /// </summary> /// <remarks> /// You can apply converter groups on a <see cref="DataBinding"/> in UXML with the <c>source-to-ui-converters</c> or /// <c>ui-to-source-converters</c> attributes or in C# script with the <see cref="DataBinding.ApplyConverterGroupToSource"/> or /// <see cref="DataBinding.ApplyConverterGroupToUI"/> methods. /// </remarks> public class ConverterGroup { /// <summary> /// The group id. /// </summary> /// <remarks> /// Converter groups can be queried through <see cref="ConverterGroups.TryGetConverterGroup"/>. /// </remarks> public string id { get; } /// <summary> /// Optional and alternative name for a converter group ID, to be displayed to users to assist while authoring. /// </summary> public string displayName { get; } /// <summary> /// Optional description for a converter group ID that may include information about what this group contains /// or is used for, to be displayed to users to assist while authoring. /// </summary> public string description { get; } internal TypeConverterRegistry registry { get; } /// <summary> /// Creates a ConverterGroup. /// </summary> /// <param name="id">The group id.</param> /// <param name="displayName">The group display name.</param> /// <param name="description">The group description.</param> public ConverterGroup(string id, string displayName = null, string description = null) { this.id = id; this.displayName = displayName; this.description = description; registry = TypeConverterRegistry.Create(); } /// <summary> /// Adds a converter to the group. /// </summary> /// <param name="converter">The converter to add.</param> /// <typeparam name="TSource">The source type to convert from.</typeparam> /// <typeparam name="TDestination">The destination type to convert to.</typeparam> public void AddConverter<TSource, TDestination>(TypeConverter<TSource, TDestination> converter) { registry.Register(typeof(TSource), typeof(TDestination), converter); } /// <summary> /// Converts the specified value from <typeparamref name="TSource"/> to <typeparamref name="TDestination"/> using only the converter group. /// </summary> /// <param name="source">The source value to convert.</param> /// <param name="destination">The converted destination value if the conversion succeeded, and the default value otherwise.</param> /// <typeparam name="TSource">The source type to convert from.</typeparam> /// <typeparam name="TDestination">The destination type to convert to.</typeparam> /// <returns><see langword="true"/> if the conversion succeeded, and <see langword="false"/> otherwise.</returns> public bool TryConvert<TSource, TDestination>(ref TSource source, out TDestination destination) { if (registry.TryGetConverter(typeof(TSource), typeof(TDestination), out var converter) && converter is TypeConverter<TSource, TDestination> typedConverter) { destination = typedConverter(ref source); return true; } destination = default; return false; } /// <summary> /// Sets the value of a property at the given path to the given value, using this converter group or the global ones. /// </summary> /// <remarks> /// This method isn't thread-safe. /// </remarks> /// <param name="container">The container whose property needs to be set.</param> /// <param name="path">The path of the property to set.</param> /// <param name="value">The value to assign to the property.</param> /// <param name="returnCode">The return code of the conversion.</param> /// <typeparam name="TContainer">The container type to set the value on.</typeparam> /// <typeparam name="TValue">The value type to set.</typeparam> /// <returns><see langword="true"/> if the value was set correctly, and <see langword="false"/> otherwise.</returns> public bool TrySetValue<TContainer, TValue>(ref TContainer container, in PropertyPath path, TValue value, out VisitReturnCode returnCode) { if (path.IsEmpty) { returnCode = VisitReturnCode.InvalidPath; return false; } var visitor = SetValueVisitor<TValue>.Pool.Get(); visitor.group = this; visitor.Path = path; visitor.Value = value; try { if (!PropertyContainer.TryAccept(visitor, ref container, out returnCode)) return false; returnCode = visitor.ReturnCode; } finally { SetValueVisitor<TValue>.Pool.Release(visitor); } return returnCode == VisitReturnCode.Ok; } } readonly struct TypeConverterRegistry : IEqualityComparer<TypeConverterRegistry> { class ConverterKeyComparer : IEqualityComparer<ConverterKey> { public bool Equals(ConverterKey x, ConverterKey y) { return x.SourceType == y.SourceType && x.DestinationType == y.DestinationType; } public int GetHashCode(ConverterKey obj) { return ((obj.SourceType != null ? obj.SourceType.GetHashCode() : 0) * 397) ^ (obj.DestinationType != null ? obj.DestinationType.GetHashCode() : 0); } } static readonly ConverterKeyComparer k_Comparer = new (); readonly struct ConverterKey { public readonly Type SourceType; public readonly Type DestinationType; public ConverterKey(Type source, Type destination) { SourceType = source; DestinationType = destination; } } readonly Dictionary<ConverterKey, Delegate> m_Converters; TypeConverterRegistry(Dictionary<ConverterKey, Delegate> storage) { m_Converters = storage; } public int ConverterCount => m_Converters?.Count ?? 0; public static TypeConverterRegistry Create() { return new TypeConverterRegistry(new Dictionary<ConverterKey, Delegate>(k_Comparer)); } public void Register(Type source, Type destination, Delegate converter) { m_Converters[new ConverterKey(source, destination)] = converter ?? throw new ArgumentException(nameof(converter)); } public void Unregister(Type source, Type destination) { m_Converters.Remove(new ConverterKey(source, destination)); } internal void Apply(TypeConverterRegistry registry) { foreach (var c in registry.m_Converters) { Register(c.Key.SourceType, c.Key.DestinationType, c.Value); } } public Delegate GetConverter(Type source, Type destination) { var key = new ConverterKey(source, destination); return m_Converters.TryGetValue(key, out var converter) ? converter : null; } public bool TryGetConverter(Type source, Type destination, out Delegate converter) { converter = GetConverter(source, destination); return null != converter; } public void GetAllTypesConvertingToType(Type type, List<Type> result) { if (m_Converters == null) return; foreach (var key in m_Converters.Keys) { if (key.DestinationType == type) result.Add(key.SourceType); } } public void GetAllTypesConvertingFromType(Type type, List<Type> result) { if (m_Converters == null) return; foreach (var key in m_Converters.Keys) { if (key.SourceType == type) result.Add(key.DestinationType); } } public void GetAllConversions(List<(Type, Type)> result) { if (m_Converters == null) return; foreach (var key in m_Converters.Keys) { result.Add((key.SourceType, key.DestinationType)); } } public bool Equals(TypeConverterRegistry x, TypeConverterRegistry y) { return x.m_Converters == y.m_Converters; } public int GetHashCode(TypeConverterRegistry obj) { return (obj.m_Converters != null ? obj.m_Converters.GetHashCode() : 0); } } }
UnityCsReference/Modules/UIElements/Core/Bindings/ConverterGroup.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Bindings/ConverterGroup.cs", "repo_id": "UnityCsReference", "token_count": 4051 }
495
// 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.UIElements { internal class ClampedDragger<T> : Clickable where T : IComparable<T> { [Flags] public enum DragDirection { None = 0, LowToHigh = 1 << 0, // i.e. left-to-right, or bottom-to-top drag HighToLow = 1 << 1, // i.e. right-to-left, or top-to-bottom Free = 1 << 2 // i.e. user is dragging using the drag element, free of any direction constraint } public event System.Action dragging; public event System.Action draggingEnded; public DragDirection dragDirection { get; set; } BaseSlider<T> slider { get; set; } public Vector2 startMousePosition { get; private set; } public Vector2 delta => (lastMousePosition - startMousePosition); public ClampedDragger(BaseSlider<T> slider, System.Action clickHandler, System.Action dragHandler) : base(clickHandler, ScrollWaitDefinitions.firstWait, ScrollWaitDefinitions.regularWait) { dragDirection = DragDirection.None; this.slider = slider; dragging += dragHandler; } protected override void ProcessDownEvent(EventBase evt, Vector2 localPosition, int pointerId) { startMousePosition = localPosition; dragDirection = DragDirection.None; base.ProcessDownEvent(evt, localPosition, pointerId); // First click should behave like dragging immediately & ensure that the cursor is clamped on first touch dragging?.Invoke(); } protected override void ProcessUpEvent(EventBase evt, Vector2 localPosition, int pointerId) { base.ProcessUpEvent(evt, localPosition, pointerId); draggingEnded?.Invoke(); } protected override void ProcessMoveEvent(EventBase evt, Vector2 localPosition) { // Let base class Clickable handle the mouse event first // (although nothing much happens in the base class on pointer drag) base.ProcessMoveEvent(evt, localPosition); // Take control if we can if (dragDirection == DragDirection.None) dragDirection = DragDirection.Free; // If and when we have control, set value from drag element if (dragDirection == DragDirection.Free) { if (evt.eventTypeId == PointerMoveEvent.TypeId()) { var pointerMoveEvent = (PointerMoveEvent)evt; if (pointerMoveEvent.pointerId != PointerId.mousePointerId) pointerMoveEvent.isHandledByDraggable = true; } dragging?.Invoke(); } } } }
UnityCsReference/Modules/UIElements/Core/ClampedDragger.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/ClampedDragger.cs", "repo_id": "UnityCsReference", "token_count": 1265 }
496
// 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.Bindings; namespace UnityEngine.UIElements { [VisibleToOtherModules("UnityEditor.UIBuilderModule")] abstract class CollectionVirtualizationController { protected readonly ScrollView m_ScrollView; public abstract int firstVisibleIndex { get; protected set; } public abstract int visibleItemCount { get; } protected CollectionVirtualizationController(ScrollView scrollView) { m_ScrollView = scrollView; } public abstract void Refresh(bool rebuild); public abstract void ScrollToItem(int id); public abstract void Resize(Vector2 size); public abstract void OnScroll(Vector2 offset); public abstract int GetIndexFromPosition(Vector2 position); public abstract float GetExpectedItemHeight(int index); public abstract float GetExpectedContentHeight(); public abstract void OnFocusIn(VisualElement leafTarget); public abstract void OnFocusOut(VisualElement willFocus); public abstract void UpdateBackground(); public abstract IEnumerable<ReusableCollectionItem> activeItems { get; } internal abstract void StartDragItem(ReusableCollectionItem item); internal abstract void EndDrag(int dropIndex); public abstract void UnbindAll(); } }
UnityCsReference/Modules/UIElements/Core/Collections/Virtualization/CollectionVirtualizationController.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Collections/Virtualization/CollectionVirtualizationController.cs", "repo_id": "UnityCsReference", "token_count": 493 }
497
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Unity.Properties; using UnityEngine.Bindings; using UnityEngine.Internal; using UnityEngine.Pool; namespace UnityEngine.UIElements { /// <summary> /// A data structure for the tree view item expansion event. /// </summary> public class TreeViewExpansionChangedArgs { /// <summary> /// The id of the item being expanded or collapsed. Returns -1 when expandAll() or collapseAll() is being called. /// </summary> public int id { get; set; } /// <summary> /// Indicates whether the item is expanded (true) or collapsed (false). /// </summary> public bool isExpanded { get; set; } /// <summary> /// Indicates whether the expandAllChildren or collapsedAllChildren is applied when expanding the item. /// </summary> public bool isAppliedToAllChildren { get; set; } } /// <summary> /// Base class for a tree view, a vertically scrollable area that links to, and displays, a list of items organized in a tree. /// </summary> public abstract class BaseTreeView : BaseVerticalCollectionView { internal static readonly BindingId autoExpandProperty = nameof(autoExpand); [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal static readonly int invalidId = -1; /// <summary> /// The USS class name for TreeView elements. /// </summary> /// <remarks> /// Unity adds this USS class to every instance of the TreeView element. Any styling applied to /// this class affects every TreeView located beside, or below the stylesheet in the visual tree. /// </remarks> public new static readonly string ussClassName = "unity-tree-view"; /// <summary> /// The USS class name for TreeView item elements. /// </summary> /// <remarks> /// Unity adds this USS class to every item element of the TreeView. Any styling applied to /// this class affects every item located beside, or below the stylesheet in the visual tree. /// </remarks> public new static readonly string itemUssClassName = ussClassName + "__item"; /// <summary> /// The USS class name for TreeView item toggle elements. /// </summary> /// <remarks> /// Unity adds this USS class to every item toggle element of the TreeView. Any styling applied to /// this class affects every item located beside, or below the stylesheet in the visual tree. /// </remarks> public static readonly string itemToggleUssClassName = ussClassName + "__item-toggle"; /// <summary> /// The USS class name for TreeView indent container elements. /// </summary> /// <remarks> /// Unity adds this USS class to every indent container element of the TreeView. Any styling applied to /// this class affects every item located beside, or below the stylesheet in the visual tree. /// </remarks> [Obsolete("Individual item indents are no longer used, see itemIndentUssClassName instead", false)] public static readonly string itemIndentsContainerUssClassName = ussClassName + "__item-indents"; // Obsoleted with warning in 2023.2. /// <summary> /// The USS class name for TreeView indent element. /// </summary> /// <remarks> /// Unity adds this USS class to every indent element of the TreeView. Any styling applied to /// this class affects every item located beside, or below the stylesheet in the visual tree. /// </remarks> public static readonly string itemIndentUssClassName = ussClassName + "__item-indent"; /// <summary> /// The USS class name for TreeView item container elements. /// </summary> /// <remarks> /// Unity adds this USS class to every item container element of the TreeView. Any styling applied to /// this class affects every item located beside, or below the stylesheet in the visual tree. /// </remarks> public static readonly string itemContentContainerUssClassName = ussClassName + "__item-content"; [ExcludeFromDocs, Serializable] public new abstract class UxmlSerializedData : BaseVerticalCollectionView.UxmlSerializedData { #pragma warning disable 649 [SerializeField] bool autoExpand; [SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags autoExpand_UxmlAttributeFlags; #pragma warning restore 649 public override void Deserialize(object obj) { base.Deserialize(obj); if (ShouldWriteAttributeValue(autoExpand_UxmlAttributeFlags)) { var e = (BaseTreeView)obj; e.autoExpand = autoExpand; } } } /// <summary> /// Defines <see cref="UxmlTraits"/> for the <see cref="TreeView"/>. /// </summary> /// <remarks> /// This class defines the TreeView element properties that you can use in a UI document asset (UXML file). /// </remarks> [Obsolete("UxmlTraits is deprecated and will be removed. Use UxmlElementAttribute instead.", false)] public new class UxmlTraits : BaseVerticalCollectionView.UxmlTraits { private readonly UxmlBoolAttributeDescription m_AutoExpand = new UxmlBoolAttributeDescription { name = "auto-expand", defaultValue = false }; public override IEnumerable<UxmlChildElementDescription> uxmlChildElementsDescription { get { yield break; } } public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) { base.Init(ve, bag, cc); var treeView = (BaseTreeView)ve; treeView.autoExpand = m_AutoExpand.GetValueFromBag(bag, cc); } } /// <summary> /// Access to the itemsSource. For a TreeView, the source contains the items wrappers. /// </summary> /// <remarks> /// To set the items source, use <see cref="SetRootItems{T}"/> instead, which allows fully typed items. /// </remarks> [CreateProperty(ReadOnly = true)] public new IList itemsSource { get => viewController?.itemsSource; internal set => GetOrCreateViewController().itemsSource = value; } /// <summary> /// Raised when an item is expanded or collapsed. /// </summary> /// <remarks> /// The <see cref="TreeViewExpansionChangedArgs"/> will contain the expanded state of the item being modified. /// </remarks> public event Action<TreeViewExpansionChangedArgs> itemExpandedChanged; /// <summary> /// Sets the root items to use with the default tree view controller. /// </summary> /// <remarks> /// Root items can include their children directly. /// This will force the use of a <see cref="DefaultTreeViewController{T}"/>. /// </remarks> /// <param name="rootItems">The TreeView root items.</param> public void SetRootItems<T>(IList<TreeViewItemData<T>> rootItems) { SetRootItemsInternal(rootItems); } internal abstract void SetRootItemsInternal<T>(IList<TreeViewItemData<T>> rootItems); /// <summary> /// Gets the root item identifiers. /// </summary> /// <returns>The root item identifiers.</returns> public IEnumerable<int> GetRootIds() { return viewController.GetRootItemIds(); } /// <summary> /// Gets the TreeView's total number of items. /// </summary> /// <returns>The TreeView's total number of items.</returns> public int GetTreeCount() { return viewController.GetTreeItemsCount(); } /// <summary> /// The view controller for this view, cast as a <see cref="BaseTreeViewController"/>. /// </summary> public new BaseTreeViewController viewController => base.viewController as BaseTreeViewController; private protected override void CreateVirtualizationController() { CreateVirtualizationController<ReusableTreeViewItem>(); } /// <summary> /// Assigns the view controller for this view and registers all events required for it to function properly. /// </summary> /// <param name="controller">The controller to use with this view.</param> /// <remarks>The controller should implement <see cref="BaseTreeViewController"/>.</remarks> public override void SetViewController(CollectionViewController controller) { if (viewController != null) { viewController.itemIndexChanged -= OnItemIndexChanged; viewController.itemExpandedChanged -= OnItemExpandedChanged; } base.SetViewController(controller); if (viewController != null) { viewController.itemIndexChanged += OnItemIndexChanged; viewController.itemExpandedChanged += OnItemExpandedChanged; } } void OnItemIndexChanged(int srcIndex, int dstIndex) { RefreshItems(); } void OnItemExpandedChanged(TreeViewExpansionChangedArgs arg) { itemExpandedChanged?.Invoke(arg); } internal override ICollectionDragAndDropController CreateDragAndDropController() => new TreeViewReorderableDragAndDropController(this); bool m_AutoExpand; /// <summary> /// When true, items are automatically expanded when added to the TreeView. /// </summary> [CreateProperty] public bool autoExpand { get => m_AutoExpand; set { if (m_AutoExpand == value) return; m_AutoExpand = value; RefreshItems(); NotifyPropertyChanged(autoExpandProperty); } } [SerializeField, DontCreateProperty] private List<int> m_ExpandedItemIds; internal List<int> expandedItemIds { get => m_ExpandedItemIds; set => m_ExpandedItemIds = value; } /// <summary> /// Creates a <see cref="TreeView"/> with all default properties. /// </summary> /// <remarks> /// Use <see cref="SetRootItems{T}"/> to add content. /// </remarks> public BaseTreeView() : this((int)ItemHeightUnset) {} /// <summary> /// Creates a <see cref="TreeView"/> with specified factory methods using the fixed height virtualization method. /// </summary> /// <param name="itemHeight">The item height to use in FixedHeight virtualization mode.</param> /// <remarks> /// Use <see cref="SetRootItems{T}"/> to add content. /// </remarks> public BaseTreeView(int itemHeight) : base(null, itemHeight) { m_ExpandedItemIds = new List<int>(); AddToClassList(ussClassName); } /// <summary> /// Gets the specified TreeView item's identifier. /// </summary> /// <param name="index">The TreeView item index.</param> /// <returns>The TreeView item's identifier.</returns> public int GetIdForIndex(int index) { return viewController.GetIdForIndex(index); } /// <summary> /// Gets the specified TreeView item's parent identifier. /// </summary> /// <param name="index">The TreeView item index.</param> /// <returns>The TreeView item's parent identifier.</returns> public int GetParentIdForIndex(int index) { return viewController.GetParentId(GetIdForIndex(index)); } /// <summary> /// Gets children identifiers for the specified TreeView item. /// </summary> /// <param name="index">The TreeView item index.</param> /// <returns>The children item identifiers.</returns> public IEnumerable<int> GetChildrenIdsForIndex(int index) { return viewController.GetChildrenIdsByIndex(index); } /// <summary> /// Gets tree data for the selected item indices. /// </summary> /// <typeparam name="T">Type of the data inside TreeViewItemData.</typeparam> /// <returns>The selected TreeViewItemData items.</returns> /// <exception cref="ArgumentException">Throws if the type does not match with the item source data type of the default controller.</exception> public IEnumerable<TreeViewItemData<T>> GetSelectedItems<T>() { return GetSelectedItemsInternal<T>(); } private protected abstract IEnumerable<TreeViewItemData<T>> GetSelectedItemsInternal<T>(); /// <summary> /// Gets data for the specified TreeView item index. /// </summary> /// <param name="index">The TreeView item index.</param> /// <typeparam name="T">Type of the data inside TreeViewItemData.</typeparam> /// <returns>The TreeView item data.</returns> /// <exception cref="ArgumentException">Throws if the type does not match with the item source data type.</exception> public T GetItemDataForIndex<T>(int index) { return GetItemDataForIndexInternal<T>(index); } private protected abstract T GetItemDataForIndexInternal<T>(int index); /// <summary> /// Gets data for the specified TreeView item id. /// </summary> /// <param name="id">The TreeView item id.</param> /// <typeparam name="T">Type of the data inside TreeViewItemData.</typeparam> /// <returns>The TreeView item data.</returns> /// <exception cref="ArgumentException">Throws if the type does not match with the item source data type.</exception> public T GetItemDataForId<T>(int id) { return GetItemDataForIdInternal<T>(id); } private protected abstract T GetItemDataForIdInternal<T>(int id); /// <summary> /// Adds an item to the existing tree. /// </summary> /// <param name="item">Item to add.</param> /// <param name="parentId">The parent id for the item.</param> /// <param name="childIndex">The child index in the parent's children list.</param> /// <param name="rebuildTree">Whether we should call RebuildTree and RefreshItems or not. Set to false when doing multiple additions to save a few rebuilds.</param> /// <typeparam name="T">Type of the data inside TreeViewItemData.</typeparam> /// <exception cref="ArgumentException">Throws if the type does not match with the item source data type.</exception> public void AddItem<T>(TreeViewItemData<T> item, int parentId = -1, int childIndex = -1, bool rebuildTree = true) { AddItemInternal(item, parentId, childIndex, rebuildTree); } private protected abstract void AddItemInternal<T>(TreeViewItemData<T> item, int parentId, int childIndex, bool rebuildTree); /// <summary> /// Removes an item of the tree if it can find it. /// </summary> /// <param name="id">The item id.</param> /// <param name="rebuildTree">Whether we need to rebuild tree data. Set to false when doing multiple additions to save a few rebuilds.</param> /// <returns>If the item was removed from the tree.</returns> public bool TryRemoveItem(int id, bool rebuildTree = true) { if (viewController.TryRemoveItem(id, rebuildTree)) { RefreshItems(); return true; } return false; } internal override void OnViewDataReady() { base.OnViewDataReady(); if (viewController != null) { viewController.OnViewDataReadyUpdateNodes(); RefreshItems(); } } private protected override bool HandleItemNavigation(bool moveIn, bool altPressed) { var selectionIncrement = 1; var hasChanges = false; foreach (var selectedId in selectedIds) { var id = viewController.GetIndexForId(selectedId); if (!viewController.HasChildrenByIndex(id)) break; if (moveIn && !IsExpandedByIndex(id)) { ExpandItemByIndex(id, altPressed); hasChanges = true; } else if (!moveIn && IsExpandedByIndex(id)) { CollapseItemByIndex(id, altPressed); hasChanges = true; } } if (hasChanges) return true; if (!moveIn) { // Find the nearest ancestor with children in the tree and select it. // If no ancestor is found, find the closest item with children before the current one. var id = viewController.GetIdForIndex(selectedIndex); var ancestorId = viewController.GetParentId(id); if (ancestorId != ReusableCollectionItem.UndefinedIndex) { SetSelectionById(ancestorId); ScrollToItemById(ancestorId); return true; } selectionIncrement = -1; } bool hasChildren; // Find the next item with children in the tree and select it. var selectionIndex = selectedIndex; do { selectionIndex += selectionIncrement; hasChildren = viewController.HasChildrenByIndex(selectionIndex); } while (!hasChildren && selectionIndex >= 0 && selectionIndex < itemsSource.Count); if (hasChildren) { SetSelection(selectionIndex); ScrollToItem(selectionIndex); return true; } return false; } /// <summary> /// Sets the currently selected item by id. /// </summary> /// <remarks> /// This will also expand the selected item if not expanded already. /// </remarks> /// <param name="id">The item id.</param> public void SetSelectionById(int id) { SetSelectionById(new[] { id }); } /// <summary> /// Sets a collection of selected items by ids. /// </summary> /// <remarks> /// This will also expand the selected items if not expanded already. /// </remarks> /// <param name="ids">The item ids.</param> public void SetSelectionById(IEnumerable<int> ids) { SetSelectionInternalById(ids, true); } /// <summary> /// Sets a collection of selected items by id, without triggering a selection change callback. /// </summary> /// <remarks> /// This will also expand the selected items if not expanded already. /// </remarks> /// <param name="ids">The item ids.</param> public void SetSelectionByIdWithoutNotify(IEnumerable<int> ids) { SetSelectionInternalById(ids, false); } internal void SetSelectionInternalById(IEnumerable<int> ids, bool sendNotification) { if (ids == null) return; var selectedIndexes = ids.Select(id => GetItemIndex(id, true)).ToList(); SetSelectionInternal(selectedIndexes, sendNotification); } /// <summary> /// Adds an item to the current selection by id. /// </summary> /// <remarks> /// This will also expand the selected item if not expanded already. /// </remarks> /// <param name="id">The item id.</param> public void AddToSelectionById(int id) { var index = GetItemIndex(id, true); AddToSelection(index); } /// <summary> /// Removes an item from the current selection by id. /// </summary> /// <param name="id">The item id.</param> public void RemoveFromSelectionById(int id) { var index = GetItemIndex(id); RemoveFromSelection(index); } int GetItemIndex(int id, bool expand = false) { if (expand) { var parentId = viewController.GetParentId(id); var list = ListPool<int>.Get(); viewController.GetExpandedItemIds(list); while (parentId != -1) { if (!list.Contains(parentId)) { viewController.ExpandItem(parentId, false); } parentId = viewController.GetParentId(parentId); } ListPool<int>.Release(list); } return viewController.GetIndexForId(id); } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal void CopyExpandedStates(int sourceId, int targetId) { if (IsExpanded(sourceId)) { ExpandItem(targetId); if (viewController.HasChildren(sourceId)) { if (viewController.GetChildrenIds(sourceId).Count() != viewController.GetChildrenIds(targetId).Count()) { Debug.LogWarning("Source and target hierarchies are not the same"); return; } for (var i = 0; i < viewController.GetChildrenIds(sourceId).Count(); i++) { var sourceChild = viewController.GetChildrenIds(sourceId).ElementAt(i); var targetChild = viewController.GetChildrenIds(targetId).ElementAt(i); CopyExpandedStates(sourceChild, targetChild); } } } else { CollapseItem(targetId); } } /// <summary> /// Returns true if the specified TreeView item is expanded, false otherwise. /// </summary> /// <param name="id">The TreeView item identifier.</param> public bool IsExpanded(int id) { return viewController.IsExpanded(id); } /// <summary> /// Collapses the specified TreeView item. /// </summary> /// <param name="id">The TreeView item identifier.</param> /// <param name="collapseAllChildren">When true, all children will also get collapsed. This is false by default.</param> /// <param name="refresh">Whether to refresh items or not. Set to false when doing multiple operations on the tree, to only do one RefreshItems once all operations are done. This is true by default.</param> public void CollapseItem(int id, bool collapseAllChildren = false, bool refresh = true) { viewController.CollapseItem(id, collapseAllChildren, refresh); } /// <summary> /// Expands the specified TreeView item. /// </summary> /// <param name="id">The TreeView item identifier.</param> /// <param name="expandAllChildren">When true, all children will also get expanded. This is false by default.</param> /// <param name="refresh">Whether to refresh items or not. Set to false when doing multiple operations on the tree, to only do one RefreshItems once all operations are done. This is true by default.</param> public void ExpandItem(int id, bool expandAllChildren = false, bool refresh = true) { viewController.ExpandItem(id, expandAllChildren, refresh); } /// <summary> /// Expands all root TreeView items. /// </summary> public void ExpandRootItems() { foreach (var itemId in viewController.GetRootItemIds()) viewController.ExpandItem(itemId, false, false); RefreshItems(); } /// <summary> /// Expands all TreeView items, including children. /// </summary> public void ExpandAll() { viewController.ExpandAll(); } /// <summary> /// Collapses all TreeView items, including children. /// </summary> public void CollapseAll() { viewController.CollapseAll(); } private bool IsExpandedByIndex(int index) { return viewController.IsExpandedByIndex(index); } private void CollapseItemByIndex(int index, bool collapseAll) { if (!viewController.HasChildrenByIndex(index)) return; viewController.CollapseItemByIndex(index, collapseAll); RefreshItems(); SaveViewData(); } private void ExpandItemByIndex(int index, bool expandAll) { if (!viewController.HasChildrenByIndex(index)) return; viewController.ExpandItemByIndex(index, expandAll); RefreshItems(); SaveViewData(); } } }
UnityCsReference/Modules/UIElements/Core/Controls/BaseTreeView.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Controls/BaseTreeView.cs", "repo_id": "UnityCsReference", "token_count": 10939 }
498