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 UnityEngine; namespace UnityEditor { // Must be in sync with enum in ParticleSystemCurves.h internal enum MinMaxGradientState { k_Color = 0, k_Gradient = 1, k_RandomBetweenTwoColors = 2, k_RandomBetweenTwoGradients = 3, k_RandomColor = 4 } internal class SerializedMinMaxGradient { public SerializedProperty m_RootProperty; public SerializedProperty m_MaxGradient; public SerializedProperty m_MinGradient; public SerializedProperty m_MaxColor; public SerializedProperty m_MinColor; private SerializedProperty m_MinMaxState; public bool m_AllowColor; public bool m_AllowGradient; public bool m_AllowRandomBetweenTwoColors; public bool m_AllowRandomBetweenTwoGradients; public bool m_AllowRandomColor; public MinMaxGradientState state { get { return (MinMaxGradientState)m_MinMaxState.intValue; } set { SetMinMaxState(value); } } public bool stateHasMultipleDifferentValues { get { return m_MinMaxState.hasMultipleDifferentValues; } } public SerializedMinMaxGradient(SerializedModule m) { Init(m, "gradient"); } public SerializedMinMaxGradient(SerializedModule m, string name) { Init(m, name); } void Init(SerializedModule m, string name) { m_RootProperty = m.GetProperty(name); m_MaxGradient = m.GetProperty(name, "maxGradient"); m_MinGradient = m.GetProperty(name, "minGradient"); m_MaxColor = m.GetProperty(name, "maxColor"); m_MinColor = m.GetProperty(name, "minColor"); m_MinMaxState = m.GetProperty(name, "minMaxState"); m_AllowColor = true; m_AllowGradient = true; m_AllowRandomBetweenTwoColors = true; m_AllowRandomBetweenTwoGradients = true; m_AllowRandomColor = false; } private void SetMinMaxState(MinMaxGradientState newState) { if (newState == state) return; m_MinMaxState.intValue = (int)newState; } public static Color GetGradientAsColor(SerializedProperty gradientProp) { Gradient gradient = gradientProp.gradientValue; return gradient.constantColor; } public static void SetGradientAsColor(SerializedProperty gradientProp, Color color) { Gradient gradient = gradientProp.gradientValue; gradient.constantColor = color; // We have changed a gradient so clear preview cache UnityEditorInternal.GradientPreviewCache.ClearCache(); } } } // namespace UnityEditor
UnityCsReference/Modules/ParticleSystemEditor/SerializedMinMaxGradient.cs/0
{ "file_path": "UnityCsReference/Modules/ParticleSystemEditor/SerializedMinMaxGradient.cs", "repo_id": "UnityCsReference", "token_count": 1291 }
409
// 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/CharacterJoint.h")] [NativeClass("Unity::CharacterJoint")] public partial class CharacterJoint : Joint { extern public Vector3 swingAxis { get; set; } extern public SoftJointLimitSpring twistLimitSpring { get; set; } extern public SoftJointLimitSpring swingLimitSpring { get; set; } extern public SoftJointLimit lowTwistLimit { get; set; } extern public SoftJointLimit highTwistLimit { get; set; } extern public SoftJointLimit swing1Limit { get; set; } extern public SoftJointLimit swing2Limit { get; set; } extern public bool enableProjection { get; set; } extern public float projectionDistance { get; set; } extern public float projectionAngle { get; set; } } }
UnityCsReference/Modules/Physics/ScriptBindings/CharacterJoint.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Physics/ScriptBindings/CharacterJoint.bindings.cs", "repo_id": "UnityCsReference", "token_count": 371 }
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.Runtime.InteropServices; using Unity.Collections.LowLevel.Unsafe; namespace UnityEngine.LowLevelPhysics { public interface IGeometry { GeometryType GeometryType { get; } } [StructLayout(LayoutKind.Sequential)] public struct BoxGeometry : IGeometry { private Vector3 m_HalfExtents; public Vector3 HalfExtents { get { return m_HalfExtents; } set { m_HalfExtents = value; } } public BoxGeometry(Vector3 halfExtents) { m_HalfExtents = halfExtents; } public GeometryType GeometryType => GeometryType.Box; } [StructLayout(LayoutKind.Sequential)] public struct SphereGeometry : IGeometry { private float m_Radius; public float Radius { get { return m_Radius; } set { m_Radius = value; } } public SphereGeometry(float radius) { m_Radius = radius; } public GeometryType GeometryType => GeometryType.Sphere; } [StructLayout(LayoutKind.Sequential)] public struct CapsuleGeometry : IGeometry { private float m_Radius; private float m_HalfLength; public float Radius { get { return m_Radius; } set { m_Radius = value; } } public float HalfLength { get { return m_HalfLength; } set { m_HalfLength = value; } } public CapsuleGeometry(float radius, float halfLength) { m_Radius = radius; m_HalfLength = halfLength; } public GeometryType GeometryType => GeometryType.Capsule; } // From PxConvexMeshGeometry.h [StructLayout(LayoutKind.Sequential)] public struct ConvexMeshGeometry : IGeometry { private Vector3 m_Scale; private Quaternion m_Rotation; private IntPtr m_ConvexMesh; private byte m_MeshFlags; private byte pad1; private short pad2; private uint pad3; public Vector3 Scale { get { return m_Scale; } set { m_Scale = value; } } public Quaternion ScaleAxisRotation { get { return m_Rotation; } set { m_Rotation = value; } } public GeometryType GeometryType => GeometryType.ConvexMesh; } // From PxTriangleMeshGeometry.h [StructLayout(LayoutKind.Sequential)] public struct TriangleMeshGeometry : IGeometry { private Vector3 m_Scale; private Quaternion m_Rotation; private byte m_MeshFlags; private byte pad1; private short pad2; private IntPtr m_TriangleMesh; private uint pad3; public Vector3 Scale { get { return m_Scale; } set { m_Scale = value; } } public Quaternion ScaleAxisRotation { get { return m_Rotation; } set { m_Rotation = value; } } public GeometryType GeometryType => GeometryType.TriangleMesh; } [StructLayout(LayoutKind.Sequential)] public struct TerrainGeometry : IGeometry { private IntPtr m_TerrainData; private float m_HeightScale; private float m_RowScale; private float m_ColumnScale; private byte m_TerrainFlags; private byte pad1; private short pad2; private uint pad3; public GeometryType GeometryType => GeometryType.Terrain; } public enum GeometryType : int { Sphere = 0, Capsule = 2, Box = 3, ConvexMesh = 4, TriangleMesh = 5, Terrain = 6, Invalid = -1 } [StructLayout(LayoutKind.Sequential)] public unsafe struct GeometryHolder { // 32 | 64 private int m_Type; // 0-4 | 0-4 private UInt32 m_DataStart; // 4-8 | 4-8 private IntPtr m_FakePointer0; // 8-12 | 8-16 private IntPtr m_FakePointer1; // 12-16 | 16-24 private fixed UInt32 m_Blob[6]; // 16-40 | 24-48 private void SetGeometry<T>(T geometry) where T : struct, IGeometry { m_Type = (int)geometry.GeometryType; UnsafeUtility.CopyStructureToPtr(ref geometry, UnsafeUtility.AddressOf(ref m_DataStart)); } public T As<T>() where T : struct, IGeometry { T geometry = default(T); if ((int)geometry.GeometryType != m_Type) throw new InvalidOperationException($"Unable to get geometry of type {geometry.GeometryType} from a geometry holder that stores {m_Type}."); UnsafeUtility.CopyPtrToStructure(UnsafeUtility.AddressOf(ref m_DataStart), out geometry); return geometry; } public static GeometryHolder Create<T>(T geometry) where T : struct, IGeometry { GeometryHolder holder = new GeometryHolder() { m_DataStart = 0, m_Type = (int)GeometryType.Invalid, m_FakePointer0 = new IntPtr(0xDEADBEEF), m_FakePointer1 = new IntPtr(0xDEADBEEF) }; holder.SetGeometry<T>(geometry); return holder; } public GeometryType Type { get { return (GeometryType)m_Type; } } } }
UnityCsReference/Modules/Physics/ScriptBindings/PhysicsGeometry.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Physics/ScriptBindings/PhysicsGeometry.bindings.cs", "repo_id": "UnityCsReference", "token_count": 2356 }
411
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; namespace UnityEditor { [CustomEditor(typeof(CapsuleCollider2D))] [CanEditMultipleObjects] class CapsuleCollider2DEditor : Collider2DEditorBase { SerializedProperty m_Size; SerializedProperty m_Direction; public override void OnEnable() { base.OnEnable(); m_Size = serializedObject.FindProperty("m_Size"); m_Direction = serializedObject.FindProperty("m_Direction"); } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUILayout.EditorToolbarForTarget(EditorGUIUtility.TrTempContent("Edit Collider"), this); GUILayout.Space(5); base.OnInspectorGUI(); EditorGUILayout.PropertyField(m_Size); EditorGUILayout.PropertyField(m_Direction); FinalizeInspectorGUI(); } } }
UnityCsReference/Modules/Physics2DEditor/Managed/Colliders/CapsuleCollider2DEditor.cs/0
{ "file_path": "UnityCsReference/Modules/Physics2DEditor/Managed/Colliders/CapsuleCollider2DEditor.cs", "repo_id": "UnityCsReference", "token_count": 459 }
412
// 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(AreaEffector2D), true)] [CanEditMultipleObjects] internal class AreaEffector2DEditor : Effector2DEditor { readonly AnimBool m_ShowForceRollout = new AnimBool(); SerializedProperty m_UseGlobalAngle; SerializedProperty m_ForceAngle; SerializedProperty m_ForceMagnitude; SerializedProperty m_ForceVariation; SerializedProperty m_ForceTarget; static readonly AnimBool m_ShowDampingRollout = new AnimBool(); SerializedProperty m_Drag; SerializedProperty m_AngularDrag; public override void OnEnable() { base.OnEnable(); m_ShowForceRollout.value = true; m_ShowForceRollout.valueChanged.AddListener(Repaint); m_UseGlobalAngle = serializedObject.FindProperty("m_UseGlobalAngle"); m_ForceAngle = serializedObject.FindProperty("m_ForceAngle"); m_ForceMagnitude = serializedObject.FindProperty("m_ForceMagnitude"); m_ForceVariation = serializedObject.FindProperty("m_ForceVariation"); m_ForceTarget = serializedObject.FindProperty("m_ForceTarget"); m_ShowDampingRollout.valueChanged.AddListener(Repaint); m_Drag = serializedObject.FindProperty("m_Drag"); m_AngularDrag = serializedObject.FindProperty("m_AngularDrag"); } public override void OnDisable() { base.OnDisable(); m_ShowForceRollout.valueChanged.RemoveListener(Repaint); m_ShowDampingRollout.valueChanged.RemoveListener(Repaint); } public override void OnInspectorGUI() { base.OnInspectorGUI(); serializedObject.Update(); // Force. m_ShowForceRollout.target = EditorGUILayout.Foldout(m_ShowForceRollout.target, "Force", true); if (EditorGUILayout.BeginFadeGroup(m_ShowForceRollout.faded)) { EditorGUILayout.PropertyField(m_UseGlobalAngle); EditorGUILayout.PropertyField(m_ForceAngle); EditorGUILayout.PropertyField(m_ForceMagnitude); EditorGUILayout.PropertyField(m_ForceVariation); EditorGUILayout.PropertyField(m_ForceTarget); EditorGUILayout.Space(); } EditorGUILayout.EndFadeGroup(); // Drag. m_ShowDampingRollout.target = EditorGUILayout.Foldout(m_ShowDampingRollout.target, "Damping", true); if (EditorGUILayout.BeginFadeGroup(m_ShowDampingRollout.faded)) { EditorGUILayout.PropertyField(m_Drag); EditorGUILayout.PropertyField(m_AngularDrag); } EditorGUILayout.EndFadeGroup(); serializedObject.ApplyModifiedProperties(); } } }
UnityCsReference/Modules/Physics2DEditor/Managed/Effectors/AreaEffector2DEditor.cs/0
{ "file_path": "UnityCsReference/Modules/Physics2DEditor/Managed/Effectors/AreaEffector2DEditor.cs", "repo_id": "UnityCsReference", "token_count": 1433 }
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; using UnityEngine; namespace UnityEditor { [CustomEditor(typeof(WheelJoint2D))] [CanEditMultipleObjects] internal class WheelJoint2DEditor : AnchoredJoint2DEditor { new public void OnSceneGUI() { if (!target) return; var wheelJoint2D = (WheelJoint2D)target; // Ignore disabled joint. if (!wheelJoint2D.enabled) return; var anchor = TransformPoint(wheelJoint2D.transform, wheelJoint2D.anchor); // Draw lines for slider angle and limits Vector3 upper = anchor; Vector3 lower = anchor; Vector3 direction = RotateVector2(Vector3.right, -wheelJoint2D.suspension.angle - wheelJoint2D.transform.eulerAngles.z); Handles.color = Color.green; direction *= HandleUtility.GetHandleSize(anchor) * 0.3f; upper += direction; lower -= direction; DrawAALine(upper, lower); base.OnSceneGUI(); } } }
UnityCsReference/Modules/Physics2DEditor/Managed/Joints/WheelJoint2DEditor.cs/0
{ "file_path": "UnityCsReference/Modules/Physics2DEditor/Managed/Joints/WheelJoint2DEditor.cs", "repo_id": "UnityCsReference", "token_count": 545 }
414
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor.EditorTools; using UnityEngine; namespace UnityEditor { [CustomEditor(typeof(ConfigurableJoint)), CanEditMultipleObjects] class ConfigurableJointEditor : JointEditor<ConfigurableJoint> {} [EditorTool("Edit Configurable Joint", typeof(ConfigurableJoint))] class ConfigurableJointTool : JointTool<ConfigurableJoint> { protected override void GetActors( ConfigurableJoint joint, out Transform dynamicPose, out Transform connectedPose, out int jointFrameActorIndex, out bool rightHandedLimit ) { base.GetActors(joint, out dynamicPose, out connectedPose, out jointFrameActorIndex, out rightHandedLimit); if (joint.swapBodies) { jointFrameActorIndex = 0; rightHandedLimit = true; } } protected override void DoAngularLimitHandles(ConfigurableJoint joint) { base.DoAngularLimitHandles(joint); angularLimitHandle.xMotion = joint.angularXMotion; angularLimitHandle.yMotion = joint.angularYMotion; angularLimitHandle.zMotion = joint.angularZMotion; SoftJointLimit limit; limit = joint.lowAngularXLimit; angularLimitHandle.xMin = limit.limit; limit = joint.highAngularXLimit; angularLimitHandle.xMax = limit.limit; limit = joint.angularYLimit; angularLimitHandle.yMax = limit.limit; angularLimitHandle.yMin = -limit.limit; limit = joint.angularZLimit; angularLimitHandle.zMax = limit.limit; angularLimitHandle.zMin = -limit.limit; EditorGUI.BeginChangeCheck(); angularLimitHandle.radius = GetAngularLimitHandleSize(Vector3.zero); angularLimitHandle.DrawHandle(); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(joint, Styles.editAngularLimitsUndoMessage); limit = joint.lowAngularXLimit; limit.limit = angularLimitHandle.xMin; joint.lowAngularXLimit = limit; limit = joint.highAngularXLimit; limit.limit = angularLimitHandle.xMax; joint.highAngularXLimit = limit; limit = joint.angularYLimit; limit.limit = angularLimitHandle.yMax == limit.limit ? -angularLimitHandle.yMin : angularLimitHandle.yMax; joint.angularYLimit = limit; limit = joint.angularZLimit; limit.limit = angularLimitHandle.zMax == limit.limit ? -angularLimitHandle.zMin : angularLimitHandle.zMax; joint.angularZLimit = limit; } } } }
UnityCsReference/Modules/PhysicsEditor/ConfigurableJointEditor.cs/0
{ "file_path": "UnityCsReference/Modules/PhysicsEditor/ConfigurableJointEditor.cs", "repo_id": "UnityCsReference", "token_count": 1311 }
415
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor.EditorTools; using UnityEditor.IMGUI.Controls; using UnityEngine; namespace UnityEditor { [EditorTool("Edit Sphere Collider", typeof(SphereCollider))] class SphereColliderTool : PrimitiveColliderTool<SphereCollider> { readonly SphereBoundsHandle m_BoundsHandle = new SphereBoundsHandle(); protected override PrimitiveBoundsHandle boundsHandle { get { return m_BoundsHandle; } } protected override void CopyColliderPropertiesToHandle(SphereCollider collider) { m_BoundsHandle.center = TransformColliderCenterToHandleSpace(collider.transform, collider.center); m_BoundsHandle.radius = collider.radius * GetRadiusScaleFactor(collider); } protected override void CopyHandlePropertiesToCollider(SphereCollider collider) { collider.center = TransformHandleCenterToColliderSpace(collider.transform, m_BoundsHandle.center); float scaleFactor = GetRadiusScaleFactor(collider); collider.radius = Mathf.Approximately(scaleFactor, 0f) ? 0f : m_BoundsHandle.radius / scaleFactor; } static float GetRadiusScaleFactor(SphereCollider collider) { float result = 0f; Vector3 lossyScale = collider.transform.lossyScale; for (int axis = 0; axis < 3; ++axis) result = Mathf.Max(result, Mathf.Abs(lossyScale[axis])); return result; } } [CustomEditor(typeof(SphereCollider))] [CanEditMultipleObjects] class SphereColliderEditor : Collider3DEditorBase { SerializedProperty m_Center; SerializedProperty m_Radius; public override void OnEnable() { base.OnEnable(); m_Center = serializedObject.FindProperty("m_Center"); m_Radius = serializedObject.FindProperty("m_Radius"); } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUILayout.EditorToolbarForTarget(EditorGUIUtility.TrTempContent("Edit Collider"), this); GUILayout.Space(5); EditorGUILayout.PropertyField(m_IsTrigger, BaseStyles.triggerContent); EditorGUILayout.PropertyField(m_ProvidesContacts, BaseStyles.providesContacts); EditorGUILayout.PropertyField(m_Material, BaseStyles.materialContent); EditorGUILayout.PropertyField(m_Center, BaseStyles.centerContent); EditorGUILayout.PropertyField(m_Radius); ShowLayerOverridesProperties(); serializedObject.ApplyModifiedProperties(); } } }
UnityCsReference/Modules/PhysicsEditor/SphereColliderEditor.cs/0
{ "file_path": "UnityCsReference/Modules/PhysicsEditor/SphereColliderEditor.cs", "repo_id": "UnityCsReference", "token_count": 1143 }
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.Collections.Generic; using System.Linq; using UnityEditor.AssetImporters; using UnityEditor.Search; using UnityEngine; using UnityEngine.Search; using Object = UnityEngine.Object; namespace UnityEditor.Presets { [Obsolete("The PresetSelectorReceiver is deprecated. Please use PresetSelector.ShowSelector(Object[], Preset, bool) instead.", false)] public abstract class PresetSelectorReceiver : ScriptableObject { public virtual void OnSelectionChanged(Preset selection) {} public virtual void OnSelectionClosed(Preset selection) {} } [Obsolete("The DefaultPresetSelectorReceiver is deprecated. Please use PresetSelector.ShowSelector(Object[], Preset, bool) instead.", false)] public class DefaultPresetSelectorReceiver : PresetSelectorReceiver { Object[] m_Targets; Preset[] m_InitialValues; internal void Init(Object[] targets) { m_Targets = targets; m_InitialValues = targets.Select(a => new Preset(a)).ToArray(); } public override void OnSelectionChanged(Preset selection) { if (selection != null) { Undo.RecordObjects(m_Targets, "Apply Preset " + selection.name); foreach (var target in m_Targets) { selection.ApplyTo(target); } } else { Undo.RecordObjects(m_Targets, "Cancel Preset"); for (int i = 0; i < m_Targets.Length; i++) { m_InitialValues[i].ApplyTo(m_Targets[i]); } } } public override void OnSelectionClosed(Preset selection) { OnSelectionChanged(selection); DestroyImmediate(this); } } #pragma warning disable 618 class PresetListArea : ObjectListArea { public PresetListArea(ObjectListAreaState state, PresetSelector owner) : base(state, owner, true) { if (noneItem != null) { noneItem.m_Icon = EditorGUIUtility.LoadIcon("Preset.Current"); } } LocalGroup.ExtraItem noneItem => m_LocalAssets?.NoneList != null && m_LocalAssets.NoneList.Length > 0 ? m_LocalAssets.NoneList[0] : null; } #pragma warning restore 618 public class PresetSelector : EditorWindow { static class Style { public static GUIStyle bottomBarBg = "ProjectBrowserBottomBarBg"; public static GUIStyle toolbarBack = "ObjectPickerToolbar"; public static GUIContent presetIcon = EditorGUIUtility.IconContent("Preset.Context"); public static GUIStyle selectedPathLabel = "Label"; } // Filter string m_SearchField; IEnumerable<Preset> m_Presets; ObjectListAreaState m_ListAreaState; PresetListArea m_ListArea; // Layout const float kMinTopSize = 170; const float kMinWidth = 200; const float kPreviewMargin = 5; const float kPreviewExpandedAreaHeight = 75; const string k_PresetSelectorWidthEditorPref = "PresetSelectorWidth"; const string k_PresetSelectorHeightEditorPref = "PresetSelectorHeight"; float k_BottomBarHeight => EditorGUI.kWindowToolbarHeight; bool m_CanCreateNew; int m_ModalUndoGroup = -1; Object m_MainTarget; // get an existing ObjectSelector or create one static PresetSelector s_SharedPresetSelector = null; #pragma warning disable 618 PresetSelectorReceiver m_EventObject; #pragma warning restore 618 string m_SelectedPath; GUIContent m_SelectedPathContent = new GUIContent(); bool canCreateNewPreset => m_CanCreateNew; internal static PresetSelector get { get { if (s_SharedPresetSelector == null) { Object[] objs = Resources.FindObjectsOfTypeAll(typeof(PresetSelector)); if (objs != null && objs.Length > 0) s_SharedPresetSelector = (PresetSelector)objs[0]; if (s_SharedPresetSelector == null) s_SharedPresetSelector = CreateInstance<PresetSelector>(); } return s_SharedPresetSelector; } } [EditorHeaderItem(typeof(Object), -1001)] public static bool DrawPresetButton(Rect rectangle, Object[] targets) { var target = targets[0]; if (!target || !new PresetType(target).IsValid() || (target.hideFlags & HideFlags.NotEditable) != 0) return false; if (EditorGUI.DropdownButton(rectangle, Style.presetIcon , FocusType.Passive, EditorStyles.iconButton)) { var presetContext = new PresetContext(targets, true); ShowSelector(presetContext); } return true; } public static void ShowSelector(Object[] targets, Preset currentSelection, bool createNewAllowed) { ShowSelector(new PresetContext(targets, currentSelection, createNewAllowed)); } public static void ShowSelector(Object[] targets, Preset currentSelection, bool createNewAllowed, Action<Preset> onSelectionChanged, Action<Preset, bool> onSelectionClosed) { ShowSelector(new PresetContext(targets, currentSelection, createNewAllowed, onSelectionChanged, onSelectionClosed)); } [Obsolete("The PresetSelectorReceiver is deprecated. Please use ShowSelector(Object[], Preset, bool).", false)] public static void ShowSelector(Object target, Preset currentSelection, bool createNewAllowed, PresetSelectorReceiver eventReceiver) { get.Init(target, currentSelection, createNewAllowed, eventReceiver); } [Obsolete("The PresetSelectorReceiver is deprecated. Please use ShowSelector(Object[], Preset, bool).", false)] public static void ShowSelector(PresetType presetType, Preset currentSelection, bool createNewAllowed, PresetSelectorReceiver eventReceiver) { get.Init(presetType, currentSelection, createNewAllowed, eventReceiver); } #pragma warning disable 618 void Init(PresetType presetType, Preset currentSelection, bool createNewAllowed, PresetSelectorReceiver eventReceiver) { AssemblyReloadEvents.beforeAssemblyReload -= OnBeforeAssemblyReload; AssemblyReloadEvents.beforeAssemblyReload += OnBeforeAssemblyReload; m_ModalUndoGroup = Undo.GetCurrentGroup(); // Freeze to prevent flicker on OSX. // Screen will be updated again when calling // SetFreezeDisplay(false) further down. ContainerWindow.SetFreezeDisplay(true); // Set member variables m_SearchField = string.Empty; m_CanCreateNew = createNewAllowed; InitListArea(); m_Presets = FindAllPresetsOfType(presetType); UpdateSearchResult(currentSelection != null ? currentSelection.GetInstanceID() : 0); m_EventObject = eventReceiver; ShowWithMode(ShowMode.AuxWindow); titleContent = EditorGUIUtility.TrTextContent("Select Preset"); // Deal with window size Rect rect = m_Parent.window.position; rect.width = EditorPrefs.GetFloat(k_PresetSelectorWidthEditorPref, 200); rect.height = EditorPrefs.GetFloat(k_PresetSelectorHeightEditorPref, 200); position = rect; minSize = new Vector2(kMinWidth, kMinTopSize + kPreviewExpandedAreaHeight + 2 * kPreviewMargin); maxSize = new Vector2(500, 600); // Focus Focus(); ContainerWindow.SetFreezeDisplay(false); // Add after unfreezing display because AuxWindowManager.cpp assumes that aux windows are added after we get 'got/lost'- focus calls. m_Parent.AddToAuxWindowList(); SetSelectedPath(GetCurrentSelection()); } #pragma warning restore 618 public static ISearchView ShowSelector(PresetType presetType, Preset currentSelection, SerializedProperty presetProperty, bool createNewAllowed) { var presetContext = new PresetContext(presetType, currentSelection, presetProperty, createNewAllowed); return ShowSelector(presetContext); } internal static ISearchView ShowSelector(PresetContext presetContext) { var provider = PresetSearchProvider.CreateProvider(presetContext); var searchContext = UnityEditor.Search.SearchService.CreateContext(provider, string.Empty); var viewState = SearchViewState.CreatePickerState("Preset", searchContext, selectHandler: (item, canceled) => { Preset preset = null; if (item?.id == PresetSearchProvider.CreateItemID) preset = CreatePreset(presetContext.Target); else { preset = item?.ToObject<Preset>(); OnPresetSelected(presetContext, preset, canceled); } presetContext.OnSelectionClosed?.Invoke(preset, canceled); PresetEditorHelper.presetEditorOpen = false; }, trackingHandler: item => { var preset = item?.ToObject<Preset>(); OnPresetSelected(in presetContext, preset, false); presetContext.OnSelectionChanged?.Invoke(preset); }, filterHandler: item => OnPresetFilter(presetContext, provider, item), SearchViewFlags.CompactView | SearchViewFlags.OpenInTextMode ); viewState.windowTitle = new GUIContent("Preset Selector"); viewState.selectedIds = presetContext.CurrentSelection != null ? new[] { presetContext.CurrentSelection.GetInstanceID() } : null; PresetEditorHelper.presetEditorOpen = true; return UnityEditor.Search.SearchService.ShowPicker(viewState); } static bool OnPresetFilter(in PresetContext presetContext, SearchProvider provider, SearchItem item) { // include the clear option if (item?.id == SearchItem.clear.id) return true; // include the Create New... item if (item?.provider == provider) return true; Preset inspectedPreset = null; if (PresetEditorHelper.InspectedObjects != null && PresetEditorHelper.InspectedObjects.Length == 1 && PresetEditorHelper.InspectedObjects[0] is Preset p) inspectedPreset = p; if (item?.ToObject() is Preset preset) { return preset.GetPresetType() == presetContext.PresetType && preset != inspectedPreset; } return false; } static void OnPresetSelected(in PresetContext presetContext, Preset selection, bool canceled) { if (canceled || (selection == null && presetContext.RevertOnNullSelection)) { RevertValues(presetContext); } else { ApplyValues(presetContext, selection); } InspectorWindow.RepaintAllInspectors(); SettingsService.RepaintAllSettingsWindow(); } static void RevertValues(in PresetContext presetContext) { if (presetContext.Targets.Length != 0) { Undo.RecordObjects(presetContext.Targets, "Cancel Preset"); for (int i = 0; i < presetContext.Targets.Length; i++) { presetContext.Presets[i].ApplyTo(presetContext.Targets[i]); } } else if (presetContext.PresetProperty != null) { presetContext.PresetProperty.objectReferenceValue = presetContext.CurrentSelection; presetContext.PresetProperty.serializedObject.ApplyModifiedProperties(); } } static void ApplyValues(in PresetContext presetContext, Preset selection) { if (presetContext.Targets.Length != 0) { Undo.RecordObjects(presetContext.Targets, "Apply Preset " + selection.name); foreach (var target in presetContext.Targets) { selection.ApplyTo(target); } } else if (presetContext.PresetProperty != null && presetContext.PresetProperty.isValid) { presetContext.PresetProperty.objectReferenceValue = selection; presetContext.PresetProperty.serializedObject.ApplyModifiedProperties(); } } static string CreatePresetDialog(ref Preset preset, Object target) { if (target is AssetImporter && ApplyImportSettingsBeforeSavingPreset(ref preset, target)) return null; return EditorUtility.SaveFilePanelInProject("New Preset", preset.GetTargetTypeName(), "preset", "", ProjectWindowUtil.GetActiveFolderPath()); } static Preset CreatePreset(Object target) { // The preset picker will apply the selection when the window is disposed. // However, when creating a new preset, the preset window is closed as the save file dialog opens. // This triggers a second selection callback invocation, which we do not want. if (PresetEditorHelper.presetEditorOpen == false) return null; // Set the preset popup closed before triggering the save file dialog PresetEditorHelper.presetEditorOpen = false; var preset = new Preset(target); var path = CreatePresetDialog(ref preset, target); if (!string.IsNullOrEmpty(path)) { // If the asset already exist, we need to make sure we keep the same PPtr valid in memory. // To ensure that, we use CopySerialized on the Asset instance instead of erasing the asset with CreateAsset. var oldPreset = AssetDatabase.LoadAssetAtPath<Preset>(path); if (oldPreset != null) { EditorUtility.CopySerialized(preset, oldPreset); // replace name because it was erased by the CopySerialized oldPreset.name = System.IO.Path.GetFileNameWithoutExtension(path); AssetDatabase.SaveAssetIfDirty(oldPreset); // If the preset is opened in any inspectors/property windows, rebuild them since the preset has been overwritten var propertyEditors = Resources.FindObjectsOfTypeAll<PropertyEditor>().Where(pe => { var editor = InspectorWindowUtils.GetFirstNonImportInspectorEditor(pe.tracker.activeEditors); return editor != null && editor.targets.Any(o => o == oldPreset); }); foreach (var pe in propertyEditors) pe.tracker.ForceRebuild(); preset = oldPreset; } else { AssetDatabase.CreateAsset(preset, path); } } GUIUtility.ExitGUI(); return preset; } void OnBeforeAssemblyReload() { Close(); } #pragma warning disable 618 void Init(Object target, Preset currentSelection, bool createNewAllowed, PresetSelectorReceiver eventReceiver) { m_MainTarget = target; Init(new PresetType(target), currentSelection, createNewAllowed, eventReceiver); } #pragma warning restore 618 static IEnumerable<Preset> FindAllPresetsOfType(PresetType presetType) { // If a preset is currently inspected, it doesn't make sense for it to be applied on itself so we filter it from the list. Preset inspectedPreset = null; if (PresetEditorHelper.InspectedObjects != null && PresetEditorHelper.InspectedObjects.Length == 1 && PresetEditorHelper.InspectedObjects[0] is Preset preset) inspectedPreset = preset; return AssetDatabase.FindAssets("t:Preset") .Select(a => AssetDatabase.LoadAssetAtPath<Preset>(AssetDatabase.GUIDToAssetPath(a))) .Where(preset => preset.GetPresetType() == presetType && preset != inspectedPreset); } void InitListArea() { if (m_ListAreaState == null) m_ListAreaState = new ObjectListAreaState(); // is serialized if (m_ListArea == null) { m_ListArea = new PresetListArea(m_ListAreaState, this); m_ListArea.allowDeselection = false; m_ListArea.allowDragging = false; m_ListArea.allowFocusRendering = false; m_ListArea.allowMultiSelect = false; m_ListArea.allowRenaming = false; m_ListArea.allowBuiltinResources = false; m_ListArea.repaintCallback += Repaint; m_ListArea.itemSelectedCallback += ListAreaItemSelectedCallback; m_ListArea.gridSize = m_ListArea.minGridSize; } } void UpdateSearchResult(int currentSelection) { var searchResult = m_Presets .Where(p => p.name.ToLower().Contains(m_SearchField.ToLower())) .Select(p => p.GetInstanceID()) .ToArray(); m_ListArea.ShowObjectsInList(searchResult); m_ListArea.InitSelection(new[] { currentSelection }); } void ListAreaItemSelectedCallback(bool doubleClicked) { if (doubleClicked) { Close(); GUIUtility.ExitGUI(); } else { Preset selectedPreset = GetCurrentSelection(); if (m_EventObject != null) { m_EventObject.OnSelectionChanged(selectedPreset); } SetSelectedPath(selectedPreset); } } void SetSelectedPath(Preset selectedPreset) { m_SelectedPath = selectedPreset != null ? AssetDatabase.GetAssetPath(selectedPreset) : string.Empty; if (!string.IsNullOrEmpty(m_SelectedPath)) { m_SelectedPathContent = new GUIContent(m_SelectedPath, AssetDatabase.GetCachedIcon(m_SelectedPath)) { tooltip = m_SelectedPath }; } else { m_SelectedPathContent = new GUIContent(); } } void OnGUI() { m_ListArea.HandleKeyboard(false); HandleKeyInput(); EditorGUI.FocusTextInControl("ComponentSearch"); DrawSearchField(); var listPosition = EditorGUILayout.GetControlRect(true, GUILayout.ExpandHeight(true)); int listKeyboardControlID = GUIUtility.GetControlID(FocusType.Keyboard); m_ListArea.OnGUI(new Rect(0, listPosition.y, position.width, listPosition.height), listKeyboardControlID); DrawBottomBar(); } void DrawBottomBar() { using (new EditorGUILayout.VerticalScope(Style.bottomBarBg, GUILayout.MinHeight(k_BottomBarHeight))) { if (canCreateNewPreset) { using (new EditorGUILayout.HorizontalScope(GUIStyle.none)) { if (GUILayout.Button("Create new Preset...")) { // Since a selection change instantly applies a preset, we clear it so the previous values gets // used to create the new preset. Undo.RevertAllDownToGroup(m_ModalUndoGroup); m_ListArea.InitSelection(Array.Empty<int>()); CreatePreset(m_MainTarget); } } } using (new EditorGUILayout.HorizontalScope(GUIStyle.none, GUILayout.MinHeight(18))) { EditorGUIUtility.SetIconSize(new Vector2(16, 16)); // If not set we see icons scaling down if text is being cropped GUILayout.Label(m_SelectedPathContent, Style.selectedPathLabel); EditorGUIUtility.SetIconSize(new Vector2(0, 0)); } } } void DrawSearchField() { using (var change = new EditorGUI.ChangeCheckScope()) { GUI.SetNextControlName("ComponentSearch"); var rect = EditorGUILayout.GetControlRect(false, 24f, Style.toolbarBack); rect.height = 40f; GUI.Label(rect, GUIContent.none, Style.toolbarBack); m_SearchField = EditorGUI.SearchField(new Rect(5f, 5f, position.width - 10f, 15f), m_SearchField); if (change.changed) { UpdateSearchResult(0); } } } void HandleKeyInput() { if (Event.current.type == EventType.KeyDown) { switch (Event.current.keyCode) { case KeyCode.Escape: if (m_SearchField == string.Empty) { Cancel(); } break; case KeyCode.KeypadEnter: case KeyCode.Return: Close(); Event.current.Use(); GUIUtility.ExitGUI(); break; } } } void OnDisable() { AssemblyReloadEvents.beforeAssemblyReload -= OnBeforeAssemblyReload; if (m_EventObject != null) { m_EventObject.OnSelectionClosed(GetCurrentSelection()); } Undo.CollapseUndoOperations(m_ModalUndoGroup); EditorPrefs.SetFloat(k_PresetSelectorWidthEditorPref, position.width); EditorPrefs.SetFloat(k_PresetSelectorHeightEditorPref, position.height); } void OnDestroy() { if (m_ListArea != null) m_ListArea.OnDestroy(); } Preset GetCurrentSelection() { Preset selection = null; if (m_ListArea != null) { var id = m_ListArea.GetSelection(); if (id != null && id.Length > 0) selection = EditorUtility.InstanceIDToObject(id[0]) as Preset; } return selection; } void Cancel() { Undo.RevertAllDownToGroup(m_ModalUndoGroup); // Clear selection so that object field doesn't grab it m_ListArea.InitSelection(new int[0]); Close(); GUI.changed = true; GUIUtility.ExitGUI(); } static bool ApplyImportSettingsBeforeSavingPreset(ref Preset preset, Object target) { // make sure modifications to importer get applied before creating preset. foreach (InspectorWindow i in InspectorWindow.GetAllInspectorWindows()) { ActiveEditorTracker activeEditor = i.tracker; foreach (Editor e in activeEditor.activeEditors) { var editor = e as AssetImporterEditor; if (editor != null && editor.target == target && editor.HasModified()) { if (EditorUtility.DisplayDialog("Unapplied import settings", "Apply settings before creating a new preset", "Apply", "Cancel")) { editor.SaveChanges(); // after reimporting, the target object has changed, so update the preset with the newly imported values. preset.UpdateProperties(editor.target); return false; } return true; } } } return false; } } }
UnityCsReference/Modules/PresetsUIEditor/PresetSelector.cs/0
{ "file_path": "UnityCsReference/Modules/PresetsUIEditor/PresetSelector.cs", "repo_id": "UnityCsReference", "token_count": 12033 }
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 Unity.Collections; using UnityEngine; namespace Unity.Profiling.Editor.UI { class BottlenecksChartViewModel : IDisposable { public BottlenecksChartViewModel( int numberOfDataSeries, int dataSeriesCapacity, Color[] colors, Color invalidColor, float bottleneckThreshold) { NumberOfDataSeries = numberOfDataSeries; DataSeriesCapacity = dataSeriesCapacity; DataValueBuffers = new NativeArray<float>[numberOfDataSeries]; for (var i = 0; i < DataValueBuffers.Length; i++) DataValueBuffers[i] = new NativeArray<float>(dataSeriesCapacity, Allocator.Persistent); Colors = colors; InvalidColor = invalidColor; BottleneckThreshold = bottleneckThreshold; } // The number of data series on the chart. public int NumberOfDataSeries { get; } // The capacity of each data series on the chart. public int DataSeriesCapacity { get; } // The buffers of all data values for each data series. public NativeArray<float>[] DataValueBuffers { get; } // The colors for each data series. public Color[] Colors { get; } // The color for invalid data values in all data series. public Color InvalidColor { get; } // The value at which the data values are identified as a 'bottleneck'. public float BottleneckThreshold { get; set; } // The frame index of the first element in the data buffers. public int FirstFrameIndex { get; set; } public void Dispose() { for (var i = 0; i < DataValueBuffers.Length; i++) DataValueBuffers[i].Dispose(); } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/Bottlenecks/Chart/Data/BottlenecksChartViewModel.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/Bottlenecks/Chart/Data/BottlenecksChartViewModel.cs", "repo_id": "UnityCsReference", "token_count": 778 }
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.Collections.Generic; using System.Linq; using Unity.Profiling; using UnityEngine.UIElements; namespace UnityEditor.Profiling.ModuleEditor { class ModuleDetailsViewController : ViewController { const string k_UssSelector_CurrentModuleDetailsTitleTextField = "current-module-details__title-text-field"; const string k_UssSelector_CurrentModuleDetailsChartCountersTitleLabel = "current-module-details__chart-counters__title-label"; const string k_UssSelector_CurrentModuleDetailsChartCountersDescriptionLabel = "current-module-details__chart-counters__description-label"; const string k_UssSelector_CurrentModuleDetailsChartCountersCountLabel = "current-module-details__chart-counters__count-label"; const string k_UssSelector_CurrentModuleDetailsChartCountersRemoveSelectedToolbarButton = "current-module-details__chart-counters__remove-selected-toolbar-button"; const string k_UssSelector_CurrentModuleDetailsChartCountersSelectAllToolbarButton = "current-module-details__chart-counters__select-all-toolbar-button"; const string k_UssSelector_CurrentModuleDetailsChartCountersDeselectAllToolbarButton = "current-module-details__chart-counters__deselect-all-toolbar-button"; const string k_UssSelector_CurrentModuleDetailsChartCountersListView = "current-module-details__chart-counters__list-view"; const string k_UssSelector_CurrentModuleDetailsDeleteButton = "current-module-details__delete-button"; const string k_UssSelector_AllCountersTitleLabel = "all-counters__title-label"; const string k_UssSelector_AllCountersDescriptionLabel = "all-counters__description-label"; const string k_UssSelector_AllCountersTreeView = "all-counters__tree-view"; const string k_UssSelector_AllCountersAddSelectedToolbarButton = "all-counters__add-selected-toolbar-button"; const string k_UssSelector_ModuleDetailsConfirmButton = "module-details__confirm-button"; const string k_UssSelector_ModuleDetailsNoModuleSelectedLabel = "module-details__no-module-selected-label"; const string k_UssSelector_DragAndDropTargetHover = "drag-and-drop__drop-target--hover"; const string k_AllCountersTreeViewDataKey = "all-counters__tree-view__data-key"; const int k_MaximumTitleLength = 40; const int k_ItemHeight = 30; // Data ModuleData m_Module; List<TreeViewItemData<ModuleDetailsItemData>> m_TreeDataItems; // UI // Any members of type Button below that are suffixed 'ToolbarButton' are defined as ToolbarButtons in the UXML and are therefore ToolbarButtons at runtime. They are declared as Buttons here because we cannot use ToolbarButton (UnityEditor.UIElements) from the Editor assembly without moving this code to its own assembly/module. TextField m_TitleTextField; Label m_ChartCountersTitleLabel; Label m_ChartCountersDescriptionLabel; Label m_ChartCountersCountLabel; Button m_ChartCountersRemoveSelectedToolbarButton; Button m_ChartCountersSelectAllToolbarButton; Button m_ChartCountersDeselectAllToolbarButton; ListView m_ChartCountersListView; Button m_DeleteModuleButton; Label m_AllCountersTitleLabel; Label m_AllCountersDescriptionLabel; TreeView m_AllCountersTreeView; DefaultTreeViewController<ModuleDetailsItemData> m_AllCountersTreeViewController; Button m_AllCountersAddSelectedButton; Button m_ConfirmButton; Label m_NoModuleSelectedLabel; bool m_isConnectedToEditor; public event Action<ModuleData> onDeleteModule; public event Action onConfirmChanges; public event Action onModuleNameChanged; public ModuleDetailsViewController(bool isConnectedToEditor) { m_isConnectedToEditor = isConnectedToEditor; } public override void ConfigureView(VisualElement root) { base.ConfigureView(root); m_TitleTextField.RegisterValueChangedCallback(OnTitleChanged); m_ChartCountersTitleLabel.text = LocalizationDatabase.GetLocalizedString("Counters"); m_ChartCountersDescriptionLabel.text = LocalizationDatabase.GetLocalizedString("Add counters to be displayed by the module."); m_ChartCountersRemoveSelectedToolbarButton.text = LocalizationDatabase.GetLocalizedString("Remove Selected"); m_ChartCountersRemoveSelectedToolbarButton.clicked += RemoveSelectedCountersFromModule; m_ChartCountersSelectAllToolbarButton.text = LocalizationDatabase.GetLocalizedString("Select All"); m_ChartCountersSelectAllToolbarButton.clicked += SelectAllChartCounters; m_ChartCountersDeselectAllToolbarButton.text = LocalizationDatabase.GetLocalizedString("Deselect All"); m_ChartCountersDeselectAllToolbarButton.clicked += DeselectAllChartCounters; m_ChartCountersListView.makeItem = MakeListViewItem; m_ChartCountersListView.bindItem = BindListViewItem; m_ChartCountersListView.selectionType = SelectionType.Multiple; m_ChartCountersListView.reorderable = true; m_ChartCountersListView.fixedItemHeight = k_ItemHeight; m_ChartCountersListView.itemIndexChanged += OnListViewItemMoved; m_DeleteModuleButton.text = LocalizationDatabase.GetLocalizedString("Delete Module"); m_DeleteModuleButton.clicked += DeleteModule; m_AllCountersTitleLabel.text = LocalizationDatabase.GetLocalizedString("Available Counters"); m_AllCountersDescriptionLabel.text = LocalizationDatabase.GetLocalizedString("Select counters in the list below to add them to the selected module's counters. This list includes all built-in Unity counters, as well as any User-defined counters present upon load in the Profiler's data stream."); m_AllCountersTreeView.makeItem = MakeTreeViewItem; m_AllCountersTreeView.bindItem = BindTreeViewItem; m_AllCountersTreeView.viewDataKey = k_AllCountersTreeViewDataKey; m_AllCountersTreeView.selectionType = SelectionType.Multiple; m_AllCountersTreeView.selectedIndicesChanged += OnTreeViewSelectionChanged; m_AllCountersTreeView.itemsChosen += OnTreeViewSelectionChosen; m_AllCountersTreeView.fixedItemHeight = k_ItemHeight; m_AllCountersAddSelectedButton.text = LocalizationDatabase.GetLocalizedString("Add Selected"); m_AllCountersAddSelectedButton.clicked += AddSelectedTreeViewCountersToModule; m_ConfirmButton.text = LocalizationDatabase.GetLocalizedString("Save Changes"); m_ConfirmButton.clicked += ConfirmChanges; m_NoModuleSelectedLabel.text = LocalizationDatabase.GetLocalizedString("Select a custom module from the list or add a new custom module."); LoadAllCounters(); } public void SetModule(ModuleData module) { m_Module = module; m_ChartCountersListView.ClearSelection(); if (m_Module.isEditable) { m_TitleTextField.SetValueWithoutNotify(m_Module.localizedName); UpdateChartCountersCountLabel(); m_ChartCountersListView.itemsSource = m_Module.chartCounters; m_ChartCountersListView.Rebuild(); m_AllCountersTreeView.Rebuild(); m_NoModuleSelectedLabel.visible = false; } else { m_NoModuleSelectedLabel.visible = true; } } public void SetNoModuleSelected() { m_NoModuleSelectedLabel.visible = true; } protected override void CollectViewElements(VisualElement root) { base.CollectViewElements(root); m_TitleTextField = root.Q<TextField>(k_UssSelector_CurrentModuleDetailsTitleTextField); m_ChartCountersTitleLabel = root.Q<Label>(k_UssSelector_CurrentModuleDetailsChartCountersTitleLabel); m_ChartCountersDescriptionLabel = root.Q<Label>(k_UssSelector_CurrentModuleDetailsChartCountersDescriptionLabel); m_ChartCountersCountLabel = root.Q<Label>(k_UssSelector_CurrentModuleDetailsChartCountersCountLabel); m_ChartCountersRemoveSelectedToolbarButton = root.Q<Button>(k_UssSelector_CurrentModuleDetailsChartCountersRemoveSelectedToolbarButton); m_ChartCountersSelectAllToolbarButton = root.Q<Button>(k_UssSelector_CurrentModuleDetailsChartCountersSelectAllToolbarButton); m_ChartCountersDeselectAllToolbarButton = root.Q<Button>(k_UssSelector_CurrentModuleDetailsChartCountersDeselectAllToolbarButton); m_ChartCountersListView = root.Q<ListView>(k_UssSelector_CurrentModuleDetailsChartCountersListView); m_DeleteModuleButton = root.Q<Button>(k_UssSelector_CurrentModuleDetailsDeleteButton); m_AllCountersTitleLabel = root.Q<Label>(k_UssSelector_AllCountersTitleLabel); m_AllCountersDescriptionLabel = root.Q<Label>(k_UssSelector_AllCountersDescriptionLabel); m_AllCountersTreeView = root.Q<TreeView>(k_UssSelector_AllCountersTreeView); m_AllCountersAddSelectedButton = root.Q<Button>(k_UssSelector_AllCountersAddSelectedToolbarButton); m_ConfirmButton = root.Q<Button>(k_UssSelector_ModuleDetailsConfirmButton); m_NoModuleSelectedLabel = root.Q<Label>(k_UssSelector_ModuleDetailsNoModuleSelectedLabel); } void LoadAllCounters() { using (ProfilerMarkers.k_LoadAllCounters.Auto()) { ProfilerMarkers.k_FetchCounters.Begin(); var counterCollector = new CounterCollector(); SortedDictionary<string, List<string>> unityCounters; SortedDictionary<string, List<string>> userCounters; if (m_isConnectedToEditor) counterCollector.LoadEditorCounters(out unityCounters, out userCounters); else counterCollector.LoadCounters(out unityCounters, out userCounters); ProfilerMarkers.k_FetchCounters.End(); // Format counter data for display in tree view. ProfilerMarkers.k_FormatCountersForDisplay.Begin(); m_TreeDataItems = new List<TreeViewItemData<ModuleDetailsItemData>>(); ModuleDetailsItemData.ResetNextId(); AddCounterGroupToTreeDataItems(unityCounters, "Unity", m_TreeDataItems); AddCounterGroupToTreeDataItems(userCounters, "User", m_TreeDataItems); ProfilerMarkers.k_FormatCountersForDisplay.End(); // Update tree view UI. ProfilerMarkers.k_RebuildCountersUI.Begin(); m_AllCountersTreeView.SetRootItems(m_TreeDataItems); m_AllCountersTreeView.Rebuild(); ProfilerMarkers.k_RebuildCountersUI.End(); // Get a reference to the controller now that items are set. m_AllCountersTreeViewController = m_AllCountersTreeView.viewController as DefaultTreeViewController<ModuleDetailsItemData>; } } void AddCounterGroupToTreeDataItems(SortedDictionary<string, List<string>> counterDictionary, string groupName, List<TreeViewItemData<ModuleDetailsItemData>> treeDataItems) { if (counterDictionary.Count == 0) { return; } var groupData = new GroupItemData(groupName); var group = new TreeViewItemData<ModuleDetailsItemData>(groupData.treeViewItem.id, groupData); foreach (var categoryName in counterDictionary.Keys) { var categoryData = new CategoryItemData(categoryName); var category = new TreeViewItemData<ModuleDetailsItemData>(categoryData.treeViewItem.id, categoryData); var counters = new List<TreeViewItemData<ModuleDetailsItemData>>(); foreach (var counter in counterDictionary[categoryName]) { var data = new CounterItemData(counter, categoryName); counters.Add(new TreeViewItemData<ModuleDetailsItemData>(data.treeViewItem.id, data)); } category.AddChildren(counters); group.AddChild(category); } treeDataItems.Add(group); } VisualElement MakeListViewItem() { var listViewItem = new CounterListViewItem(); return listViewItem; } void BindListViewItem(VisualElement element, int index) { var counter = m_Module.chartCounters[index]; var counterListViewItem = element as CounterListViewItem; var titleLabel = counterListViewItem.titleLabel; titleLabel.text = counter.m_Name; } VisualElement MakeTreeViewItem() { var treeViewItem = new CounterTreeViewItem(); return treeViewItem; } void BindTreeViewItem(VisualElement element, int index) { var itemData = m_AllCountersTreeViewController.GetTreeViewItemDataForIndex(index); var treeViewItem = element as CounterTreeViewItem; var titleLabel = treeViewItem.titleLabel; titleLabel.text = itemData.data.treeViewItem.data; bool moduleHasCounter = false; if ((m_Module != null) && (itemData.data is CounterItemData counterItemData)) { var category = counterItemData.category; var counter = counterItemData.treeViewItem.data; moduleHasCounter = m_Module.ContainsChartCounter(counter, category); } treeViewItem.SetSelectable(!moduleHasCounter); } void OnTitleChanged(ChangeEvent<string> evt) { var newValue = evt.newValue; if (newValue.Length > k_MaximumTitleLength) { m_TitleTextField.SetValueWithoutNotify(evt.previousValue); return; } m_Module.SetName(evt.newValue); onModuleNameChanged?.Invoke(); } void OnTreeViewSelectionChanged(IEnumerable<int> selectedIndices) { var selectedCounterItems = new List<int>(); foreach (var index in selectedIndices.ToList()) { var selectedItem = m_AllCountersTreeViewController.GetTreeViewItemDataForIndex(index); // Only counters have no children. if (!selectedItem.hasChildren) { selectedCounterItems.Add(selectedItem.id); } else { var id = selectedItem.id; if (m_AllCountersTreeView.IsExpanded(id)) { m_AllCountersTreeView.CollapseItem(id); } else { m_AllCountersTreeView.ExpandItem(id); } } } m_AllCountersTreeView.SetSelectionByIdWithoutNotify(selectedCounterItems); } void OnTreeViewSelectionChosen(IEnumerable<object> selectedItems) { AddSelectedTreeViewCountersToModule(); } void AddSelectedTreeViewCountersToModule() { var selectedItems = m_AllCountersTreeView.selectedIndices; foreach (var index in selectedItems) { var selectedItem = m_AllCountersTreeViewController.GetTreeViewItemDataForIndex(index); var itemData = selectedItem.data; if (itemData != null && itemData is CounterItemData counterTreeViewItemData) { var counter = new ProfilerCounterData() { m_Category = counterTreeViewItemData.category, m_Name = counterTreeViewItemData.treeViewItem.data, }; AddCounterToModuleWithoutUIRefresh(counter); } } m_AllCountersTreeView.ClearSelection(); m_ChartCountersListView.Rebuild(); m_AllCountersTreeView.Rebuild(); UpdateChartCountersCountLabel(); } void AddCounterToModuleWithoutUIRefresh(ProfilerCounterData counter) { if (m_Module.hasMaximumChartCounters) { return; } if (m_Module.ContainsChartCounter(counter)) { return; } m_Module.AddChartCounter(counter); } void RemoveSelectedCountersFromModule() { var selectedIndices = m_ChartCountersListView.selectedIndices.ToList(); selectedIndices.Sort((a, b) => b.CompareTo(a)); // Ensure indices are in reverse order as we are deleting. for (int i = 0; i < selectedIndices.Count; i++) { var selectedIndex = selectedIndices[i]; m_Module.RemoveChartCounterAtIndex(selectedIndex); } m_ChartCountersListView.ClearSelection(); m_ChartCountersListView.Rebuild(); m_AllCountersTreeView.Rebuild(); UpdateChartCountersCountLabel(); } void ConfirmChanges() { onConfirmChanges?.Invoke(); } void DeleteModule() { var title = LocalizationDatabase.GetLocalizedString("Delete Module"); var localizedMessageFormat = LocalizationDatabase.GetLocalizedString("Are you sure you want to delete the module '{0}'?"); var message = string.Format(localizedMessageFormat, m_Module.localizedName); var delete = LocalizationDatabase.GetLocalizedString("Delete"); var cancel = LocalizationDatabase.GetLocalizedString("Cancel"); if (EditorUtility.DisplayDialog(title, message, delete, cancel)) { onDeleteModule.Invoke(m_Module); } } void SelectAllChartCounters() { m_ChartCountersListView.SelectAll(); } void DeselectAllChartCounters() { m_ChartCountersListView.ClearSelection(); } void UpdateChartCountersCountLabel() { m_ChartCountersCountLabel.text = $"{m_Module.chartCounters.Count}/{ModuleData.k_MaximumChartCountersCount}"; } void OnListViewItemMoved(int previousIndex, int newIndex) { m_Module.SetUpdatedEditedStateForOrderIndexChange(); } static class ProfilerMarkers { public static readonly ProfilerMarker k_LoadAllCounters = new ProfilerMarker("ModuleEditor.LoadAllCounters"); public static readonly ProfilerMarker k_FetchCounters = new ProfilerMarker("ModuleEditor.FetchCounters"); public static readonly ProfilerMarker k_FormatCountersForDisplay = new ProfilerMarker("ModuleEditor.FormatCountersForDisplay"); public static readonly ProfilerMarker k_RebuildCountersUI = new ProfilerMarker("ModuleEditor.RebuildCountersUI"); } class ModuleDetailsItemData { static int s_NextId = 0; public TreeViewItemData<string> treeViewItem { get; } public ModuleDetailsItemData(string data, List<TreeViewItemData<string>> children = null) { treeViewItem = new TreeViewItemData<string>(s_NextId++, data, children); } public static void ResetNextId() { s_NextId = 0; } } class GroupItemData : ModuleDetailsItemData { public GroupItemData(string group) : base(group) {} } class CategoryItemData : ModuleDetailsItemData { public CategoryItemData(string category) : base(category) {} } class CounterItemData : ModuleDetailsItemData { public CounterItemData(string counter, string category) : base(counter) { this.category = category; } public string category { get; } } abstract class CounterItem : VisualElement { const string k_UssClass_Label = "counter-list-view-item__label"; public CounterItem() { titleLabel = new Label(); titleLabel.AddToClassList(k_UssClass_Label); Add(titleLabel); } public Label titleLabel { get; } } class CounterListViewItem : CounterItem { const string k_UssClass = "counter-list-view-item"; public CounterListViewItem() { AddToClassList(k_UssClass); var dragIndicator = new DragIndicator(); Add(dragIndicator); dragIndicator.SendToBack(); } } class CounterTreeViewItem : CounterItem { const string k_UssClass = "counter-tree-view-item"; const string k_UssClass_Unselectable = "counter-tree-view-item__unselectable"; public CounterTreeViewItem() { AddToClassList(k_UssClass); } public void SetSelectable(bool selectable) { EnableInClassList(k_UssClass_Unselectable, !selectable); } } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ModuleEditor/ModuleDetailsViewController.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ModuleEditor/ModuleDetailsViewController.cs", "repo_id": "UnityCsReference", "token_count": 9477 }
419
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using System; using UnityEditor; using UnityEditor.Profiling; using UnityEditor.MPE; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.InteropServices; namespace UnityEditorInternal.Profiling { [Serializable] internal class ProfilerFrameDataViewBase { internal static GUIContent showFullDetailsForCallStacksContent => BaseStyles.showFullDetailsForCallStacks; protected static class BaseStyles { public static readonly GUIContent noData = EditorGUIUtility.TrTextContent("No frame data available. Select a frame from the charts above to see its details here."); public static GUIContent disabledSearchText = EditorGUIUtility.TrTextContent("Showing search results are disabled while recording with deep profiling.\nStop recording to view search results."); public static GUIContent cpuGPUTime = EditorGUIUtility.TrTextContent("CPU:{0}ms GPU:{1}ms"); public static readonly GUIStyle header = "OL title"; public static readonly GUIStyle label = "OL label"; public static readonly GUIStyle toolbar = EditorStyles.toolbar; public static readonly GUIStyle selectionExtraInfoArea = EditorStyles.helpBox; public static readonly GUIContent warningTriangle = EditorGUIUtility.IconContent("console.infoicon.inactive.sml"); public static readonly GUIStyle tooltip = new GUIStyle("AnimationEventTooltip"); public static readonly GUIStyle tooltipText = new GUIStyle("AnimationEventTooltip"); public static readonly GUIStyle tooltipArrow = "AnimationEventTooltipArrow"; public static readonly GUIStyle tooltipButton = EditorStyles.miniButton; public static readonly GUIStyle tooltipDropdown = new GUIStyle("MiniPopup"); public static readonly int tooltipButtonAreaControlId = "ProfilerTimelineTooltipButton".GetHashCode(); public static readonly int timelineTimeAreaControlId = "ProfilerTimelineTimeArea".GetHashCode(); public static readonly GUIContent tooltipCopyTooltip = EditorGUIUtility.TrTextContent("Copy", "Copy to Clipboard"); public static readonly GUIContent showDetailsDropdownContent = EditorGUIUtility.TrTextContent("Show"); public static readonly GUIContent showFullDetailsForCallStacks = EditorGUIUtility.TrTextContent("Full details for Call Stacks"); public static readonly GUIContent showSelectedSampleStacks = EditorGUIUtility.TrTextContent("Selected Sample Stack ..."); public static readonly GUIStyle viewTypeToolbarDropDown = new GUIStyle(EditorStyles.toolbarDropDownLeft); public static readonly GUIStyle threadSelectionToolbarDropDown = new GUIStyle(EditorStyles.toolbarDropDown); public static readonly GUIStyle detailedViewTypeToolbarDropDown = new GUIStyle(EditorStyles.toolbarDropDown); public static readonly GUIContent updateLive = EditorGUIUtility.TrTextContent("Live", "Display the current or selected frame while recording Playmode or Editor. This increases the overhead in the EditorLoop when the Profiler Window is repainted."); public static readonly GUIContent liveUpdateMessage = EditorGUIUtility.TrTextContent("Displaying of frame data disabled while recording Playmode or Editor. To see the data, pause recording, or toggle \"Live\" display mode on. " + "\n \"Live\" display mode increases the overhead in the EditorLoop when the Profiler Window is repainted."); public static readonly string selectionExtraInfoHierarhcyView = L10n.Tr("Selection Info: "); public static readonly string proxySampleMessage = L10n.Tr("Sample \"{0}\" {1} {2} deeper not found in this frame within the selected Sample Stack."); public static readonly string proxySampleMessageScopeSingular = L10n.Tr("scope"); public static readonly string proxySampleMessageScopePlural = L10n.Tr("scopes"); public static readonly string proxySampleMessageTooltip = L10n.Tr("Selected Sample Stack: {0}"); public static readonly string proxySampleMessagePart2TimelineView = L10n.Tr("\nClosest match:\n"); public static readonly string callstackText = LocalizationDatabase.GetLocalizedString("Call Stack:"); // 6 seems like a good default value for margins used in quite some places. Do note though, that this is little more than a semi-randomly chosen magic number. public const int magicMarginValue = 6; const float k_DetailedViewTypeToolbarDropDownWidth = 150f; public static readonly Rect tooltipArrowRect = new Rect(-32, 0, 64, 6); static BaseStyles() { viewTypeToolbarDropDown.fixedWidth = Chart.kSideWidth; viewTypeToolbarDropDown.stretchWidth = false; detailedViewTypeToolbarDropDown.fixedWidth = k_DetailedViewTypeToolbarDropDownWidth; tooltip.contentOffset = new Vector2(0, 0); tooltip.overflow = new RectOffset(0, 0, 0, 0); tooltipText = new GUIStyle(tooltip); tooltipText.onNormal.background = null; tooltipDropdown.margin.right += magicMarginValue; } } protected const string k_ShowFullDetailsForCallStacksPrefKey = "Profiler.ShowFullDetailsForCallStacks"; internal static bool showFullDetailsForCallStacks { get { return EditorPrefs.GetBool(k_ShowFullDetailsForCallStacksPrefKey, false); } set { if (value != showFullDetailsForCallStacks) { EditorPrefs.SetBool(k_ShowFullDetailsForCallStacksPrefKey, value); callStackNeedsRegeneration = true; } } } [NonSerialized] internal static bool callStackNeedsRegeneration = false; [NonSerialized] public string dataAvailabilityMessage = null; static readonly GUIContent[] kCPUProfilerViewTypeNames = new GUIContent[] { EditorGUIUtility.TrTextContent("Timeline"), EditorGUIUtility.TrTextContent("Hierarchy"), EditorGUIUtility.TrTextContent("Inverted Hierarchy"), EditorGUIUtility.TrTextContent("Raw Hierarchy"), }; static GUIContent GetCPUProfilerViewTypeName(ProfilerViewType viewType) { switch (viewType) { case ProfilerViewType.Hierarchy: return kCPUProfilerViewTypeNames[1]; case ProfilerViewType.Timeline: return kCPUProfilerViewTypeNames[0]; case ProfilerViewType.RawHierarchy: return kCPUProfilerViewTypeNames[3]; case ProfilerViewType.InvertedHierarchy: return kCPUProfilerViewTypeNames[2]; default: throw new NotImplementedException($"Lookup Not Implemented for {viewType}"); } } static readonly int[] kCPUProfilerViewTypes = new int[] { (int)ProfilerViewType.Timeline, (int)ProfilerViewType.Hierarchy, (int)ProfilerViewType.InvertedHierarchy, (int)ProfilerViewType.RawHierarchy, }; static readonly GUIContent[] kGPUProfilerViewTypeNames = new GUIContent[] { EditorGUIUtility.TrTextContent("Hierarchy"), EditorGUIUtility.TrTextContent("Raw Hierarchy") }; static readonly int[] kGPUProfilerViewTypes = new int[] { (int)ProfilerViewType.Hierarchy, (int)ProfilerViewType.RawHierarchy }; public bool gpuView { get; private set; } protected IProfilerWindowController m_ProfilerWindow; public CPUOrGPUProfilerModule cpuModule { get; private set; } public delegate void ViewTypeChangedCallback(ProfilerViewType viewType); public event ViewTypeChangedCallback viewTypeChanged = delegate {}; public virtual void OnEnable(CPUOrGPUProfilerModule cpuOrGpuModule, IProfilerWindowController profilerWindow, bool isGpuView) { m_ProfilerWindow = profilerWindow; cpuModule = cpuOrGpuModule; gpuView = isGpuView; } public virtual void OnDisable() { } protected void DrawViewTypePopup(ProfilerViewType viewType) { ProfilerViewType newViewType; if (!gpuView) { newViewType = (ProfilerViewType)EditorGUILayout.IntPopup((int)viewType, kCPUProfilerViewTypeNames, kCPUProfilerViewTypes, BaseStyles.viewTypeToolbarDropDown, GUILayout.Width(BaseStyles.viewTypeToolbarDropDown.fixedWidth)); } else { if (viewType == ProfilerViewType.Timeline || viewType == ProfilerViewType.InvertedHierarchy) viewType = ProfilerViewType.Hierarchy; newViewType = (ProfilerViewType)EditorGUILayout.IntPopup((int)viewType, kGPUProfilerViewTypeNames, kGPUProfilerViewTypes, BaseStyles.viewTypeToolbarDropDown, GUILayout.Width(BaseStyles.viewTypeToolbarDropDown.fixedWidth)); } if (newViewType != viewType) { viewTypeChanged(newViewType); GUIUtility.ExitGUI(); } } protected void DrawLiveUpdateToggle(ref bool updateViewLive) { using (new EditorGUI.DisabledScope(ProcessService.level != ProcessLevel.Main)) { // This button is only needed in the Master Process updateViewLive = GUILayout.Toggle(updateViewLive, BaseStyles.updateLive, EditorStyles.toolbarButton); } } protected void DrawCPUGPUTime(float cpuTimeMs, float gpuTimeMs) { var cpuTime = cpuTimeMs > 0 ? UnityString.Format("{0:N2}", cpuTimeMs) : "--"; var gpuTime = gpuTimeMs > 0 ? UnityString.Format("{0:N2}", gpuTimeMs) : "--"; GUILayout.Label(UnityString.Format(BaseStyles.cpuGPUTime.text, cpuTime, gpuTime), EditorStyles.toolbarLabel); } protected void ShowLargeTooltip(Vector2 pos, Rect fullRect, GUIContent content, ReadOnlyCollection<string> selectedSampleStack, float lineHeight, int frameIndex, int threadIndex, bool hasCallstack, ref float downwardsZoomableAreaSpaceNeeded, int selectedSampleIndexIfProxySelection = -1) { // Arrow of tooltip var arrowRect = BaseStyles.tooltipArrowRect; arrowRect.position += pos; var style = BaseStyles.tooltip; var size = style.CalcSize(content); var copyButtonSize = BaseStyles.tooltipButton.CalcSize(BaseStyles.tooltipCopyTooltip); var sampleStackButtonSize = new Vector2(); if (selectedSampleStack != null && selectedSampleStack.Count > 0) { sampleStackButtonSize = BaseStyles.tooltipButton.CalcSize(BaseStyles.showDetailsDropdownContent); sampleStackButtonSize.x += BaseStyles.magicMarginValue; } const int k_ButtonBottomMargin = BaseStyles.magicMarginValue; var requiredButtonHeight = Mathf.Max(copyButtonSize.y, sampleStackButtonSize.y) + k_ButtonBottomMargin; // report how big the zoomable area needs to be to be able to see the entire contents if the view is big enough downwardsZoomableAreaSpaceNeeded = arrowRect.height + size.y + requiredButtonHeight; size.y += requiredButtonHeight; size.x = Mathf.Max(size.x, copyButtonSize.x + sampleStackButtonSize.x + k_ButtonBottomMargin * 3); var heightAvailableDownwards = Mathf.Max(fullRect.yMax - arrowRect.yMax, 0); var heightAvailableUpwards = Mathf.Max(pos.y - lineHeight - arrowRect.height - fullRect.y, 0); float usedHeight = 0; float rectY = 0; // Flip tooltip if too close to bottom and there's more space above it var flipped = (arrowRect.yMax + arrowRect.height + size.y > fullRect.yMax) && heightAvailableUpwards > heightAvailableDownwards; if (flipped) { arrowRect.y -= (lineHeight + 2 * arrowRect.height); usedHeight = Mathf.Min(heightAvailableUpwards, size.y); rectY = arrowRect.y + arrowRect.height - usedHeight; } else { usedHeight = Mathf.Min(heightAvailableDownwards, size.y); rectY = arrowRect.yMax; } // The tooltip needs to have enough space (on line of text + buttons) to allow for us to but buttons in there without glitches var showButtons = usedHeight >= (requiredButtonHeight + style.CalcSize(BaseStyles.tooltipCopyTooltip).y); if (!showButtons) { size.y -= requiredButtonHeight; } // Label box var rect = new Rect(pos.x + BaseStyles.tooltipArrowRect.x, rectY, size.x, usedHeight); // Ensure it doesn't go too far right if (rect.xMax > fullRect.xMax) rect.x = Mathf.Max(fullRect.x, fullRect.xMax - rect.width); if (rect.xMax > fullRect.xMax) rect.xMax = fullRect.xMax; if (arrowRect.xMax > fullRect.xMax + 20) arrowRect.x = fullRect.xMax - arrowRect.width + 20; // Adjust left to we can always see giant (STL) names. if (rect.xMin < fullRect.xMin) rect.x = fullRect.xMin; if (arrowRect.xMin < fullRect.xMin - 20) arrowRect.x = fullRect.xMin - 20; // Draw small arrow GUI.BeginClip(arrowRect); var oldMatrix = GUI.matrix; if (flipped) GUIUtility.ScaleAroundPivot(new Vector2(1.0f, -1.0f), new Vector2(arrowRect.width * 0.5f, arrowRect.height)); GUI.Label(new Rect(0, 0, arrowRect.width, arrowRect.height), GUIContent.none, BaseStyles.tooltipArrow); GUI.matrix = oldMatrix; GUI.EndClip(); var copyButtonRect = new Rect(rect.x + k_ButtonBottomMargin, rect.yMax - copyButtonSize.y - k_ButtonBottomMargin, copyButtonSize.x, copyButtonSize.y); var selectableLabelTextRect = rect; if (showButtons) selectableLabelTextRect.yMax = copyButtonRect.y - k_ButtonBottomMargin; var buttonArea = rect; if (showButtons) buttonArea.yMin = copyButtonRect.y; // Draw tooltip if (Event.current.type == EventType.Repaint) { style.Draw(rect, false, false, false, false); } GUI.BeginClip(selectableLabelTextRect); selectableLabelTextRect.position = Vector2.zero; //var controlId = GUIUtility.GetControlID(BaseStyles.tooltipButtonAreaControlId, FocusType.Passive, buttonArea); EditorGUI.SelectableLabel(selectableLabelTextRect, content.text, style); GUI.EndClip(); if (showButtons) { // overwrite the mouse cursor for the buttons on potential splitters underneath the buttons if (Event.current.type == EventType.Repaint) { EditorGUIUtility.AddCursorRect(buttonArea, MouseCursor.Arrow); } // and steal the hot control if needed. var controlId = GUIUtility.GetControlID(BaseStyles.tooltipButtonAreaControlId, FocusType.Passive, buttonArea); var eventType = Event.current.GetTypeForControl(controlId); if (eventType == EventType.MouseDown && buttonArea.Contains(Event.current.mousePosition)) { GUIUtility.hotControl = controlId; } else if (GUIUtility.hotControl == controlId && eventType == EventType.MouseUp) { GUIUtility.hotControl = 0; } // copyButton if (GUI.Button(copyButtonRect, BaseStyles.tooltipCopyTooltip, BaseStyles.tooltipButton)) { Clipboard.stringValue = content.text; } if (selectedSampleStack != null && selectedSampleStack.Count > 0) { var sampleStackRect = new Rect(copyButtonRect.xMax + k_ButtonBottomMargin, copyButtonRect.y, sampleStackButtonSize.x, sampleStackButtonSize.y); if (EditorGUI.DropdownButton(sampleStackRect, BaseStyles.showDetailsDropdownContent, FocusType.Passive, BaseStyles.tooltipDropdown)) { var menu = new GenericMenu(); // The tooltip is already pointing to the what's currently selected, switching the view will Apply that selection in the other view menu.AddItem(GetCPUProfilerViewTypeName(ProfilerViewType.Hierarchy), false, () => { viewTypeChanged(ProfilerViewType.Hierarchy); }); menu.AddItem(GetCPUProfilerViewTypeName(ProfilerViewType.InvertedHierarchy), false, () => { viewTypeChanged(ProfilerViewType.InvertedHierarchy); }); menu.AddItem(GetCPUProfilerViewTypeName(ProfilerViewType.RawHierarchy), false, () => { viewTypeChanged(ProfilerViewType.RawHierarchy); }); menu.AddSeparator(""); if (hasCallstack) menu.AddItem(BaseStyles.showFullDetailsForCallStacks, showFullDetailsForCallStacks, () => showFullDetailsForCallStacks = !showFullDetailsForCallStacks); else menu.AddDisabledItem(BaseStyles.showFullDetailsForCallStacks, showFullDetailsForCallStacks); menu.AddSeparator(""); var rectWindowPosition = EditorGUIUtility.GUIToScreenRect(sampleStackRect).position; // Show Sample Selection : // admittedly, it'd be nice to only generate the text if sample selection option was chosen... // however, that would need to happen in an OnGui call and not within the callback of the generic menu, // to be able to calculate the needed window size and avoid glitches on first displaying it. // at least the user already clicked on the dropdown for this... string selectedSampleStackText = null; var sampleStackSb = new System.Text.StringBuilder(); for (int i = selectedSampleStack.Count - 1; i >= 0; i--) { sampleStackSb.AppendLine(selectedSampleStack[i]); } selectedSampleStackText = sampleStackSb.ToString(); string actualSampleStackText = null; if (selectedSampleIndexIfProxySelection >= 0) { using (var frameData = ProfilerDriver.GetRawFrameDataView(frameIndex, threadIndex)) { if (frameData.valid) { sampleStackSb.Clear(); string sampleName = null; var markerIdPath = new List<int>(selectedSampleStack != null ? selectedSampleStack.Count : 10); if (ProfilerTimelineGUI.GetItemMarkerIdPath(frameData, cpuModule, selectedSampleIndexIfProxySelection, ref sampleName, ref markerIdPath) >= 0) { for (int i = markerIdPath.Count - 1; i >= 0; i--) { sampleStackSb.AppendLine(frameData.GetMarkerName(markerIdPath[i])); } actualSampleStackText = sampleStackSb.ToString(); } } } } var selectionSampleStackContent = selectedSampleStack != null ? new GUIContent(selectedSampleStackText) : null; var actualSampleStackContent = actualSampleStackText != null ? new GUIContent(actualSampleStackText) : null; var sampleStackWindowSize = SelectedSampleStackWindow.CalculateSize(selectionSampleStackContent, actualSampleStackContent); menu.AddItem(BaseStyles.showSelectedSampleStacks, false, () => { SelectedSampleStackWindow.ShowSampleStackWindow(rectWindowPosition, sampleStackWindowSize, selectionSampleStackContent, actualSampleStackContent); }); menu.DropDown(sampleStackRect); } } } } internal void CompileCallStack(System.Text.StringBuilder sb, List<ulong> m_CachedCallstack, FrameDataView frameDataView) { sb.Append(BaseStyles.callstackText); sb.Append('\n'); var fullCallStack = showFullDetailsForCallStacks; foreach (var addr in m_CachedCallstack) { var methodInfo = frameDataView.ResolveMethodInfo(addr); if (string.IsNullOrEmpty(methodInfo.methodName)) { if (fullCallStack) sb.AppendFormat("0x{0:X}\n", addr); } else if (string.IsNullOrEmpty(methodInfo.sourceFileName)) { if (fullCallStack) sb.AppendFormat("0x{0:X}\t\t{1}\n", addr, methodInfo.methodName); else sb.AppendFormat("{0}\n", methodInfo.methodName); } else { var normalizedPath = methodInfo.sourceFileName.Replace('\\', '/'); if (methodInfo.sourceFileLine == 0) { if (fullCallStack) sb.AppendFormat("0x{0:X}\t\t{1}\t<a href=\"{2}\" line=\"1\">{2}</a>\n", addr, methodInfo.methodName, normalizedPath); else sb.AppendFormat("{0}\t<a href=\"{1}\" line=\"1\">{1}</a>\n", methodInfo.methodName, normalizedPath); } else { if (fullCallStack) sb.AppendFormat("0x{0:X}\t\t{1}\t<a href=\"{2}\" line=\"{3}\">{2}:{3}</a>\n", addr, methodInfo.methodName, normalizedPath, methodInfo.sourceFileLine); else sb.AppendFormat("{0}\t<a href=\"{1}\" line=\"{2}\">{1}:{2}</a>\n", methodInfo.methodName, normalizedPath, methodInfo.sourceFileLine); } } } } internal class SelectedSampleStackWindow : EditorWindow { public static class Content { public static readonly GUIContent title = EditorGUIUtility.TrTextContent("Sample Stack"); public static readonly GUIContent selectedSampleStack = EditorGUIUtility.TrTextContent("Selected Sample Stack"); public static readonly GUIContent actualSampleStack = EditorGUIUtility.TrTextContent("Actual Sample Stack"); } [NonSerialized] static GCHandle m_PinnedInstance; [SerializeField] GUIContent m_SelectedSampleStackText = null; [SerializeField] GUIContent m_ActualSampleStackText = null; static readonly Vector2 k_DefaultInitalSize = new Vector2(100, 200); [NonSerialized] bool initialized = false; public static Vector2 CalculateSize(GUIContent selectedSampleStackText, GUIContent actualSampleStackText) { var copyButtonSize = GUI.skin.button.CalcSize(BaseStyles.tooltipCopyTooltip); if (copyButtonSize.x < 2) return Vector2.zero; // Likely in a bad UI state, abort. var neededSelectedSampleStackSize = CalcSampleStackSize(Content.selectedSampleStack, selectedSampleStackText, copyButtonSize); var neededActualSampleStackSize = CalcSampleStackSize(Content.actualSampleStack, actualSampleStackText, copyButtonSize); var neededSize = new Vector2(neededSelectedSampleStackSize.x + neededActualSampleStackSize.x, Mathf.Max(neededSelectedSampleStackSize.y, neededActualSampleStackSize.y)); neededSize.y += copyButtonSize.y + BaseStyles.magicMarginValue; // keep at least a minimum size according to the initial size neededSize.x = Mathf.Max(neededSize.x, k_DefaultInitalSize.x); return neededSize; } // use SelectedSampleStackWindow.CalculateSize from within OnGui to get precalculatedSize and avoid glitches on the first frame public static void ShowSampleStackWindow(Vector2 position, Vector2 precalculatedSize, GUIContent selectedSampleStackText, GUIContent actualSampleStackText) { var window = ShowSampleStackWindowInternal(position, precalculatedSize, selectedSampleStackText, actualSampleStackText); window.titleContent = Content.title; window.initialized = precalculatedSize != Vector2.zero; } static SelectedSampleStackWindow ShowSampleStackWindowInternal(Vector2 position, Vector2 size, GUIContent selectedSampleStackText, GUIContent actualSampleStackText) { if (m_PinnedInstance.IsAllocated && m_PinnedInstance.Target != null) { var target = m_PinnedInstance.Target as SelectedSampleStackWindow; target.Close(); DestroyImmediate(target); } // can't calculate the size in here if the call does not come from an OnGui context, so going with a sane default and resizing on initialization var rect = new Rect(position, size); var window = GetWindowWithRect<SelectedSampleStackWindow>(rect, true); window.m_SelectedSampleStackText = selectedSampleStackText; window.m_ActualSampleStackText = actualSampleStackText; window.m_Parent.window.m_DontSaveToLayout = true; return window; } void OnEnable() { m_PinnedInstance = GCHandle.Alloc(this); } void OnDisable() { m_PinnedInstance.Free(); } void OnGUI() { if (m_SelectedSampleStackText == null && m_ActualSampleStackText == null) Close(); if (!initialized) { // Ugly fallback in case the size was not pre calculated... this will cause a one frame glitch var neededSize = CalculateSize(m_SelectedSampleStackText, m_ActualSampleStackText); if (neededSize != Vector2.zero) { var rect = new Rect(position.position, neededSize); position = rect; minSize = rect.size; maxSize = rect.size; initialized = true; Repaint(); } } GUILayout.BeginHorizontal(); ShowSampleStack(Content.selectedSampleStack, m_SelectedSampleStackText); ShowSampleStack(Content.actualSampleStack, m_ActualSampleStackText); GUILayout.EndHorizontal(); } static Vector2 CalcSampleStackSize(GUIContent label, GUIContent sampleStack, Vector2 copyButtonSize) { if (sampleStack != null) { var neededSelectedSampleStackSize = GUI.skin.textArea.CalcSize(sampleStack); var labelSize = GUI.skin.label.CalcSize(Content.selectedSampleStack); neededSelectedSampleStackSize.y += copyButtonSize.y + BaseStyles.magicMarginValue; neededSelectedSampleStackSize.x = Mathf.Max(neededSelectedSampleStackSize.x + BaseStyles.magicMarginValue, labelSize.x + BaseStyles.magicMarginValue); neededSelectedSampleStackSize.x = Mathf.Max(neededSelectedSampleStackSize.x + BaseStyles.magicMarginValue, copyButtonSize.x + BaseStyles.magicMarginValue); return neededSelectedSampleStackSize; } return Vector2.zero; } void ShowSampleStack(GUIContent label, GUIContent sampleStack) { if (sampleStack != null) { GUILayout.BeginVertical(); GUILayout.Label(label); GUILayout.TextArea(sampleStack.text, GUILayout.ExpandHeight(true)); if (GUILayout.Button(BaseStyles.tooltipCopyTooltip)) { Clipboard.stringValue = sampleStack.text; } GUILayout.EndVertical(); } } } public virtual void Clear() { } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerFrameViewBase.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerFrameViewBase.cs", "repo_id": "UnityCsReference", "token_count": 13859 }
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; using System.Collections.Generic; using Unity.Profiling; using Unity.Profiling.Editor; using UnityEditor; using UnityEditor.Profiling; using UnityEngine; namespace UnityEditorInternal.Profiling { [Serializable] [ProfilerModuleMetadata("File Access", typeof(LocalizationResource), IconPath = "Profiler.FileAccess")] internal class FileIOProfilerModule : ProfilerModuleBase { FileIOProfilerView m_FileIOProfilerView; static readonly string[] k_FileIOChartCounterNames = { "Files Opened", "Files Closed", "File Seeks", "Reads in Flight", "File Handles Open" }; static readonly string k_FileIOCountersCategoryName = ProfilerCategory.FileIO.Name; public FileIOProfilerModule() : base(ProfilerModuleChartType.Line) {} private protected override int defaultOrderIndex => 14; internal override void OnEnable() { base.OnEnable(); if (m_FileIOProfilerView == null) { m_FileIOProfilerView = new FileIOProfilerView(); } } private protected override bool ReadActiveState() { return EditorPrefs.GetBool(activeStatePreferenceKey, false); } private protected override void SaveActiveState() { EditorPrefs.SetBool(activeStatePreferenceKey, active); } public override void DrawToolbar(Rect position) { m_FileIOProfilerView.DrawToolbar(position); } public override void DrawDetailsView(Rect position) { m_FileIOProfilerView?.DrawUIPane(ProfilerWindow); } protected override List<ProfilerCounterData> CollectDefaultChartCounters() { var chartCounters = new List<ProfilerCounterData>(k_FileIOChartCounterNames.Length); foreach (var counterName in k_FileIOChartCounterNames) { chartCounters.Add(new ProfilerCounterData() { m_Name = counterName, m_Category = k_FileIOCountersCategoryName, }); } return chartCounters; } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/FileIO/FileIOProfilerModule.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/FileIO/FileIOProfilerModule.cs", "repo_id": "UnityCsReference", "token_count": 1044 }
421
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Unity.Profiling.Editor; using UnityEditor; using UnityEditor.Profiling; using UnityEngine; using System.Globalization; namespace UnityEditorInternal.Profiling { [Serializable] internal abstract class ProfilerModuleBase : ProfilerModule { protected List<ProfilerCounterData> m_LegacyChartCounters; protected List<ProfilerCounterData> m_LegacyDetailCounters; [SerializeField] protected Vector2 m_PaneScroll; // We cannot provide counters in the constructor for legacy modules. All concrete module types now use a parameterless constructor that invokes this base constructor, causing this to be called in serialization. Access to ProfilerDriver.GetGraphStatisticsPropertiesForArea is banned during (de)serialization, which is used by these modules to construct their counter lists. Therefore, we initialize with a null list and provide it later in Initialize(). protected ProfilerModuleBase(ProfilerModuleChartType defaultChartType = ProfilerModuleChartType.Line) : base(null, defaultChartType) {} internal override void LegacyModuleInitialize() { base.LegacyModuleInitialize(); // Construct legacy counter lists. m_LegacyChartCounters = CollectDefaultChartCounters(); if (m_LegacyChartCounters.Count > maximumNumberOfChartCounters) { throw new ArgumentException($"Chart counters cannot contain more than {maximumNumberOfChartCounters} counters."); } m_LegacyDetailCounters = CollectDefaultDetailCounters(); InternalUpdateBaseCountersAndAutoEnabledCategoryNames(); } public ReadOnlyCollection<ProfilerCounterData> chartCounters => m_LegacyChartCounters.AsReadOnly(); public ReadOnlyCollection<ProfilerCounterData> detailCounters => m_LegacyDetailCounters.AsReadOnly(); // Modules that use legacy stats override `usesCounters` to use the legacy GetGraphStatisticsPropertiesForArea functionality instead of Profiler Counters. public virtual bool usesCounters => true; private protected override string activeStatePreferenceKey { get { if (!string.IsNullOrEmpty(legacyPreferenceKey)) { // Use the legacy preference key to maintain user settings on built-in modules. return legacyPreferenceKey; } return base.activeStatePreferenceKey; } } int maximumNumberOfChartCounters { get => ProfilerChart.k_MaximumSeriesCount; } public virtual void DrawToolbar(Rect position) {} public virtual void DrawDetailsView(Rect position) {} public override ProfilerModuleViewController CreateDetailsViewController() { return new LegacyDetailsViewController(ProfilerWindow, this); } public void SetCounters(List<ProfilerCounterData> chartCounters, List<ProfilerCounterData> detailCounters) { if (chartCounters.Count > maximumNumberOfChartCounters) { throw new ArgumentException($"Chart counters cannot contain more than {maximumNumberOfChartCounters} counters."); } if (active) { // Release existing categories prior to updating counters. ProfilerWindow.SetCategoriesInUse(GetAutoEnabledCategoryNames, false); } // Capture each chart counter's enabled state prior to assignment. Dictionary<ProfilerCounterData, bool> counterEnabledStates = null; if (m_Chart != null) { counterEnabledStates = new Dictionary<ProfilerCounterData, bool>(); for (int i = 0; i < m_LegacyChartCounters.Count; ++i) { var counter = m_LegacyChartCounters[i]; var enabled = m_Chart.m_Series[i].enabled; counterEnabledStates.Add(counter, enabled); } } m_LegacyChartCounters = chartCounters; m_LegacyDetailCounters = detailCounters; InternalUpdateBaseCountersAndAutoEnabledCategoryNames(); if (Chart != null) RebuildChart(); // Restore each chart counter's enabled state after assignment. if (counterEnabledStates != null && counterEnabledStates.Count > 0) { for (int i = 0; i < m_LegacyChartCounters.Count; ++i) { var counter = m_LegacyChartCounters[i]; bool enabled; if (!counterEnabledStates.TryGetValue(counter, out enabled)) { // A new counter is enabled by default. enabled = true; } m_Chart.m_Series[i].enabled = enabled; } } if (active) { // Retain new categories after updating counters. ProfilerWindow.SetCategoriesInUse(GetAutoEnabledCategoryNames, true); } } /// <summary> /// Override this method to customize the text displayed in the module's details view. /// </summary> protected virtual string GetDetailsViewText() { string detailsViewText = (usesCounters) ? ConstructTextSummaryFromDetailCounters() : ProfilerDriver.GetOverviewText(area, ProfilerWindow.GetActiveVisibleFrameIndex()); return detailsViewText; } /// <summary> /// Override this method to provide the module's default chart counters. Modules that define a ProfilerArea, and therefore use legacy stats instead of counters, do not need to override this method. /// </summary> protected virtual List<ProfilerCounterData> CollectDefaultChartCounters() { var chartCounters = new List<ProfilerCounterData>(); if (!usesCounters) { // Legacy modules can define ProfilerArea-based stats instead of counters. In that case, convert the area to a category name. var legacyStats = ProfilerDriver.GetGraphStatisticsPropertiesForArea(area); var categoryName = LegacyProfilerAreaUtility.ProfilerAreaToCategoryName(area); foreach (var legacyStatName in legacyStats) { var counter = new ProfilerCounterData() { m_Category = categoryName, m_Name = legacyStatName, }; chartCounters.Add(counter); } } return chartCounters; } /// <summary> /// Override this method to provide the module's default detail counters. /// </summary> protected virtual List<ProfilerCounterData> CollectDefaultDetailCounters() { return new List<ProfilerCounterData>(); } protected void DrawEmptyToolbar() { EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); } protected void DrawDetailsViewText(Rect position) { string activeText = GetDetailsViewText(); 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 static long GetCounterValue(FrameDataView frameData, string name) { var id = frameData.GetMarkerId(name); if (id == FrameDataView.invalidMarkerId) return -1; return frameData.GetCounterValueAsLong(id); } protected static string GetCounterValueAsBytes(FrameDataView frameData, string name) { var id = frameData.GetMarkerId(name); if (id == FrameDataView.invalidMarkerId) return "N/A"; return EditorUtility.FormatBytes(frameData.GetCounterValueAsLong(id)); } protected static string GetCounterValueAsNumber(FrameDataView frameData, string name) { var id = frameData.GetMarkerId(name); if (id == FrameDataView.invalidMarkerId) return "N/A"; return FormatNumber(frameData.GetCounterValueAsLong(id)); } protected static string FormatNumber(long num) { if (num < 1000) return num.ToString(CultureInfo.InvariantCulture.NumberFormat); if (num < 1000000) return (num * 0.001).ToString("f1", CultureInfo.InvariantCulture.NumberFormat) + "k"; return (num * 0.000001).ToString("f1", CultureInfo.InvariantCulture.NumberFormat) + "M"; } string ConstructTextSummaryFromDetailCounters() { string detailsViewText = null; using (var rawFrameDataView = ProfilerDriver.GetRawFrameDataView(ProfilerWindow.GetActiveVisibleFrameIndex(), 0)) { if (rawFrameDataView.valid) { var stringBuilder = new System.Text.StringBuilder(); foreach (var counterData in m_LegacyDetailCounters) { var category = counterData.m_Category; var counter = counterData.m_Name; var counterValue = ProfilerDriver.GetFormattedCounterValue(rawFrameDataView.frameIndex, category, counter); stringBuilder.AppendLine($"{counter}: {counterValue}"); } detailsViewText = stringBuilder.ToString(); } } return detailsViewText; } public void SetNameAndUpdateAllPreferences(string name) { EditorPrefs.DeleteKey(activeStatePreferenceKey); EditorPrefs.DeleteKey(orderIndexPreferenceKey); SetName(name); SaveActiveState(); orderIndex = orderIndex; m_Chart.SetName(DisplayName, legacyPreferenceKey); } // ProfilerModule (base class) does not publicly support changing the chart's counters - it expects it to remain constant. We can do this internally from ProfilerModuleBase as long as we also update the auto-enabled category names. void InternalUpdateBaseCountersAndAutoEnabledCategoryNames() { // Pass legacy counter lists to base module. InternalSetChartCounters(ProfilerCounterDataUtility.ConvertFromLegacyCounterDatas(m_LegacyChartCounters)); // Construct auto-enabled category names from chart and detail counters. var categories = new HashSet<string>(); foreach (var chartCounter in chartCounters) { var categoryName = chartCounter.m_Category; categories.Add(categoryName); } foreach (var detailCounter in detailCounters) { var categoryName = detailCounter.m_Category; categories.Add(categoryName); } var autoEnabledCategoryNames = new string[categories.Count]; categories.CopyTo(autoEnabledCategoryNames); // Pass auto-enabled category names to base module. InternalSetAutoEnabledCategoryNames(autoEnabledCategoryNames); } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/ProfilerModuleBase.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/ProfilerModuleBase.cs", "repo_id": "UnityCsReference", "token_count": 5143 }
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.Collections.Generic; using Unity.Profiling.Editor; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.Profiling { [UIFramework(UIFrameworkUsage.UITK)] internal class ProfilerModulesDropdownWindow : EditorWindow { const string k_UxmlResourceName = "ProfilerModulesDropdownWindow.uxml"; const string k_UssSelectorModuleEditorWindowDark = "profiler-modules-dropdown-window__dark"; const string k_UssSelectorModuleEditorWindowLight = "profiler-modules-dropdown-window__light"; const string k_UssSelector_ListView = "modules__list-view"; const string k_UssSelector_ConfigureButton = "modules__toolbar__configure-button"; const string k_UssSelector_ConfigureIcon = "modules__toolbar__configure-icon"; const string k_UssSelector_RestoreDefaultsButton = "modules__toolbar__restore-defaults-button"; const int k_WindowWidth = 250; const int k_ListViewItemHeight = 26; const int k_ToolbarHeight = 30; const int k_TotalBorderHeight = 2; static long s_LastClosedTime; // Data bool m_IsInitialized; List<ProfilerModule> m_Modules; bool m_BottleneckViewVisible; // Temporary workaround whilst Bottleneck is not a module due to upcoming transition to UIToolkit. // UI ListView m_ModulesListView; ModuleListViewItem m_BottlenecksItem; public IResponder responder { get; set; } public static bool TryPresentIfNoOpenInstances(Rect buttonRect, List<ProfilerModule> modules, bool bottleneckViewVisible, out ProfilerModulesDropdownWindow window) { /* Due to differences in the timing of Editor window destruction across platforms, we cannot easily detect if the window was just destroyed due to being unfocussed with EditorWindow.HasOpenInstances alone. We need to detect this situation in the case of clicking the dropdown control whilst the window is open - this should close the window. Following the advice of the Editor team, this timer pattern is copied from LayerSettingsWindow as this is how they work around the issue. realtimeSinceStartUp is not used since it is set to 0 when entering/exiting playmode, we assume an increasing time when comparing time. */ long nowMilliSeconds = System.DateTime.Now.Ticks / System.TimeSpan.TicksPerMillisecond; bool justClosed = nowMilliSeconds < s_LastClosedTime + 50; if (HasOpenInstances<ProfilerModulesDropdownWindow>() || justClosed) { window = null; return false; } window = GetWindowDontShow<ProfilerModulesDropdownWindow>(); window.Initialize(modules, bottleneckViewVisible); const int k_ExtraRowForBottleneck = k_ListViewItemHeight; var windowHeight = (k_ListViewItemHeight * modules.Count) + k_ToolbarHeight + k_TotalBorderHeight + k_ExtraRowForBottleneck; var windowSize = new Vector2(k_WindowWidth, windowHeight); window.ShowAsDropDown(buttonRect, windowSize); window.Focus(); return true; } void Initialize(List<ProfilerModule> modules, bool bottleneckViewVisible) { if (m_IsInitialized) { return; } m_Modules = modules; m_BottleneckViewVisible = bottleneckViewVisible; m_IsInitialized = true; BuildWindow(); } void BuildWindow() { var template = EditorGUIUtility.Load(k_UxmlResourceName) as VisualTreeAsset; template.CloneTree(rootVisualElement); var themeUssClass = (EditorGUIUtility.isProSkin) ? k_UssSelectorModuleEditorWindowDark : k_UssSelectorModuleEditorWindowLight; rootVisualElement.AddToClassList(themeUssClass); // Temporary workaround whilst Bottleneck is not a module due to upcoming transition to UIToolkit. m_BottlenecksItem = new ModuleListViewItem() { style = { height = k_ListViewItemHeight, paddingTop = 1, paddingRight = 1, paddingBottom = 1, paddingLeft = 1, } }; m_BottlenecksItem.Configure("Highlights", m_BottleneckViewVisible); m_BottlenecksItem.RegisterCallback<ClickEvent>(OnBottlenecksSelected); rootVisualElement.Insert(0, m_BottlenecksItem); m_ModulesListView = rootVisualElement.Q<ListView>(k_UssSelector_ListView); m_ModulesListView.fixedItemHeight = k_ListViewItemHeight; m_ModulesListView.makeItem = MakeListViewItem; m_ModulesListView.bindItem = BindListViewItem; m_ModulesListView.selectionType = SelectionType.Single; m_ModulesListView.selectionChanged += OnModuleSelected; m_ModulesListView.itemsSource = m_Modules; var configureButton = rootVisualElement.Q<Button>(k_UssSelector_ConfigureButton); configureButton.clicked += ConfigureModules; var configureIcon = rootVisualElement.Q<VisualElement>(k_UssSelector_ConfigureIcon); configureIcon.style.backgroundImage = Styles.configureIcon; var restoreDefaultsButton = rootVisualElement.Q<Button>(k_UssSelector_RestoreDefaultsButton); restoreDefaultsButton.text = LocalizationDatabase.GetLocalizedString("Restore Defaults"); restoreDefaultsButton.clicked += RestoreDefaults; } void OnDisable() { s_LastClosedTime = System.DateTime.Now.Ticks / System.TimeSpan.TicksPerMillisecond; } void OnModuleSelected(IEnumerable<object> selectedItems) { var selectedIndex = m_ModulesListView.selectedIndex; if (selectedIndex < 0) { return; } var selectedModule = m_Modules[selectedIndex]; selectedModule.ToggleActive(); m_ModulesListView.Rebuild(); m_ModulesListView.ClearSelection(); responder?.OnModuleActiveStateChanged(); } void OnBottlenecksSelected(ClickEvent evt) { m_BottleneckViewVisible = !m_BottleneckViewVisible; responder?.OnBottlenecksActiveStateChanged(m_BottleneckViewVisible); m_BottlenecksItem.SetActive(m_BottleneckViewVisible); } void ConfigureModules() { responder?.OnConfigureModules(); Close(); } void RestoreDefaults() { var title = LocalizationDatabase.GetLocalizedString("Restore Defaults"); var message = LocalizationDatabase.GetLocalizedString("Do you want to restore the default Profiler Window modules? All custom modules will be deleted and the order of modules will be reset."); var restoreDefaults = LocalizationDatabase.GetLocalizedString("Restore Defaults"); var cancel = LocalizationDatabase.GetLocalizedString("Cancel"); bool proceed = EditorUtility.DisplayDialog(title, message, restoreDefaults, cancel); if (proceed) { responder?.OnRestoreDefaultModules(); } Close(); } VisualElement MakeListViewItem() { return new ModuleListViewItem(); } void BindListViewItem(VisualElement element, int index) { var module = m_Modules[index]; var moduleListViewItem = element as ModuleListViewItem; moduleListViewItem.ConfigureWithModule(module); } static class Styles { public static readonly Texture2D configureIcon = EditorGUIUtility.LoadIcon("SettingsIcon"); } class ModuleListViewItem : VisualElement { const string k_UssClass = "module-list-view-item"; const string k_UssClass_Icon = "module-list-view-item__icon"; const string k_UssClass_Label = "module-list-view-item__label"; const string k_UssClass_WarningIcon = "module-list-view-item__warning-icon"; Image m_Icon; Label m_Label; Image m_WarningIcon; public ModuleListViewItem() { AddToClassList(k_UssClass); m_Icon = new Image { scaleMode = ScaleMode.ScaleToFit }; m_Icon.AddToClassList(k_UssClass_Icon); Add(m_Icon); m_Label = new Label(); m_Label.AddToClassList(k_UssClass_Label); Add(m_Label); m_WarningIcon = new Image { scaleMode = ScaleMode.ScaleToFit, image = EditorGUIUtility.LoadIcon("console.warnicon.sml") }; m_WarningIcon.AddToClassList(k_UssClass_WarningIcon); Add(m_WarningIcon); } public void ConfigureWithModule(ProfilerModule module) { Configure(module.DisplayName, module.active, module.WarningMsg); } public void Configure(string displayName, bool active, string warningMsg = null) { m_Label.text = displayName; SetActive(active); if (!string.IsNullOrEmpty(warningMsg)) { m_WarningIcon.style.visibility = Visibility.Visible; m_WarningIcon.tooltip = warningMsg; } else m_WarningIcon.style.visibility = Visibility.Hidden; } public void SetActive(bool active) { var icon = (active) ? Styles.activeIcon : Styles.inactiveIcon; m_Icon.image = icon; } static class Styles { public static readonly Texture2D inactiveIcon = EditorGUIUtility.LoadIcon("toggle_bg"); public static readonly Texture2D activeIcon = EditorGUIUtility.LoadIcon("toggle_on"); } } public interface IResponder { void OnModuleActiveStateChanged(); void OnConfigureModules(); void OnRestoreDefaultModules(); // Temporary workaround whilst Bottleneck is not a module due to upcoming transition to UIToolkit. void OnBottlenecksActiveStateChanged(bool active); } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModulesDropdownWindow.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModulesDropdownWindow.cs", "repo_id": "UnityCsReference", "token_count": 4773 }
423
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEditorInternal; using UnityEngine; namespace UnityEditor.Profiling { internal enum ProfilerEditorTargetMode { Playmode, Editmode } internal class ProfilerUserSettings { // User setting keys. Don't localize! const string k_SettingsPrefix = "Profiler."; public const string k_FrameCountSettingKey = k_SettingsPrefix + "FrameCount"; public const string k_ProfilerOutOfProcessSettingKey = k_SettingsPrefix + "OutOfProcess"; public const string k_RememberLastRecordStateSettingKey = k_SettingsPrefix + "RememberLastRecordState"; public const string k_DefaultRecordStateSettingKey = k_SettingsPrefix + "DefaultRecordState"; public const string k_DefaultTargetModeSettingKey = k_SettingsPrefix + "DefaultTargetMode"; public const string k_ShowStatsLabelsOnCurrentFrameSettingKey = k_SettingsPrefix + "ShowStatsLabelsOnCurrentFrame"; public const string k_CustomConnectionID = k_SettingsPrefix + "CustomConnectionID"; public const string k_TargetFramesPerSecond = k_SettingsPrefix + "TargetFramesPerSecond"; public const int kMinFrameCount = 300; public const int kMaxFrameCount = 2000; public const int k_MinimumTargetFramesPerSecond = 1; public const int k_MaximumTargetFramesPerSecond = 1000; private const int kMaxCustomIDLength = 26; [SerializeField] private static int m_FrameCount = 0; public static Action settingsChanged; public static event Action targetFramesPerSecondChanged; public static int frameCount { get { if (m_FrameCount == 0) { var value = EditorPrefs.GetInt(k_FrameCountSettingKey, kMinFrameCount); m_FrameCount = Mathf.Clamp(value, kMinFrameCount, kMaxFrameCount); ProfilerDriver.SetMaxFrameHistoryLength(m_FrameCount); } return m_FrameCount; } set { if (value < 0 || value > kMaxFrameCount) throw new ArgumentOutOfRangeException(nameof(frameCount), value, $"must be between {0} and {kMaxFrameCount}"); if (value != m_FrameCount) { m_FrameCount = value; EditorPrefs.SetInt(k_FrameCountSettingKey, value); ProfilerDriver.SetMaxFrameHistoryLength(value); if (settingsChanged != null) settingsChanged.Invoke(); } } } public static bool rememberLastRecordState { get { return EditorPrefs.GetBool(k_RememberLastRecordStateSettingKey, false); } set { EditorPrefs.SetBool(k_RememberLastRecordStateSettingKey, value); } } public static bool defaultRecordState { get { return EditorPrefs.GetBool(k_DefaultRecordStateSettingKey, true); } set { EditorPrefs.SetBool(k_DefaultRecordStateSettingKey, value); } } public static bool showStatsLabelsOnCurrentFrame { get { return EditorPrefs.GetBool(k_ShowStatsLabelsOnCurrentFrameSettingKey, false); } set { EditorPrefs.SetBool(k_ShowStatsLabelsOnCurrentFrameSettingKey, value); } } public static ProfilerEditorTargetMode defaultTargetMode { get { return (ProfilerEditorTargetMode)EditorPrefs.GetInt(k_DefaultTargetModeSettingKey, (int)ProfilerEditorTargetMode.Playmode); } set { EditorPrefs.SetInt(k_DefaultTargetModeSettingKey, (int)value); } } public static string customConnectionID { get => EditorPrefs.GetString(k_CustomConnectionID, ""); set { if (value.Length > kMaxCustomIDLength) { value = value.Substring(0, kMaxCustomIDLength); Debug.LogWarning($"Custom Connection ID is capped at {kMaxCustomIDLength} characters in length."); } EditorPrefs.SetString(k_CustomConnectionID, value); } } public static int targetFramesPerSecond { get => EditorPrefs.GetInt(k_TargetFramesPerSecond, 60); set { if (value < k_MinimumTargetFramesPerSecond || value > k_MaximumTargetFramesPerSecond) throw new ArgumentOutOfRangeException(nameof(targetFramesPerSecond)); EditorPrefs.SetInt(k_TargetFramesPerSecond, value); targetFramesPerSecondChanged?.Invoke(); } } public static void Refresh() { // Reset all cached values to force fetching it from the settings registry. m_FrameCount = 0; } public static bool ValidCustomConnectionID(string id) { return !id.Contains("\"") && !id.Contains("*") && id.Length <= kMaxCustomIDLength; } } }
UnityCsReference/Modules/ProfilerEditor/Public/ProfilerSettings.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/Public/ProfilerSettings.cs", "repo_id": "UnityCsReference", "token_count": 2278 }
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 System.Collections.Generic; using Unity.Properties.Internal; namespace Unity.Properties { /// <summary> /// Scope for using a given set of attributes. /// </summary> public readonly struct AttributesScope : IDisposable { readonly IAttributes m_Target; readonly List<Attribute> m_Previous; /// <summary> /// Initializes a new instance of the <see cref="AttributesScope"/> struct assigns the given attributes to the specified target. /// </summary> /// <param name="target">The target to set the attributes for.</param> /// <param name="source">The source to copy attributes from.</param> public AttributesScope(IProperty target, IProperty source) { m_Target = target as IAttributes; m_Previous = (target as IAttributes)?.Attributes; if (null != m_Target) m_Target.Attributes = (source as IAttributes)?.Attributes; } /// <summary> /// Initializes a new instance of the <see cref="AttributesScope"/> struct assigns the given attributes to the specified target. /// </summary> /// <param name="target">The target to set the attributes for.</param> /// <param name="attributes">The attributes to set.</param> internal AttributesScope(IAttributes target, List<Attribute> attributes) { m_Target = target; m_Previous = target.Attributes; target.Attributes = attributes; } /// <summary> /// Re-assigns the original attributes to the target. /// </summary> public void Dispose() { if (null != m_Target) m_Target.Attributes = m_Previous; } } }
UnityCsReference/Modules/Properties/Runtime/Properties/AttributesScope.cs/0
{ "file_path": "UnityCsReference/Modules/Properties/Runtime/Properties/AttributesScope.cs", "repo_id": "UnityCsReference", "token_count": 735 }
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.Collections.Generic; namespace Unity.Properties { /// <summary> /// A <see cref="IPropertyBag{T}"/> implementation for a generic key/value pair. /// </summary> /// <typeparam name="TKey">The key type.</typeparam> /// <typeparam name="TValue">The value type.</typeparam> public class KeyValuePairPropertyBag<TKey, TValue> : PropertyBag<KeyValuePair<TKey, TValue>>, INamedProperties<KeyValuePair<TKey, TValue>> { static readonly DelegateProperty<KeyValuePair<TKey, TValue>, TKey> s_KeyProperty = new DelegateProperty<KeyValuePair<TKey, TValue>, TKey>( nameof(KeyValuePair<TKey, TValue>.Key), (ref KeyValuePair<TKey, TValue> container) => container.Key, null); static readonly DelegateProperty<KeyValuePair<TKey, TValue>, TValue> s_ValueProperty = new DelegateProperty<KeyValuePair<TKey, TValue>, TValue>( nameof(KeyValuePair<TKey, TValue>.Value), (ref KeyValuePair<TKey, TValue> container) => container.Value, null); /// <inheritdoc cref="IPropertyBag{T}.GetProperties()"/> public override PropertyCollection<KeyValuePair<TKey, TValue>> GetProperties() { return new PropertyCollection<KeyValuePair<TKey, TValue>>(GetPropertiesEnumerable()); } /// <inheritdoc cref="IPropertyBag{T}.GetProperties(ref T)"/> public override PropertyCollection<KeyValuePair<TKey, TValue>> GetProperties(ref KeyValuePair<TKey, TValue> container) { return new PropertyCollection<KeyValuePair<TKey, TValue>>(GetPropertiesEnumerable()); } static IEnumerable<IProperty<KeyValuePair<TKey, TValue>>> GetPropertiesEnumerable() { yield return s_KeyProperty; yield return s_ValueProperty; } /// <summary> /// Gets the property associated with the specified name. /// </summary> /// <param name="container">The container hosting the data.</param> /// <param name="name">The name of the property to get.</param> /// <param name="property">When this method returns, contains the property associated with the specified name, if the name is found; otherwise, null.</param> /// <returns><see langword="true"/> if the <see cref="INamedProperties{TContainer}"/> contains a property with the specified name; otherwise, <see langword="false"/>.</returns> public bool TryGetProperty(ref KeyValuePair<TKey, TValue> container, string name, out IProperty<KeyValuePair<TKey, TValue>> property) { if (name == nameof(KeyValuePair<TKey, TValue>.Key)) { property = s_KeyProperty; return true; } if (name == nameof(KeyValuePair<TKey, TValue>.Value)) { property = s_ValueProperty; return true; } property = default; return false; } } }
UnityCsReference/Modules/Properties/Runtime/PropertyBags/KeyValuePairPropertyBag.cs/0
{ "file_path": "UnityCsReference/Modules/Properties/Runtime/PropertyBags/KeyValuePairPropertyBag.cs", "repo_id": "UnityCsReference", "token_count": 1349 }
426
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; namespace Unity.Properties { /// <summary> /// Helper visitor to visit a single property using a specified <see cref="PropertyPath"/>. /// </summary> public abstract class PathVisitor : IPropertyBagVisitor, IPropertyVisitor { readonly struct PropertyScope : IDisposable { readonly PathVisitor m_Visitor; readonly IProperty m_Property; public PropertyScope(PathVisitor visitor, IProperty property) { m_Visitor = visitor; m_Property = m_Visitor.Property; m_Visitor.Property = property; } public void Dispose() => m_Visitor.Property = m_Property; } int m_PathIndex; /// <summary> /// The path to visit. /// </summary> public PropertyPath Path { get; set; } /// <summary> /// Resets the state of the visitor. /// </summary> public virtual void Reset() { m_PathIndex = 0; Path = default; ReturnCode = VisitReturnCode.Ok; ReadonlyVisit = false; } /// <summary> /// Returns the property for the currently visited container. /// </summary> IProperty Property { get; set; } /// <summary> /// Returns whether or not the visitor will write back values along the path. /// </summary> public bool ReadonlyVisit { get; set; } /// <summary> /// Returns the error code encountered while visiting the provided path. /// </summary> public VisitReturnCode ReturnCode { get; protected set; } void IPropertyBagVisitor.Visit<TContainer>(IPropertyBag<TContainer> properties, ref TContainer container) { var part = Path[m_PathIndex++]; IProperty<TContainer> property; switch (part.Kind) { case PropertyPathPartKind.Name: { if (properties is INamedProperties<TContainer> named && named.TryGetProperty(ref container, part.Name, out property)) { property.Accept(this, ref container); } else { ReturnCode = VisitReturnCode.InvalidPath; } } break; case PropertyPathPartKind.Index: { if (properties is IIndexedProperties<TContainer> indexable && indexable.TryGetProperty(ref container, part.Index, out property)) { using ((property as Internal.IAttributes).CreateAttributesScope(Property as Internal.IAttributes)) { property.Accept(this, ref container); } } else { ReturnCode = VisitReturnCode.InvalidPath; } } break; case PropertyPathPartKind.Key: { if (properties is IKeyedProperties<TContainer, object> keyable && keyable.TryGetProperty(ref container, part.Key, out property)) { using ((property as Internal.IAttributes).CreateAttributesScope(Property as Internal.IAttributes)) { property.Accept(this, ref container); } } else { ReturnCode = VisitReturnCode.InvalidPath; } } break; default: ReturnCode = VisitReturnCode.InvalidPath; break; } } void IPropertyVisitor.Visit<TContainer, TValue>(Property<TContainer, TValue> property, ref TContainer container) { var value = property.GetValue(ref container); if (m_PathIndex >= Path.Length) { VisitPath(property, ref container, ref value); } else if (PropertyBag.TryGetPropertyBagForValue(ref value, out _)) { if (TypeTraits<TValue>.CanBeNull && EqualityComparer<TValue>.Default.Equals(value, default)) { ReturnCode = VisitReturnCode.InvalidPath; return; } using (new PropertyScope(this, property)) { PropertyContainer.Accept(this, ref value); } if (!property.IsReadOnly && !ReadonlyVisit) property.SetValue(ref container, value); } else { ReturnCode = VisitReturnCode.InvalidPath; } } /// <summary> /// Method called when the visitor has successfully visited the provided path. /// </summary> /// <param name="property"></param> /// <param name="container"></param> /// <param name="value"></param> /// <typeparam name="TContainer"></typeparam> /// <typeparam name="TValue"></typeparam> protected virtual void VisitPath<TContainer, TValue>(Property<TContainer, TValue> property, ref TContainer container, ref TValue value) { } } }
UnityCsReference/Modules/Properties/Runtime/PropertyVisitors/PathVisitor.cs/0
{ "file_path": "UnityCsReference/Modules/Properties/Runtime/PropertyVisitors/PathVisitor.cs", "repo_id": "UnityCsReference", "token_count": 2868 }
427
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License //#define DEBUG_INDEXING using System; using System.Collections.Generic; using System.IO; using System.Linq; using Unity.Profiling; using UnityEditor; using UnityEditor.Search.Providers; using UnityEngine; using Object = UnityEngine.Object; namespace UnityEditor.Search { internal enum FilePattern { Extension, Folder, File } /// <summary> /// Specialized <see cref="SearchIndexer"/> used to index Unity Assets. See <see cref="AssetIndexer"/> for a specialized SearchIndexer used to index simple assets and /// see <see cref="SceneIndexer"/> for an indexer used to index scene and prefabs. /// </summary> public abstract class ObjectIndexer : SearchIndexer { static readonly ProfilerMarker k_IndexWordMarker = new($"{nameof(ObjectIndexer)}.{nameof(IndexWord)}"); static readonly ProfilerMarker k_IndexObjectMarker = new($"{nameof(ObjectIndexer)}.{nameof(IndexObject)}"); static readonly ProfilerMarker k_IndexPropertiesMarker = new($"{nameof(ObjectIndexer)}.{nameof(IndexProperties)}"); static readonly ProfilerMarker k_IndexPropertyMarker = new($"{nameof(ObjectIndexer)}.{nameof(IndexProperty)}"); static readonly ProfilerMarker k_IndexSerializedPropertyMarker = new($"{nameof(ObjectIndexer)}.IndexSerializedProperty"); static readonly ProfilerMarker k_IndexPropertyComponentsMarker = new($"{nameof(ObjectIndexer)}.IndexPropertyComponents"); static readonly ProfilerMarker k_IndexPropertyStringComponentsMarker = new($"{nameof(ObjectIndexer)}.{nameof(IndexPropertyStringComponents)}"); static readonly ProfilerMarker k_LogPropertyMarker = new($"{nameof(ObjectIndexer)}.{nameof(LogProperty)}"); static readonly ProfilerMarker k_IndexCustomPropertiesMarker = new($"{nameof(ObjectIndexer)}.{nameof(IndexCustomProperties)}"); static readonly ProfilerMarker k_AddReferenceMarker = new($"{nameof(ObjectIndexer)}.{nameof(AddReference)}"); static readonly ProfilerMarker k_AddObjectReferenceMarker = new($"{nameof(ObjectIndexer)}.AddObjectReference"); // Define a list of patterns that will automatically skip path entries if they start with it. readonly static string[] BuiltInTransientFilePatterns = new[] { "~", "##ignore", "InitTestScene" }; internal SearchDatabase.Settings settings { get; private set; } private HashSet<string> m_IgnoredProperties; internal HashSet<string> ignoredProperties { get { if (m_IgnoredProperties == null) { m_IgnoredProperties = new HashSet<string>(SearchSettings.ignoredProperties.Split(new char[] { ';', '\n' }, StringSplitOptions.RemoveEmptyEntries).Select(t => t.ToLowerInvariant())); } return m_IgnoredProperties; } } internal ObjectIndexer(string name, SearchDatabase.Settings settings) : base(name) { this.settings = settings; } /// <summary> /// Run a search query in the index. /// </summary> /// <param name="searchQuery">Search query to look out for. If if matches any of the indexed variations a result will be returned.</param> /// <param name="context">The search context on which the query is applied.</param> /// <param name="provider">The provider that initiated the search.</param> /// <param name="maxScore">Maximum score of any matched Search Result. See <see cref="SearchResult.score"/>.</param> /// <param name="patternMatchLimit">Maximum number of matched Search Result that can be returned. See <see cref="SearchResult"/>.</param> /// <returns>Returns a collection of Search Result matching the query.</returns> public override IEnumerable<SearchResult> Search(string searchQuery, SearchContext context, SearchProvider provider, int maxScore = int.MaxValue, int patternMatchLimit = 2999) { if (settings.options.disabled) return Enumerable.Empty<SearchResult>(); return base.Search(searchQuery, context, provider, maxScore, patternMatchLimit).Take(patternMatchLimit); } internal override IEnumerable<SearchResult> SearchWord(string word, SearchIndexOperator op, SearchResultCollection subset) { //using (new DebugTimer($"Search word {word}, {op}, {subset?.Count}")) { foreach (var r in base.SearchWord(word, op, subset)) yield return r; if (SearchSettings.findProviderIndexHelper) { var baseScore = settings.baseScore; var options = FindOptions.Words | FindOptions.Glob | FindOptions.Regex | FindOptions.FileName; if (m_DoFuzzyMatch) options |= FindOptions.Fuzzy; var documents = subset != null ? subset.Select(r => GetDocument(r.index)) : GetDocuments(ignoreNulls: true); foreach (var r in FindProvider.SearchWord(false, word, options, documents)) { if (m_IndexByDocuments.TryGetValue(r.id, out var documentIndex)) yield return new SearchResult(r.id, documentIndex, baseScore + r.score + 5); } } } } static bool ShouldIgnorePattern(in string pattern, in string path) { var filename = Path.GetFileName(path); return filename.StartsWith(pattern, StringComparison.Ordinal) || filename.EndsWith(pattern, StringComparison.Ordinal); } /// <summary> /// Called when the index is built to see if a specified document needs to be indexed. See <see cref="SearchIndexer.skipEntryHandler"/> /// </summary> /// <param name="path">Path of a document</param> /// <param name="checkRoots"></param> /// <returns>Returns true if the document doesn't need to be indexed.</returns> public override bool SkipEntry(string path, bool checkRoots = false) { if (string.IsNullOrEmpty(path)) return true; // Skip files with ~ in their file path and built-in transient files if (BuiltInTransientFilePatterns.Any(pattern => ShouldIgnorePattern(pattern, path))) return true; if (checkRoots) { if (!GetRoots().Any(r => path.StartsWith(r, StringComparison.OrdinalIgnoreCase))) return true; } var ext = Path.GetExtension(path); // Exclude some file extensions by default if (ext.Equals(".meta", StringComparison.Ordinal) || ext.Equals(".index", StringComparison.Ordinal)) return true; if (settings.includes?.Length > 0 || settings.excludes?.Length > 0) { var dir = Path.GetDirectoryName(path).Replace("\\", "/"); if (settings.includes?.Length > 0 && !settings.includes.Any(pattern => PatternChecks(pattern, ext, dir, path))) return true; if (settings.excludes?.Length > 0 && settings.excludes.Any(pattern => PatternChecks(pattern, ext, dir, path))) return true; } return false; } /// <summary> /// Get all this indexer root paths. /// </summary> /// <returns>Returns a list of root paths.</returns> internal abstract IEnumerable<string> GetRoots(); /// <summary> /// Get all documents that would be indexed. /// </summary> /// <returns>Returns a list of file paths.</returns> internal abstract List<string> GetDependencies(); /// <summary> /// Compute the hash of a specific document id. Generally a file path. /// </summary> /// <param name="id">Document id.</param> /// <returns>Returns the hash of this document id.</returns> internal abstract Hash128 GetDocumentHash(string id); /// <summary> /// Function to override in a concrete SearchIndexer to index the content of a document. /// </summary> /// <param name="id">Path of the document to index.</param> /// <param name="checkIfDocumentExists">Check if the document actually exists.</param> public abstract override void IndexDocument(string id, bool checkIfDocumentExists); /// <summary> /// Split a word into multiple components. /// </summary> /// <param name="documentIndex">Document where the indexed word was found.</param> /// <param name="word">Word to add to the index.</param> public void IndexWordComponents(int documentIndex, in string word) { int scoreModifier = 0; foreach (var c in GetEntryComponents(word, documentIndex)) IndexWord(documentIndex, c, scoreModifier: scoreModifier++); } /// <summary> /// Split a value into multiple components. /// </summary> /// <param name="documentIndex">Document where the indexed word was found.</param> /// <param name="name">Key used to retrieve the value. See <see cref="SearchIndexer.AddProperty"/></param> /// <param name="value">Value to add to the index.</param> public void IndexPropertyComponents(int documentIndex, string name, string value) { using var _ = k_IndexPropertyComponentsMarker.Auto(); int scoreModifier = 0; double number = 0; foreach (var c in GetEntryComponents(value, documentIndex)) { var score = settings.baseScore + scoreModifier++; if (Utils.TryParse(c, out number)) { AddNumber(name, number, score, documentIndex); } else { AddProperty(name, c, score, documentIndex, saveKeyword: false, exact: false); } } AddProperty(name, value.ToLowerInvariant(), settings.baseScore - 5, documentIndex, saveKeyword: false, exact: true); } /// <summary> /// Splits a string into multiple words that will be indexed. /// It works with paths and UpperCamelCase strings. /// </summary> /// <param name="entry">The string to be split.</param> /// <param name="documentIndex">The document index that will index that entry.</param> /// <returns>The entry components.</returns> public virtual IEnumerable<string> GetEntryComponents(in string entry, int documentIndex) { return SearchUtils.SplitFileEntryComponents(entry, SearchUtils.entrySeparators); } /// <summary> /// Add a new word coming from a specific document to the index. The word will be added with multiple variations allowing partial search. See <see cref="SearchIndexer.AddWord"/>. /// </summary> /// <param name="word">Word to add to the index.</param> /// <param name="documentIndex">Document where the indexed word was found.</param> /// <param name="maxVariations">Maximum number of variations to compute. Cannot be higher than the length of the word.</param> /// <param name="exact">If true, we will store also an exact match entry for this word.</param> /// <param name="scoreModifier">Modified to apply to the base score for a specific word.</param> public void IndexWord(int documentIndex, in string word, int maxVariations, bool exact, int scoreModifier = 0) { IndexWord(documentIndex, word, minWordIndexationLength, maxVariations, exact, scoreModifier); } internal void IndexWord(int documentIndex, in string word, int minVariations, int maxVariations, bool exact, int scoreModifier = 0) { using var _ = k_IndexWordMarker.Auto(); var lword = word.ToLowerInvariant(); var modifiedScore = settings.baseScore + scoreModifier; AddWord(lword, minVariations, maxVariations, modifiedScore, documentIndex); if (exact) AddExactWord(lword, modifiedScore, documentIndex); } /// <summary> /// Add a new word coming from a specific document to the index. The word will be added with multiple variations allowing partial search. See <see cref="SearchIndexer.AddWord"/>. /// </summary> /// <param name="word">Word to add to the index.</param> /// <param name="documentIndex">Document where the indexed word was found.</param> /// <param name="exact">If true, we will store also an exact match entry for this word.</param> /// <param name="scoreModifier">Modified to apply to the base score for a specific word.</param> public void IndexWord(int documentIndex, in string word, bool exact = false, int scoreModifier = 0) { IndexWord(documentIndex, word, word.Length, exact, scoreModifier: scoreModifier); } /// <summary> /// Add a property value to the index. A property is specified with a key and a string value. The value will be stored with multiple variations. See <see cref="SearchIndexer.AddProperty"/>. /// </summary> /// <param name="name">Key used to retrieve the value. See <see cref="SearchIndexer.AddProperty"/></param> /// <param name="value">Value to add to the index.</param> /// <param name="documentIndex">Document where the indexed word was found.</param> /// <param name="saveKeyword">Define if we store this key in the keyword registry of the index. See <see cref="SearchIndexer.GetKeywords"/>.</param> /// <param name="exact">If exact is true, only the exact match of the value will be stored in the index (not the variations).</param> public void IndexProperty(int documentIndex, string name, string value, bool saveKeyword, bool exact = false) { using var _ = k_IndexPropertyMarker.Auto(); if (string.IsNullOrEmpty(value)) return; var valueLower = value.ToLowerInvariant(); if (exact) { AddProperty(name, valueLower, valueLower.Length, valueLower.Length, settings.baseScore, documentIndex, saveKeyword: saveKeyword, exact: true); } else AddProperty(name, valueLower, settings.baseScore, documentIndex, saveKeyword: saveKeyword); } public void IndexProperty<TProperty, TPropertyOwner>(int documentIndex, string name, string value, bool saveKeyword, bool exact) { IndexProperty(documentIndex, name, value, saveKeyword, exact); MapProperty(name, name, name, typeof(TProperty).AssemblyQualifiedName, typeof(TPropertyOwner).AssemblyQualifiedName, removeNestedKeys: true); } internal void IndexProperty<TProperty, TPropertyOwner>(int documentIndex, string name, string value, bool saveKeyword, bool exact, string keywordLabel, string keywordHelp) { IndexProperty(documentIndex, name, value, saveKeyword, exact); MapProperty(name, keywordLabel, keywordHelp, typeof(TProperty).AssemblyQualifiedName, typeof(TPropertyOwner).AssemblyQualifiedName, removeNestedKeys: true); } /// <summary> /// Add a key-number value pair to the index. The key won't be added with variations. See <see cref="SearchIndexer.AddNumber"/>. /// </summary> /// <param name="name">Key used to retrieve the value.</param> /// <param name="number">Number value to store in the index.</param> /// <param name="documentIndex">Document where the indexed value was found.</param> public void IndexNumber(int documentIndex, string name, double number) { AddNumber(name, number, settings.baseScore, documentIndex); } internal static FilePattern GetFilePattern(string pattern) { if (!string.IsNullOrEmpty(pattern)) { if (pattern[0] == '.') return FilePattern.Extension; if (pattern[pattern.Length - 1] == '/') return FilePattern.Folder; } return FilePattern.File; } private bool PatternChecks(string pattern, string ext, string dir, string filePath) { var filePattern = GetFilePattern(pattern); switch (filePattern) { case FilePattern.Extension: return ext.Equals(pattern, StringComparison.OrdinalIgnoreCase); case FilePattern.Folder: var icDir = pattern.Substring(0, pattern.Length - 1); return dir.IndexOf(icDir, StringComparison.OrdinalIgnoreCase) != -1; case FilePattern.File: return filePath.IndexOf(pattern, StringComparison.OrdinalIgnoreCase) != -1; } return false; } /// <summary> /// Index all the properties of an object. /// </summary> /// <param name="obj">Object to index.</param> /// <param name="documentIndex">Document where the indexed object was found.</param> /// <param name="dependencies">Index dependencies.</param> protected void IndexObject(int documentIndex, Object obj, bool dependencies = false) { IndexObject(documentIndex, obj, dependencies, recursive: false); } internal void IndexObject(int documentIndex, Object obj, bool dependencies, bool recursive) { using var _ = k_IndexObjectMarker.Auto(); using (var so = new SerializedObject(obj)) { var p = so.GetIterator(); const int maxDepth = 1; IndexProperties(documentIndex, p, recursive, maxDepth); } } private bool ShouldIndexChildren(SerializedProperty p, bool recursive) { // Degenerative built-in types to skip. if (p.propertyType == SerializedPropertyType.Generic) { switch (p.type) { case "SerializedProperties": case "VFXPropertySheetSerializedBase": case "ComputeShaderCompilationContext": return false; } } if (p.depth > 2 && !recursive) return false; if ((p.isArray || p.isFixedBuffer) && !recursive) return false; if (p.propertyType == SerializedPropertyType.Vector2 || p.propertyType == SerializedPropertyType.Vector3 || p.propertyType == SerializedPropertyType.Vector4) return false; return p.hasVisibleChildren; } internal static string GetFieldName(string propertyName) { return propertyName.Replace("m_", "").Replace(" ", "").ToLowerInvariant(); } static Func<SerializedProperty, bool> s_IndexAllPropertiesFunc = p => true; internal void IndexProperties(int documentIndex, in SerializedProperty p, bool recursive, int maxDepth) { IndexProperties(documentIndex, p, recursive, maxDepth, s_IndexAllPropertiesFunc); } internal static bool IsIndexableProperty(in SerializedPropertyType type) { switch (type) { // Unsupported property types: case SerializedPropertyType.Generic: case SerializedPropertyType.Bounds: case SerializedPropertyType.BoundsInt: case SerializedPropertyType.Rect: case SerializedPropertyType.RectInt: case SerializedPropertyType.Vector2Int: case SerializedPropertyType.Vector3Int: case SerializedPropertyType.LayerMask: case SerializedPropertyType.AnimationCurve: case SerializedPropertyType.Gradient: case SerializedPropertyType.ExposedReference: case SerializedPropertyType.ManagedReference: case SerializedPropertyType.FixedBufferSize: return false; default: return true; } } internal void IndexProperties(int documentIndex, in SerializedProperty p, bool recursive, int maxDepth, Func<SerializedProperty, bool> shouldContinueIterating) { using var _ = k_IndexPropertiesMarker.Auto(); var next = p.NextVisible(true); while (next) { var fieldName = GetFieldName(p.displayName); if (IsIndexableProperty(p.propertyType) && p.propertyPath[p.propertyPath.Length - 1] != ']') IndexProperty(documentIndex, fieldName, p, maxDepth); next = shouldContinueIterating(p) && p.NextVisible(ShouldIndexChildren(p, recursive)); } } internal void IndexProperty(in int documentIndex, in string fieldName, in SerializedProperty p, int maxDepth) { using var _ = k_IndexSerializedPropertyMarker.Auto(); if (ignoredProperties.Contains(fieldName)) return; if (ignoredProperties.Contains(p.type)) return; if (p.depth <= 1 && p.isArray && p.propertyType != SerializedPropertyType.String) { IndexNumber(documentIndex, fieldName, p.arraySize); LogProperty(fieldName, p, p.arraySize); } if (p.depth > maxDepth) return; switch (p.propertyType) { case SerializedPropertyType.ArraySize: case SerializedPropertyType.Character: case SerializedPropertyType.Integer: IndexNumber(documentIndex, fieldName, (double)p.intValue); var managedType = p.GetManagedType(); if (managedType?.IsEnum == true) { var values = Enum.GetValues(managedType); for (int i = 0; i < values.Length; i++) { var v = (int)values.GetValue(i); if (v == p.intValue) { if (IndexPropertyStringComponents(documentIndex, fieldName, Enum.GetNames(managedType)[i])) LogProperty(fieldName, p, Enum.GetValues(managedType).GetValue(i)); break; } } } else if (managedType == typeof(bool)) { var boolStringValue = p.intValue == 0 ? "false" : "true"; IndexProperty(documentIndex, fieldName, boolStringValue, saveKeyword: false, exact: true); LogProperty(fieldName, p, boolStringValue); } else LogProperty(fieldName, p, p.intValue); break; case SerializedPropertyType.Boolean: IndexProperty(documentIndex, fieldName, p.boolValue.ToString().ToLowerInvariant(), saveKeyword: false, exact: true); LogProperty(fieldName, p, p.boolValue); break; case SerializedPropertyType.Float: IndexNumber(documentIndex, fieldName, (double)p.floatValue); LogProperty(fieldName, p, p.floatValue); break; case SerializedPropertyType.String: if (IndexPropertyStringComponents(documentIndex, fieldName, p.stringValue)) LogProperty(fieldName, p, p.stringValue); break; case SerializedPropertyType.Enum: if (p.enumValueIndex < 0 || p.type != "Enum") return; var enumValue = p.enumNames[p.enumValueIndex].Replace(" ", ""); if (IndexPropertyStringComponents(documentIndex, fieldName, enumValue)) LogProperty(fieldName, p, enumValue); break; case SerializedPropertyType.Color: IndexerExtensions.IndexColor(fieldName, p.colorValue, this, documentIndex); LogProperty(fieldName, p, p.colorValue); break; case SerializedPropertyType.Vector2: IndexerExtensions.IndexVector(fieldName, p.vector2Value, this, documentIndex); LogProperty(fieldName, p, p.vector2Value); break; case SerializedPropertyType.Vector3: IndexerExtensions.IndexVector(fieldName, p.vector3Value, this, documentIndex); LogProperty(fieldName, p, p.vector3Value); break; case SerializedPropertyType.Vector4: IndexerExtensions.IndexVector(fieldName, p.vector4Value, this, documentIndex); LogProperty(fieldName, p, p.vector4Value); break; case SerializedPropertyType.Quaternion: IndexerExtensions.IndexVector(fieldName, p.quaternionValue.eulerAngles, this, documentIndex); LogProperty(fieldName, p, p.quaternionValue.eulerAngles); break; case SerializedPropertyType.ObjectReference: AddReference(documentIndex, fieldName, p.objectReferenceValue); LogProperty(fieldName, p, p.objectReferenceValue); break; case SerializedPropertyType.Hash128: IndexProperty(documentIndex, fieldName, p.hash128Value.ToString().ToLowerInvariant(), saveKeyword: true, exact: true); LogProperty(fieldName, p, p.hash128Value); break; } } bool IndexPropertyStringComponents(in int documentIndex, in string fieldName, in string sv) { using var _ = k_IndexPropertyStringComponentsMarker.Auto(); if (string.IsNullOrEmpty(sv) || sv.Length > 64) return false; if (sv.Length >= minWordIndexationLength && sv.Length < 32) IndexPropertyComponents(documentIndex, fieldName, sv); else IndexProperty(documentIndex, fieldName, sv, saveKeyword: false, exact: true); return true; } void LogProperty(in string fieldName, in SerializedProperty p, object value = null) { using var _ = k_LogPropertyMarker.Auto(); var propertyType = SearchUtils.GetPropertyManagedTypeString(p); if (propertyType != null) MapProperty(fieldName, p.displayName, p.tooltip, propertyType, p.serializedObject?.targetObject?.GetType().AssemblyQualifiedName, removeNestedKeys: true); } internal void AddReference(int documentIndex, string assetPath, bool saveKeyword = false) { using var _ = k_AddReferenceMarker.Auto(); if (string.IsNullOrEmpty(assetPath)) return; IndexProperty(documentIndex, "ref", assetPath, saveKeyword, exact: true); var assetInstanceID = Utils.GetMainAssetInstanceID(assetPath); var gid = GlobalObjectId.GetGlobalObjectIdSlow(assetInstanceID); if (gid.identifierType != 0) IndexProperty(documentIndex, "ref", gid.ToString(), saveKeyword, exact: true); if (settings.options.properties) IndexPropertyStringComponents(documentIndex, "ref", Path.GetFileNameWithoutExtension(assetPath)); } internal void AddReference(int documentIndex, string propertyName, Object objRef, in string label = null, in Type ownerPropertyType = null) { using var _ = k_AddObjectReferenceMarker.Auto(); if (!objRef) { if (settings.options.properties) IndexProperty(documentIndex, propertyName, "none", saveKeyword: false, exact: true); return; } var assetPath = SearchUtils.GetObjectPath(objRef); if (string.IsNullOrEmpty(assetPath)) return; propertyName = propertyName.ToLowerInvariant(); IndexProperty(documentIndex, propertyName, assetPath, saveKeyword: false, exact: true); var gid = GlobalObjectId.GetGlobalObjectIdSlow(objRef); if (gid.identifierType != 0) IndexProperty(documentIndex, "ref", gid.ToString(), saveKeyword: false, exact: true); if (settings.options.dependencies) IndexProperty(documentIndex, "ref", assetPath, saveKeyword: false, exact: true); if (settings.options.properties) { IndexPropertyStringComponents(documentIndex, propertyName, Path.GetFileNameWithoutExtension(Utils.RemoveInvalidCharsFromPath(objRef.name ?? assetPath, '_'))); if (label != null && ownerPropertyType != null) MapProperty(propertyName, label, null, objRef.GetType().AssemblyQualifiedName, ownerPropertyType.AssemblyQualifiedName, false); } } /// <summary> /// Call all the registered custom indexer for a specific object. See <see cref="CustomObjectIndexerAttribute"/>. /// </summary> /// <param name="documentId">Document index.</param> /// <param name="documentIndex">Document where the indexed object was found.</param> /// <param name="obj">Object to index.</param> internal void IndexCustomProperties(string documentId, int documentIndex, Object obj) { using var _ = k_IndexCustomPropertiesMarker.Auto(); using (var so = new SerializedObject(obj)) { CallCustomIndexers(documentId, documentIndex, obj, so); } } /// <summary> /// Call all the registered custom indexer for an object of a specific type. See <see cref="CustomObjectIndexerAttribute"/>. /// </summary> /// <param name="documentId">Document id.</param> /// <param name="obj">Object to index.</param> /// <param name="documentIndex">Document where the indexed object was found.</param> /// <param name="so">SerializedObject representation of obj.</param> /// <param name="multiLevel">If true, calls all the indexer that would fit the type of the object (all assignable type). If false only check for an indexer registered for the exact type of the Object.</param> private void CallCustomIndexers(string documentId, int documentIndex, Object obj, SerializedObject so, bool multiLevel = true) { var objectType = obj.GetType(); List<CustomIndexerHandler> customIndexers; if (!multiLevel) { if (!CustomIndexers.TryGetValue(objectType, out customIndexers)) return; } else { customIndexers = new List<CustomIndexerHandler>(); foreach (var indexerType in CustomIndexers.types) { if (indexerType.IsAssignableFrom(objectType)) customIndexers.AddRange(CustomIndexers.GetHandlers(indexerType)); } } var indexerTarget = new CustomObjectIndexerTarget { id = documentId, documentIndex = documentIndex, target = obj, serializedObject = so, targetType = objectType }; foreach (var customIndexer in customIndexers) { try { customIndexer(indexerTarget, this); } catch(System.Exception e) { Debug.LogError($"Error while using custom asset indexer: {e}"); } } } /// <summary> /// Checks if we have a custom indexer for the specified type. /// </summary> /// <param name="type">Type to lookup</param> /// <param name="multiLevel">Check for subtypes too.</param> /// <returns>True if a custom indexer exists, otherwise false is returned.</returns> internal bool HasCustomIndexers(Type type, bool multiLevel = true) { return CustomIndexers.HasCustomIndexers(type, multiLevel); } private protected override void OnFinish() { IndexerExtensions.ClearIndexerCaches(this); } } }
UnityCsReference/Modules/QuickSearch/Editor/Indexing/ObjectIndexer.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/Indexing/ObjectIndexer.cs", "repo_id": "UnityCsReference", "token_count": 14497 }
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.Linq; using System.Collections.Generic; using System.IO; namespace UnityEditor.Search.Providers { static class AdbProvider { public const string type = "adb"; static ObjectQueryEngine<UnityEngine.Object> m_ResourcesQueryEngine; public static IEnumerable<int> EnumerateInstanceIDs(in string searchQuery, in Type filterType, in SearchFlags flags) { var searchFilter = new SearchFilter { searchArea = GetSearchArea(flags), showAllHits = flags.HasAny(SearchFlags.WantsMore), originalText = searchQuery }; if (!string.IsNullOrEmpty(searchQuery)) SearchUtility.ParseSearchString(searchQuery, searchFilter); if (filterType != null && searchFilter.classNames.Length == 0) searchFilter.classNames = new[] { filterType.Name }; searchFilter.filterByTypeIntersection = true; return EnumerateInstanceIDs(searchFilter); } static SearchFilter.SearchArea GetSearchArea(in SearchFlags searchFlags) { if (searchFlags.HasAny(SearchFlags.Packages)) return SearchFilter.SearchArea.AllAssets; return SearchFilter.SearchArea.InAssetsOnly; } static IEnumerable<int> EnumerateInstanceIDs(SearchFilter searchFilter) { var rIt = AssetDatabase.EnumerateAllAssets(searchFilter); while (rIt.MoveNext()) { if (rIt.Current.pptrValue) yield return rIt.Current.instanceID; } } public static IEnumerable<int> EnumerateInstanceIDs(SearchContext context) { if (context.filterType == null && context.empty) return Enumerable.Empty<int>(); if (context.userData is SearchFilter legacySearchFilter) { legacySearchFilter.filterByTypeIntersection = true; return EnumerateInstanceIDs(legacySearchFilter); } return EnumerateInstanceIDs(context.searchQuery, context.filterType, context.options); } public static IEnumerable<string> EnumeratePaths(SearchContext context) { foreach (var id in EnumerateInstanceIDs(context)) yield return AssetDatabase.GetAssetPath(id); } static Dictionary<string, UnityEngine.Object[]> s_BundleResourceObjects = new Dictionary<string, UnityEngine.Object[]>(); static IEnumerable<UnityEngine.Object> GetAllResourcesAtPath(in string path) { if (s_BundleResourceObjects.TryGetValue(path, out var objects)) return objects; objects = AssetDatabase.LoadAllAssetsAtPath(path).ToArray(); s_BundleResourceObjects[path] = objects; return objects; } static IEnumerable<SearchItem> FetchItems(SearchContext context, SearchProvider provider) { if (string.IsNullOrEmpty(context.searchQuery) && context.filterType == null) yield break; if (m_ResourcesQueryEngine == null) { m_ResourcesQueryEngine = new ObjectQueryEngine() { reportError = false }; } // Search asset database foreach (var id in EnumerateInstanceIDs(context)) { var path = AssetDatabase.GetAssetPath(id); var gid = GlobalObjectId.GetGlobalObjectIdSlow(id).ToString(); string label = null; var flags = SearchDocumentFlags.Asset; if (AssetDatabase.IsSubAsset(id)) { var obj = UnityEngine.Object.FindObjectFromInstanceID(id); var filename = Path.GetFileNameWithoutExtension(path); label = obj?.name ?? filename; path = Utils.RemoveInvalidCharsFromPath($"{filename}/{label}", ' '); flags |= SearchDocumentFlags.Nested; } var item = AssetProvider.CreateItem("ADB", context, provider, context.filterType, gid, path, 998, flags); if (label != null) { item.label = label; } yield return item; } // Search builtin resources var resources = GetAllResourcesAtPath("library/unity default resources") .Concat(GetAllResourcesAtPath("resources/unity_builtin_extra")); if (context.wantsMore) resources = resources.Concat(GetAllResourcesAtPath("library/unity editor resources")); if (context.filterType != null) resources = resources.Where(r => context.filterType.IsAssignableFrom(r.GetType())); if (!string.IsNullOrEmpty(context.searchQuery)) resources = m_ResourcesQueryEngine.Search(context, provider, resources); else if (context.filterType == null) yield break; foreach (var obj in resources) { if (!obj) continue; var gid = GlobalObjectId.GetGlobalObjectIdSlow(obj); if (gid.identifierType == 0) continue; yield return AssetProvider.CreateItem("Resources", context, provider, gid.ToString(), null, 1998, SearchDocumentFlags.Resources); } } static IEnumerable<SearchProposition> FetchPropositions(SearchContext context, SearchPropositionOptions options) { if (!options.flags.HasAny(SearchPropositionFlags.QueryBuilder)) yield break; foreach (var f in QueryListBlockAttribute.GetPropositions(typeof(QueryTypeBlock))) yield return f; foreach (var f in QueryListBlockAttribute.GetPropositions(typeof(QueryLabelBlock))) yield return f; foreach (var f in QueryListBlockAttribute.GetPropositions(typeof(QueryAreaFilterBlock))) yield return f; foreach (var f in QueryListBlockAttribute.GetPropositions(typeof(QueryBundleFilterBlock))) yield return f; yield return new SearchProposition(category: null, "Reference", "ref:<$object:none,UnityEngine.Object$>", "Find all assets referencing a specific asset."); yield return new SearchProposition(category: null, "Glob", "glob:\"Assets/**/*.png\"", "Search according to a glob query."); } [SearchItemProvider] internal static SearchProvider CreateProvider() { return new SearchProvider(type, "Asset Database") { type = "asset", active = false, priority = 2500, fetchItems = (context, items, provider) => FetchItems(context, SearchService.GetProvider("asset") ?? provider), fetchPropositions = (context, options) => FetchPropositions(context, options) }; } [MenuItem("Window/Search/Asset Database", priority = 1271)] static void OpenProvider() => SearchService.ShowContextual(type); [ShortcutManagement.Shortcut("Help/Search/Asset Database")] static void OpenShortcut() => SearchUtils.OpenWithContextualProvider(type); } [QueryListBlock(null, "area", "a", ":")] class QueryAreaFilterBlock : QueryListBlock { public QueryAreaFilterBlock(IQuerySource source, string id, string value, QueryListBlockAttribute attr) : base(source, id, value, attr) { icon = Utils.LoadIcon("Filter Icon"); } public override IEnumerable<SearchProposition> GetPropositions(SearchPropositionFlags flags) { yield return CreateProposition(flags, "All", "all", "Search all", score: -99); yield return CreateProposition(flags, "Assets", "assets", "Search in Assets folder only", score: -98); yield return CreateProposition(flags, "Packages", "packages", "Search in packages only", score: -97); } } [QueryListBlock("Bundle", "bundle", "b", ":")] class QueryBundleFilterBlock : QueryListBlock { public QueryBundleFilterBlock(IQuerySource source, string id, string value, QueryListBlockAttribute attr) : base(source, id, value, attr) { icon = Utils.LoadIcon("Filter Icon"); } public override IEnumerable<SearchProposition> GetPropositions(SearchPropositionFlags flags) { var bundleNames = AssetDatabase.GetAllAssetBundleNames(); foreach (var bundleName in bundleNames) { yield return CreateProposition(flags, bundleName, bundleName, $"Search inside bundle \"{bundleName}\""); } } } }
UnityCsReference/Modules/QuickSearch/Editor/Providers/AdbProvider.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/Providers/AdbProvider.cs", "repo_id": "UnityCsReference", "token_count": 3974 }
429
// Unity C# 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 System.Reflection; using System.Text.RegularExpressions; using UnityEngine; namespace UnityEditor.Search.Providers { static class StaticMethodProvider { private const string type = "static_methods"; private const string displayName = "Static API"; private static readonly string[] _ignoredAssemblies = { "^UnityScript$", "^System$", "^mscorlib$", "^netstandard$", "^System\\..*", "^nunit\\..*", "^Microsoft\\..*", "^Mono\\..*", "^SyntaxTree\\..*" }; private static MethodInfo[] methods; [SearchItemProvider] internal static SearchProvider CreateProvider() { return new SearchProvider(type, displayName) { priority = 85, filterId = "api:", isExplicitProvider = true, fetchItems = (context, items, provider) => FetchItems(context, provider), fetchThumbnail = (item, context) => Icons.staticAPI }; } private static IEnumerable<SearchItem> FetchItems(SearchContext context, SearchProvider provider) { // Cache all available static APIs if (methods == null) methods = FetchStaticAPIMethodInfo(); var casePattern = context.searchQuery.Replace(" ", ""); var matches = new List<int>(); foreach (var m in methods) { if (!m.IsPublic && !context.options.HasFlag(SearchFlags.WantsMore)) continue; long score = 0; var fullName = $"{m.DeclaringType.FullName}.{m.Name}"; var fullNameLower = fullName.ToLowerInvariant(); if (FuzzySearch.FuzzyMatch(casePattern, fullNameLower, ref score, matches) && score > 300) { var visibilityString = m.IsPublic ? string.Empty : "(Non Public)"; yield return provider.CreateItem(context, m.Name, m.IsPublic ? ~(int)score - 999 : ~(int)score, m.Name, $"{fullName} {visibilityString}", null, m); } else yield return null; } } private static MethodInfo[] FetchStaticAPIMethodInfo() { // Note: since 23.2 an internal api causes a hard crash when fetching for it. // bool isDevBuild = Unsupported.IsDeveloperBuild(); return AppDomain.CurrentDomain.GetAllStaticMethods(false); } private static MethodInfo[] GetAllStaticMethods(this AppDomain aAppDomain, bool showInternalAPIs) { var result = new List<MethodInfo>(); var assemblies = aAppDomain.GetAssemblies(); var bindingFlags = BindingFlags.Static | (showInternalAPIs ? BindingFlags.Public | BindingFlags.NonPublic : BindingFlags.Public) | BindingFlags.DeclaredOnly; foreach (var assembly in assemblies) { if (IsIgnoredAssembly(assembly.GetName())) continue; var types = assembly.GetLoadableTypes(); foreach (var type in types) { var methods = type.GetMethods(bindingFlags); foreach (var m in methods) { if (m.IsGenericMethod) continue; if (m.GetCustomAttribute<ObsoleteAttribute>() != null) continue; if (m.Name.Contains("Begin") || m.Name.Contains("End")) continue; if (m.GetParameters().Length == 0) result.Add(m); } } } return result.ToArray(); } private static bool IsIgnoredAssembly(AssemblyName assemblyName) { var name = assemblyName.Name; return _ignoredAssemblies.Any(candidate => Regex.IsMatch(name, candidate)); } private static void LogResult(object result) { if (result == null) return; Debug.LogFormat(LogType.Log, LogOption.NoStacktrace, result as UnityEngine.Object, result.ToString()); } [SearchActionsProvider] internal static IEnumerable<SearchAction> ActionHandlers() { return new[] { new SearchAction(type, "exec", null, "Execute method", (items) => { foreach (var item in items) { var m = item.data as MethodInfo; if (m == null) return; var result = m.Invoke(null, null); if (result == null) return; if (result is string || !(result is IEnumerable list)) { LogResult(result); EditorGUIUtility.systemCopyBuffer = result.ToString(); } else { foreach (var e in list) LogResult(e); } } }) }; } } }
UnityCsReference/Modules/QuickSearch/Editor/Providers/StaticMethodProvider.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/Providers/StaticMethodProvider.cs", "repo_id": "UnityCsReference", "token_count": 2902 }
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.Collections.Generic; using System.Linq; namespace UnityEditor.Search { struct QueryMarkerArgument { public StringView rawText; public object value; public SearchExpression expression; public bool needsEvaluation => expression != null && value == null; public IEnumerable<object> Evaluate(SearchContext context, bool reevaluateLiterals = false) { if (expression == null) { yield return rawText.ToString(); } else if (expression.types.HasAny(SearchExpressionType.Literal) && !reevaluateLiterals) { yield return value; } else { var oldOptions = context.options; context.options |= SearchFlags.Synchronous; foreach (var r in expression.Execute(context).Where(item => item != null).Select(item => item.value)) yield return r; context.options = oldOptions; } } public IEnumerable<object> Evaluate(bool reevaluateLiterals = false) { using (var context = SearchService.CreateContext("")) { return Evaluate(context, reevaluateLiterals).ToList(); } } } // <$CONTROL_TYPE:[VALUE,]EXPRESSION_ARGS$>. struct QueryMarker { const string k_StartToken = "<$"; const string k_EndToken = "$>"; public string type; // Control Editor Type public StringView text; public object value => args.Length > 0 ? args[0].value : null; public QueryMarkerArgument[] args; public static QueryMarker none = new QueryMarker(); public bool valid => text.valid; public static bool TryParse(string text, out QueryMarker marker) { return TryParse(text.GetStringView(), out marker); } public static bool TryParse(StringView text, out QueryMarker marker) { marker = none; if (!IsQueryMarker(text)) return false; var innerText = text.Substring(k_StartToken.Length, text.length - k_StartToken.Length - k_EndToken.Length); var indexOfColon = innerText.IndexOf(':'); if (indexOfColon < 0) return false; var controlType = innerText.Substring(0, indexOfColon).Trim().ToString(); var args = new List<StringView>(); var level = 0; var currentArgStart = indexOfColon + 1; for (var i = currentArgStart; i < innerText.length; ++i) { if (ParserUtils.IsOpener(innerText[i])) ++level; if (ParserUtils.IsCloser(innerText[i])) --level; if (innerText[i] != ',' || level != 0) continue; if (i+1 == innerText.length) return false; args.Add(innerText.Substring(currentArgStart, i - currentArgStart).Trim()); currentArgStart = i + 1; } if (currentArgStart == innerText.length) return false; // No arguments // Extract the final argument, since there is no comma after the last argument args.Add(innerText.Substring(currentArgStart, innerText.length - currentArgStart).Trim()); var queryMarkerArguments = new List<QueryMarkerArgument>(); using (var context = SearchService.CreateContext("")) { foreach (var arg in args) { var parserArgs = new SearchExpressionParserArgs(arg, context, SearchExpressionParserFlags.ImplicitLiterals); SearchExpression expression = null; try { expression = SearchExpression.Parse(parserArgs); } catch (SearchExpressionParseException) { } if (expression == null || !expression.types.HasAny(SearchExpressionType.Literal)) { queryMarkerArguments.Add(new QueryMarkerArgument { rawText = arg, expression = expression, value = expression == null ? arg.ToString() : null }); continue; } var results = expression.Execute(context); var resolvedValue = results.FirstOrDefault(item => item != null); var resolvedValueObject = resolvedValue?.value; queryMarkerArguments.Add(new QueryMarkerArgument { rawText = arg, expression = expression, value = resolvedValueObject }); } } marker = new QueryMarker { type = controlType, text = text, args = queryMarkerArguments.ToArray() }; return true; } public static bool IsQueryMarker(StringView text) { return text.StartsWith(k_StartToken) && text.EndsWith(k_EndToken); } public static QueryMarker[] ParseAllMarkers(string text) { return ParseAllMarkers(text.GetStringView()); } public static QueryMarker[] ParseAllMarkers(StringView text) { if (text.length <= k_StartToken.Length + k_EndToken.Length) return null; List<QueryMarker> markers = new List<QueryMarker>(); var startIndex = -1; var endIndex = -1; var nestedLevel = 0; bool inQuotes = false; for (var i = 0; i < text.length; ++i) { if (i + k_StartToken.Length > text.length || i + k_EndToken.Length > text.length) break; if (ParserUtils.IsOpener(text[i]) && !inQuotes) ++nestedLevel; if (ParserUtils.IsCloser(text[i]) && !inQuotes) --nestedLevel; if (text[i] == '"' || text[i] == '\'') inQuotes = !inQuotes; if (startIndex == -1 && nestedLevel == 0 && !inQuotes) { var openerSv = text.Substring(i, k_StartToken.Length); if (openerSv == k_StartToken) startIndex = i; } if (endIndex == -1 && nestedLevel == 0 && !inQuotes) { var closerSv = text.Substring(i, k_EndToken.Length); if (closerSv == k_EndToken) endIndex = i + k_EndToken.Length; } if (startIndex != -1 && endIndex != -1) { var markerSv = text.Substring(startIndex, endIndex - startIndex); if (TryParse(markerSv, out var marker)) markers.Add(marker); startIndex = -1; endIndex = -1; } } return markers.ToArray(); } public static string ReplaceMarkersWithRawValues(string text, out QueryMarker[] markers) { return ReplaceMarkersWithRawValues(text.GetStringView(), out markers); } public static string ReplaceMarkersWithRawValues(StringView text, out QueryMarker[] markers) { markers = ParseAllMarkers(text); if (markers == null || markers.Length == 0) return text.ToString(); var modifiedSv = text.GetSubsetStringView(); foreach (var queryMarker in markers) { if (!queryMarker.valid || queryMarker.args == null || queryMarker.args.Length == 0) continue; var valueArg = queryMarker.args[0]; modifiedSv.ReplaceWithSubset(queryMarker.text.startIndex, queryMarker.text.endIndex, valueArg.rawText.startIndex, valueArg.rawText.endIndex); } return modifiedSv.ToString(); } public static string ReplaceMarkersWithEvaluatedValues(string text, SearchContext context) { var allMarkers = ParseAllMarkers(text); var modifiedText = text; var offset = 0; foreach (var queryMarker in allMarkers) { if (!queryMarker.valid || queryMarker.args == null || queryMarker.args.Length == 0) continue; var valueArg = queryMarker.args[0]; var value = valueArg.value; if (valueArg.needsEvaluation) value = valueArg.Evaluate(context).FirstOrDefault(); if (value == null) continue; var valueStr = value.ToString(); modifiedText = modifiedText.Remove(queryMarker.text.startIndex + offset, queryMarker.text.length); modifiedText = modifiedText.Insert(queryMarker.text.startIndex + offset, valueStr); offset += valueStr.Length - queryMarker.text.length; } return modifiedText; } public static string ReplaceMarkersWithEvaluatedValues(StringView text, SearchContext context) { return ReplaceMarkersWithEvaluatedValues(text.ToString(), context); } // Evaluate arguments as search expressions public IEnumerable<object> EvaluateArgs(bool reevaluateLiterals = false) { using (var context = SearchService.CreateContext("")) { return EvaluateArgs(context, reevaluateLiterals).ToList(); // Calling ToList to force evaluation so context is not used after disposal. } } public IEnumerable<object> EvaluateArgs(SearchContext context, bool reevaluateLiterals = false) { return args.SelectMany(qma => qma.Evaluate(context, reevaluateLiterals)); } public IEnumerable<object> EvaluateArgsNoSpread(bool reevaluateLiterals = false) { using (var context = SearchService.CreateContext("")) { return EvaluateArgsNoSpread(context, reevaluateLiterals).ToList(); // Calling ToList to force evaluation so context is not used after disposal. } } public IEnumerable<object> EvaluateArgsNoSpread(SearchContext context, bool reevaluateLiterals = false) { return args.Select(qma => qma.Evaluate(context, reevaluateLiterals)); } public override string ToString() { return $"{k_StartToken}{type}:{string.Join(",", EvaluateArgs())}{k_EndToken}"; } } }
UnityCsReference/Modules/QuickSearch/Editor/QueryBuilder/QueryMarker.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/QueryBuilder/QueryMarker.cs", "repo_id": "UnityCsReference", "token_count": 5213 }
431
// 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> /// A QueryError holds the definition of a query parsing error. /// </summary> public class QueryError { /// <summary> Index where the error happened. </summary> public int index { get; set; } /// <summary> Length of the block that was being parsed. </summary> public int length { get; set; } /// <summary> Reason why the parsing failed. </summary> public string reason { get; set; } /// <summary> The error type. </summary> internal SearchQueryErrorType type { get; set; } /// <summary> /// Construct a new QueryError with a default length of 0. /// </summary> public QueryError() { index = 0; reason = ""; length = 0; type = SearchQueryErrorType.Error; } /// <summary> /// Construct a new QueryError with a default length of 1. /// </summary> /// <param name="index">Index where the error happened.</param> /// <param name="reason">Reason why the parsing failed.</param> public QueryError(int index, string reason) : this(index, 1, reason) {} /// <summary> /// Construct a new QueryError. /// </summary> /// <param name="index">Index where the error happened.</param> /// <param name="length">Length of the block that was being parsed.</param> /// <param name="reason">Reason why the parsing failed.</param> public QueryError(int index, int length, string reason) : this(index, length, reason, SearchQueryErrorType.Error) {} internal QueryError(int index, string reason, SearchQueryErrorType type) : this(index, 1, reason, type) {} internal QueryError(int index, int length, string reason, SearchQueryErrorType type) { this.index = index; this.reason = reason; this.length = length; this.type = type; } } }
UnityCsReference/Modules/QuickSearch/Editor/QueryEngine/QueryError.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/QueryEngine/QueryError.cs", "repo_id": "UnityCsReference", "token_count": 888 }
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; using System.Collections.Generic; using System.Linq; using UnityEditor.Search.Providers; using UnityEditor.SearchService; using UnityEngine; using Object = UnityEngine.Object; namespace UnityEditor.Search { class SearchApiSession : IDisposable { bool m_Disposed; public SearchContext context { get; private set; } public Action<IEnumerable<string>> onAsyncItemsReceived { get; set; } public SearchApiSession(ISearchContext searchContext, params SearchProvider[] providers) { context = new SearchContext(providers); context.runtimeContext = new RuntimeSearchContext() { searchEngineContext = searchContext }; } ~SearchApiSession() { Dispose(false); } public void StopAsyncResults() { if (context.searchInProgress) { context.sessions.StopAllAsyncSearchSessions(); } context.asyncItemReceived -= OnAsyncItemsReceived; } public void StartAsyncResults() { context.asyncItemReceived += OnAsyncItemsReceived; } private void OnAsyncItemsReceived(SearchContext context, IEnumerable<SearchItem> items) { onAsyncItemsReceived?.Invoke(items.Select(item => item.id)); } protected virtual void Dispose(bool disposing) { if (!m_Disposed) { StopAsyncResults(); context?.Dispose(); m_Disposed = true; context = null; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } abstract class QuickSearchEngine : ISearchEngineBase, IDisposable { bool m_Disposed; public Dictionary<Guid, SearchApiSession> searchSessions = new Dictionary<Guid, SearchApiSession>(); ~QuickSearchEngine() { Dispose(false); } public virtual void BeginSession(ISearchContext context) { if (searchSessions.ContainsKey(context.guid)) return; var provider = SearchService.Providers.First(p => p.id == providerId); searchSessions.Add(context.guid, new SearchApiSession(context, provider)); } public virtual void EndSession(ISearchContext context) { if (!searchSessions.ContainsKey(context.guid)) return; searchSessions[context.guid].StopAsyncResults(); searchSessions[context.guid].Dispose(); searchSessions.Remove(context.guid); } public virtual void BeginSearch(ISearchContext context, string query) { if (!searchSessions.ContainsKey(context.guid)) return; searchSessions[context.guid].StopAsyncResults(); searchSessions[context.guid].StartAsyncResults(); } public virtual void EndSearch(ISearchContext context) {} internal static string k_Name = "Advanced"; public string name => k_Name; public abstract string providerId { get; } protected virtual void Dispose(bool disposing) { if (!m_Disposed) { foreach (var kvp in searchSessions) { kvp.Value.Dispose(); } m_Disposed = true; searchSessions = null; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } [ProjectSearchEngine] class ProjectSearchEngine : QuickSearchEngine, IProjectSearchEngine { public override string providerId => "asset"; public override void BeginSession(ISearchContext context) { if (searchSessions.ContainsKey(context.guid)) return; var engineProvider = SearchService.GetProvider(providerId); var adbProvider = SearchService.GetProvider(AdbProvider.type); var searchSession = new SearchApiSession(context, adbProvider, engineProvider); searchSessions.Add(context.guid, searchSession); } public virtual IEnumerable<string> Search(ISearchContext context, string query, Action<IEnumerable<string>> asyncItemsReceived) { if (!searchSessions.ContainsKey(context.guid)) return new string[] {}; var searchSession = searchSessions[context.guid]; var projectSearchContext = (ProjectSearchContext)context; if (asyncItemsReceived != null) { searchSession.onAsyncItemsReceived = asyncItemsReceived; } if (context.requiredTypeNames != null && context.requiredTypeNames.Any()) { searchSession.context.filterType = Utils.GetTypeFromName(context.requiredTypeNames.First()); } else { searchSession.context.filterType = null; } searchSession.context.searchText = query; searchSession.context.options &= ~SearchFlags.Packages; if (projectSearchContext.searchFilter != null) { searchSession.context.userData = projectSearchContext.searchFilter; if (projectSearchContext.searchFilter.searchArea == SearchFilter.SearchArea.InAssetsOnly) { searchSession.context.searchText = $"{query} a:assets"; } else if (projectSearchContext.searchFilter.searchArea == SearchFilter.SearchArea.InPackagesOnly) { searchSession.context.options |= SearchFlags.Packages; searchSession.context.searchText = $"{query} a:packages"; } else if (projectSearchContext.searchFilter.searchArea == SearchFilter.SearchArea.AllAssets) { searchSession.context.options |= SearchFlags.Packages; } } var items = SearchService.GetItems(searchSession.context); return items.Select(item => ToPath(item)); } private string ToPath(SearchItem item) { if (GlobalObjectId.TryParse(item.id, out var gid)) return AssetDatabase.GUIDToAssetPath(gid.assetGUID); return item.id; } } [SceneSearchEngine] class SceneSearchEngine : QuickSearchEngine, ISceneSearchEngine { private readonly Dictionary<Guid, HashSet<int>> m_SearchItemsBySession = new Dictionary<Guid, HashSet<int>>(); public override string providerId => "scene"; public override void BeginSearch(ISearchContext context, string query) { if (!searchSessions.ContainsKey(context.guid)) return; base.BeginSearch(context, query); var searchSession = searchSessions[context.guid]; if (searchSession.context.searchText == query) return; searchSession.context.searchText = query; if (context.requiredTypeNames != null && context.requiredTypeNames.Any()) { searchSession.context.filterType = Utils.GetTypeFromName(context.requiredTypeNames.First()); } else { searchSession.context.filterType = typeof(GameObject); } if (!m_SearchItemsBySession.ContainsKey(context.guid)) m_SearchItemsBySession.Add(context.guid, new HashSet<int>()); var searchItemsSet = m_SearchItemsBySession[context.guid]; searchItemsSet.Clear(); foreach (var id in SearchService.GetItems(searchSession.context, SearchFlags.Synchronous).Select(item => Convert.ToInt32(item.id))) { searchItemsSet.Add(id); } } public override void EndSearch(ISearchContext context) { if (!searchSessions.ContainsKey(context.guid)) return; base.EndSearch(context); } public override void EndSession(ISearchContext context) { if (m_SearchItemsBySession.ContainsKey(context.guid)) { m_SearchItemsBySession[context.guid].Clear(); m_SearchItemsBySession.Remove(context.guid); } base.EndSession(context); } public virtual bool Filter(ISearchContext context, string query, HierarchyProperty objectToFilter) { if (!m_SearchItemsBySession.ContainsKey(context.guid)) return false; return m_SearchItemsBySession[context.guid].Contains(objectToFilter.instanceID); } } [ObjectSelectorEngine] class ObjectSelectorEngine : QuickSearchEngine, IObjectSelectorEngine { public override string providerId => "asset"; AdvancedObjectSelector m_CurrentSelector; public override void BeginSearch(ISearchContext context, string query) {} public override void BeginSession(ISearchContext context) { m_CurrentSelector = null; var objectSelectorContext = context as ObjectSelectorSearchContext; if (objectSelectorContext == null) return; if (!TryGetValidHandler(objectSelectorContext, out m_CurrentSelector)) return; var selectorArgs = new AdvancedObjectSelectorParameters(objectSelectorContext); m_CurrentSelector.handler(AdvancedObjectSelectorEventType.BeginSession, selectorArgs); } public override void EndSearch(ISearchContext context) {} public override void EndSession(ISearchContext context) { if (m_CurrentSelector == null) return; var selectorArgs = new AdvancedObjectSelectorParameters(context); m_CurrentSelector.handler(AdvancedObjectSelectorEventType.EndSession, selectorArgs); m_CurrentSelector = null; } public bool SelectObject(ISearchContext context, Action<Object, bool> selectHandler, Action<Object> trackingHandler) { if (m_CurrentSelector == null) return false; var selectorArgs = new AdvancedObjectSelectorParameters(context, selectHandler, trackingHandler); m_CurrentSelector.handler(AdvancedObjectSelectorEventType.OpenAndSearch, selectorArgs); SearchAnalytics.SendEvent(null, SearchAnalytics.GenericEventType.QuickSearchPickerOpens, m_CurrentSelector.id, "object", "ObjectSelectorEngine"); return true; } public void SetSearchFilter(ISearchContext context, string searchFilter) { if (m_CurrentSelector == null) return; var selectorArgs = new AdvancedObjectSelectorParameters(context, searchFilter); m_CurrentSelector.handler(AdvancedObjectSelectorEventType.SetSearchFilter, selectorArgs); } static bool TryGetValidHandler(ObjectSelectorSearchContext context, out AdvancedObjectSelector selector) { selector = null; foreach (var searchSelector in GetActiveSelectors()) { if (searchSelector.validator.handler(context)) { selector = searchSelector; return true; } } return false; } static IEnumerable<AdvancedObjectSelector> GetActiveSelectors() { return SearchService.OrderedObjectSelectors.Where(p => p.active); } } }
UnityCsReference/Modules/QuickSearch/Editor/SearchEngines/SearchEngines.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/SearchEngines/SearchEngines.cs", "repo_id": "UnityCsReference", "token_count": 5327 }
433
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Linq; using System.Text.RegularExpressions; using System.Collections.Generic; using System.ComponentModel; namespace UnityEditor.Search { static partial class Evaluators { static Regex QueryVariableRx = new Regex(@"([\$\@])([\#\w][\w\d\.\\/]*)"); [Description("Returns a Search Query from a string"), Category("Primitives")] [SearchExpressionEvaluator(SearchExpressionEvaluationHints.ExpandSupported | SearchExpressionEvaluationHints.DoNotValidateSignature)] public static IEnumerable<SearchItem> Query(SearchExpressionContext c) { if (c.expression.types.HasFlag(SearchExpressionType.Function)) { using (c.runtime.Push(c.args[0], c.args.Skip(1))) return Query(c.runtime.current); } // Resolve variables var queryText = UnEscapeExpressions(c.expression); if (c.items.Count > 0 && (queryText.Contains('$') || queryText.Contains('@'))) { foreach (Match m in QueryVariableRx.Matches(queryText)) { for (int i = 2; i < m.Groups.Count; i++) queryText = ResolveVariable(queryText, m.Groups[1].Value, m.Groups[i].Value, c); } } // Spread nested expressions if (c.args?.Length > 0) return SpreadExpression(queryText, c); return RunQuery(c, queryText); } public static IEnumerable<SearchItem> RunQuery(SearchExpressionContext c, string queryText) { using (var context = new SearchContext(c.search.GetProviders(), queryText, c.search.options | SearchFlags.QueryString)) using (var results = SearchService.Request(context)) foreach (var r in results) yield return r; } readonly struct SpreadContext { public readonly string query; public readonly string alias; public SpreadContext(string query, string alias = null) { this.query = query; this.alias = alias; } } private static IEnumerable<SearchItem> SpreadExpression(string query, SearchExpressionContext c) { var spreaded = new List<SpreadContext>(); var toSpread = new List<SpreadContext>() { new SpreadContext(query.ToString(), c.ResolveAlias()) }; foreach (var e in c.args) { spreaded = new List<SpreadContext>(); foreach (var r in e.Execute(c)) { if (r != null) { foreach (var q in toSpread) { if (r.value == null) continue; var replacement = r.value is UnityEngine.Object ? TaskEvaluatorManager.EvaluateMainThread(() => r.value.ToString()): r.value.ToString(); if (replacement.LastIndexOf(' ') != -1) replacement = '"' + replacement + '"'; var pattern = @"[\[\{]?" + Regex.Escape(e.outerText.ToString()) + @"[\}\]]?"; spreaded.Add(new SpreadContext(Regex.Replace(q.query, pattern, replacement), alias: c.ResolveAlias(e, replacement))); } } else yield return null; } toSpread = spreaded; } foreach (var s in spreaded) { if (c.flags.HasFlag(SearchExpressionExecutionFlags.Expand)) { yield return SearchExpression.CreateSearchExpressionItem(s.query, s.alias); } else { foreach (var r in RunQuery(c, s.query)) yield return r; } } } static string ResolveVariable(string query, string token, string varName, SearchExpressionContext c) { var v = SelectorManager.SelectValue(c, varName, out var _); if (v == null) c.ThrowError($"Cannot resolve variable {token}{varName}"); return query.Replace(token + varName, v.ToString()); } static string UnEscapeExpressions(SearchExpression expression) { if (!expression.hasEscapedNestedExpressions) return expression.innerText.ToString(); return ParserUtils.UnEscapeExpressions(expression.innerText); } } }
UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Evaluators/QueryEvaluator.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Evaluators/QueryEvaluator.cs", "repo_id": "UnityCsReference", "token_count": 2437 }
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; using System.Linq; using System.Collections.Generic; using System.Reflection; using UnityEngine; using System.Text.RegularExpressions; namespace UnityEditor.Search { internal delegate IEnumerable<SearchItem> SearchExpressionEvaluatorHandler(SearchExpressionContext context); [Flags] public enum SearchExpressionEvaluationHints { ThreadSupported = 1 << 0, ThreadNotSupported = 1 << 1, ExpandSupported = 1 << 2, AlwaysExpand = 1 << 3, DoNotValidateSignature = 1 << 4, DoNotValidateArgsSignature = 1 << 5, ImplicitArgsLiterals = 1 << 6, Default = ThreadSupported } [AttributeUsage(AttributeTargets.Method)] public class SearchExpressionEvaluatorAttribute : Attribute { public SearchExpressionEvaluatorAttribute(params SearchExpressionType[] signatureArgumentTypes) : this(null, SearchExpressionEvaluationHints.Default, new SearchExpressionValidator.Signature(signatureArgumentTypes)) {} public SearchExpressionEvaluatorAttribute(string name, params SearchExpressionType[] signatureArgumentTypes) : this(name, SearchExpressionEvaluationHints.Default, new SearchExpressionValidator.Signature(signatureArgumentTypes)) {} public SearchExpressionEvaluatorAttribute(SearchExpressionEvaluationHints hints, params SearchExpressionType[] signatureArgumentTypes) : this(null, hints, new SearchExpressionValidator.Signature(signatureArgumentTypes)) {} public SearchExpressionEvaluatorAttribute(string name, SearchExpressionEvaluationHints hints, params SearchExpressionType[] signatureArgumentTypes) : this(name, hints, new SearchExpressionValidator.Signature(signatureArgumentTypes)) {} private SearchExpressionEvaluatorAttribute(string name, SearchExpressionEvaluationHints hints, SearchExpressionValidator.Signature signature) { this.name = name; this.signature = signature; this.hints = hints; } internal string name { get; private set; } internal SearchExpressionValidator.Signature signature { get; private set; } internal SearchExpressionEvaluationHints hints { get; private set; } } [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class SearchExpressionEvaluatorSignatureOverloadAttribute : Attribute { public SearchExpressionEvaluatorSignatureOverloadAttribute(params SearchExpressionType[] signatureArgumentTypes) : this(new SearchExpressionValidator.Signature(signatureArgumentTypes)) {} private SearchExpressionEvaluatorSignatureOverloadAttribute(SearchExpressionValidator.Signature signature) { this.signature = signature; } internal SearchExpressionValidator.Signature signature { get; private set; } } static class EvaluatorManager { public static List<SearchExpressionEvaluator> evaluators { get; private set; } public static SearchItemQueryEngine itemQueryEngine; public static Dictionary<string, List<SearchExpressionValidator.Signature>> evaluatorSignatures = new Dictionary<string, List<SearchExpressionValidator.Signature>>(); static EvaluatorManager() { try { RefreshEvaluators(); } catch (Exception) { Debug.LogError("Error while loading evaluators"); } itemQueryEngine = new SearchItemQueryEngine(); } public static SearchExpressionEvaluator GetEvaluatorByNameDuringEvaluation(string name, StringView errorView, SearchExpressionContext context) { return GetEvaluatorByName(name, errorView, false, context); } public static SearchExpressionEvaluator GetEvaluatorByNameDuringParsing(string name, StringView errorView) { return GetEvaluatorByName(name, errorView, true); } private static SearchExpressionEvaluator GetEvaluatorByName(string name, StringView errorView, bool duringParsing, SearchExpressionContext context = default) { var evaluator = FindEvaluatorByName(name); if (!evaluator.valid) { if (duringParsing) throw new SearchExpressionParseException(GetEvaluatorNameExceptionMessage(name), errorView.startIndex, errorView.length); else context.ThrowError(GetEvaluatorNameExceptionMessage(name), errorView); } return evaluator; } public static SearchExpressionEvaluator GetConstantEvaluatorByName(string name) { var evaluator = FindEvaluatorByName(name); if (!evaluator.valid) throw new ArgumentException(GetEvaluatorNameExceptionMessage(name), nameof(name)); return evaluator; } private static string GetEvaluatorNameExceptionMessage(string name) { return $"Search expression evaluator {name} does not exist."; } public static IEnumerable<SearchExpressionValidator.Signature> GetSignaturesByName(string name) { name = name.ToLowerInvariant(); if (evaluatorSignatures.TryGetValue(name.ToLowerInvariant(), out var signatures)) { return signatures.OrderByDescending(s => s.mandatoryArgumentNumber); } return null; } public static void AddSignature(string name, SearchExpressionValidator.Signature signature) { name = name.ToLowerInvariant(); string error = ""; if (!SearchExpressionValidator.ValidateSignature(name, signature, ref error)) { Debug.LogError($"Invalid signature for {name}({signature}) : {error}"); return; } if (!evaluatorSignatures.TryGetValue(name.ToLowerInvariant(), out var signatures)) { signatures = new List<SearchExpressionValidator.Signature>(); evaluatorSignatures.Add(name, signatures); } evaluatorSignatures[name].Add(signature); } public static SearchExpressionEvaluator FindEvaluatorByName(string name) { foreach (var e in evaluators) if (string.Equals(e.name, name, StringComparison.OrdinalIgnoreCase)) return e; return default; } public static void RefreshEvaluators() { var supportedSignature = MethodSignature.FromDelegate<SearchExpressionEvaluatorHandler>(); evaluators = ReflectionUtils.LoadAllMethodsWithAttribute<SearchExpressionEvaluatorAttribute, SearchExpressionEvaluator>((mi, attribute, handler) => { var descAttr = mi.GetCustomAttribute<System.ComponentModel.DescriptionAttribute>(); var description = descAttr != null ? descAttr.Description : null; var catAttr = mi.GetCustomAttribute<System.ComponentModel.CategoryAttribute>(); var category = catAttr != null ? catAttr.Category : "General"; var name = attribute.name ?? mi.Name; var additionalSignatures = mi.GetCustomAttributes<SearchExpressionEvaluatorSignatureOverloadAttribute>(); if (handler is SearchExpressionEvaluatorHandler _handler) { if (attribute.signature != null) AddSignature(name, attribute.signature); foreach (var additionalSignature in additionalSignatures) { AddSignature(name, additionalSignature.signature); } return new SearchExpressionEvaluator(name, description, category, _handler, attribute.hints); } Debug.LogWarning($"Invalid evaluator handler: \"{attribute.name}\" using: \"{mi.DeclaringType.FullName}.{mi.Name}\""); return new SearchExpressionEvaluator(); }, supportedSignature, ReflectionUtils.AttributeLoaderBehavior.DoNotThrowOnValidation).Distinct().Where(evaluator => evaluator.valid).ToList(); } } class SearchExpressionEvaluatorException : Exception { public SearchExpressionContext evaluationContext { get; private set; } public StringView errorView { get; private set; } public SearchExpressionEvaluatorException(SearchExpressionContext c, Exception innerException = null) : this(innerException != null ? innerException.Message : "Failed", GetErrorStringView(c, innerException), c, innerException) { } public SearchExpressionEvaluatorException(string message, StringView errorPosition, SearchExpressionContext c, Exception innerException = null) : base(FormatDefaultEvaluationExceptionMessage(c, message), innerException) { if (errorPosition.IsNullOrEmpty()) { errorView = new StringView(c.search.searchText); } else { errorView = errorPosition; } evaluationContext = c; } private static string FormatDefaultEvaluationExceptionMessage(SearchExpressionContext c, string prefixMessage = "Failed") { if (!c.valid) return prefixMessage; var e = c.expression; var eval = e.evaluator; var m = eval.execute.Method; return $"{prefixMessage} to evaluate expression `{e.outerText}` using {m.DeclaringType.Name}.{m.Name}"; } private static StringView GetErrorStringView(SearchExpressionContext c, Exception innerException) { if (innerException is SearchExpressionEvaluatorException runtimeEx) return runtimeEx.errorView; return c.expression?.outerText ?? c.search.searchQuery.GetStringView(); } } readonly struct SearchExpressionEvaluator : IEqualityComparer<SearchExpressionEvaluator> { public readonly string name; public readonly string description; public readonly string category; public readonly SearchExpressionEvaluatorHandler execute; public readonly SearchExpressionEvaluationHints hints; public bool valid => execute != null; internal SearchExpressionEvaluator(string name, string description, string category, SearchExpressionEvaluatorHandler execute, SearchExpressionEvaluationHints hints) { this.name = name; this.description = description; this.category = category; this.execute = execute; this.hints = hints; } internal SearchExpressionEvaluator(string name, SearchExpressionEvaluatorHandler execute, SearchExpressionEvaluationHints hints) : this(name, description : null , category : "General", execute, hints) { } public override string ToString() { return $"{name} | {execute.Method.DeclaringType.Name}.{execute.Method.Name}"; } public bool Equals(SearchExpressionEvaluator x, SearchExpressionEvaluator y) { return x.name == y.name; } public int GetHashCode(SearchExpressionEvaluator obj) { return obj.name.GetHashCode(); } } }
UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/SearchExpressionEvaluator.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/SearchExpressionEvaluator.cs", "repo_id": "UnityCsReference", "token_count": 4685 }
435
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace UnityEditor.Search { class SearchTemplateAttribute : Attribute { static List<SearchTemplateAttribute> s_QueryProviders; public string providerId { get; set; } public string description { get; set; } public UnityEngine.Search.SearchViewFlags viewFlags { get; set; } private Func<IEnumerable<string>> multiEntryHandler; public SearchTemplateAttribute(string description = null, string providerId = null, UnityEngine.Search.SearchViewFlags viewFlags = UnityEngine.Search.SearchViewFlags.None) { this.providerId = providerId; this.description = description; this.viewFlags = viewFlags; } internal static IEnumerable<ISearchQuery> GetAllQueries() { return providers.SelectMany(p => p.CreateQuery()); } IEnumerable<ISearchQuery> CreateQuery() { var queries = multiEntryHandler(); foreach (var query in queries) { var q = new SearchQuery(); var provider = SearchService.GetProvider(providerId); var searchText = query; if (provider != null && !query.StartsWith(provider.filterId)) { searchText = $"{provider.filterId} {query}"; } q.searchText = searchText; q.displayName = searchText; if (!string.IsNullOrEmpty(providerId)) q.viewState.providerIds = new[] { providerId }; q.description = description; q.viewState.SetSearchViewFlags(viewFlags); yield return q; } } internal static IEnumerable<SearchTemplateAttribute> providers { get { if (s_QueryProviders == null) RefreshQueryProviders(); return s_QueryProviders; } } internal static void RefreshQueryProviders() { s_QueryProviders = new List<SearchTemplateAttribute>(); var methods = TypeCache.GetMethodsWithAttribute<SearchTemplateAttribute>(); foreach (var mi in methods) { try { var attr = mi.GetCustomAttributes(typeof(SearchTemplateAttribute), false).Cast<SearchTemplateAttribute>().First(); if (mi.ReturnType == typeof(string)) { var singleEntryHandler = Delegate.CreateDelegate(typeof(Func<string>), mi) as Func<string>; attr.multiEntryHandler = () => new[] { singleEntryHandler() }; } else { attr.multiEntryHandler = Delegate.CreateDelegate(typeof(Func<IEnumerable<string>>), mi) as Func<IEnumerable<string>>; } s_QueryProviders.Add(attr); } catch (Exception e) { Debug.LogWarning($"Cannot register Search Template provider: {mi.Name}\n{e}"); } } } } }
UnityCsReference/Modules/QuickSearch/Editor/SearchQuery/SearchTemplateAttribute.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/SearchQuery/SearchTemplateAttribute.cs", "repo_id": "UnityCsReference", "token_count": 1668 }
436
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Collections.Generic; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.Search { public interface ITableView { bool readOnly { get; } SearchContext context { get; } void AddColumn(Vector2 mousePosition, int activeColumnIndex); void AddColumns(IEnumerable<SearchColumn> descriptors, int activeColumnIndex); void SetupColumns(IEnumerable<SearchItem> elements = null); void RemoveColumn(int activeColumnIndex); void SwapColumns(int columnIndex, int swappedColumnIndex); IEnumerable<SearchItem> GetElements(); IEnumerable<SearchColumn> GetColumns(); IEnumerable<SearchItem> GetRows(); SearchTable GetSearchTable(); void SetSelection(IEnumerable<SearchItem> items); void OnItemExecuted(SearchItem item); void SetDirty(); bool OpenContextualMenu(Event evt, SearchItem item); [System.Obsolete("Search IMGUI is not supported anymore", error: false)] // 2023.1 void UpdateColumnSettings(int columnIndex, IMGUI.Controls.MultiColumnHeaderState.Column columnSettings); [System.Obsolete("Search IMGUI is not supported anymore", error: false)] // 2023.1 bool AddColumnHeaderContextMenuItems(GenericMenu menu); [System.Obsolete("Search IMGUI is not supported anymore", error: false)] // 2023.1 void AddColumnHeaderContextMenuItems(GenericMenu menu, SearchColumn sourceColumn); /// Mainly used for test internal IEnumerable<object> GetValues(int columnIdx); internal float GetRowHeight(); internal int GetColumnIndex(string name); internal SearchColumn FindColumnBySelector(string selector); } [System.Obsolete("IMGUI is not support anymore. Use ITableView interface instead.", error: false)] // 2023.1 public class PropertyTable : UnityEditor.IMGUI.Controls.TreeView, System.IDisposable { public PropertyTable(string serializationUID, ITableView tableView) : base(new IMGUI.Controls.TreeViewState()) => throw new System.NotSupportedException(); protected override void BeforeRowsGUI() => throw new System.NotSupportedException(); protected override UnityEditor.IMGUI.Controls.TreeViewItem BuildRoot() => throw new System.NotSupportedException(); protected override System.Collections.Generic.IList<UnityEditor.IMGUI.Controls.TreeViewItem> BuildRows(UnityEditor.IMGUI.Controls.TreeViewItem root) => throw new System.NotSupportedException(); protected override bool CanStartDrag(UnityEditor.IMGUI.Controls.TreeView.CanStartDragArgs args) => throw new System.NotSupportedException(); public void Dispose() => throw new System.NotSupportedException(); protected override void DoubleClickedItem(int id) => throw new System.NotSupportedException(); public void FrameColumn(int columnIndex) => throw new System.NotSupportedException(); protected override DragAndDropVisualMode HandleDragAndDrop(UnityEditor.IMGUI.Controls.TreeView.DragAndDropArgs args) => throw new System.NotSupportedException(); protected override void KeyEvent() => throw new System.NotSupportedException(); public override void OnGUI(UnityEngine.Rect tableRect) => throw new System.NotSupportedException(); protected override void RowGUI(UnityEditor.IMGUI.Controls.TreeView.RowGUIArgs args) => throw new System.NotSupportedException(); protected override void SelectionChanged(System.Collections.Generic.IList<int> selectedIds) => throw new System.NotSupportedException(); protected override void SetupDragAndDrop(UnityEditor.IMGUI.Controls.TreeView.SetupDragAndDropArgs args) => throw new System.NotSupportedException(); } }
UnityCsReference/Modules/QuickSearch/Editor/Table/ITableView.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/Table/ITableView.cs", "repo_id": "UnityCsReference", "token_count": 1223 }
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; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Search; namespace UnityEditor.Search { static class SearchViewFlagsExtensions { public static bool HasAny(this SearchViewFlags flags, SearchViewFlags f) => (flags & f) != 0; public static bool HasAll(this SearchViewFlags flags, SearchViewFlags all) => (flags & all) == all; public static bool HasNone(this SearchViewFlags flags, SearchViewFlags f) => (flags & f) == 0; } [Serializable] public class SearchViewState : ISerializationCallbackReceiver { public static readonly Vector2 defaultSize = new Vector2(850f, 539f); static readonly string[] emptyProviders = new string[0]; [NonSerialized] private SearchContext m_Context; [NonSerialized] private bool m_WasDeserialized; [SerializeField] internal string[] providerIds; [SerializeField] internal SearchFlags searchFlags; [SerializeField] internal string searchText; // Also used as the initial query when the view was created [SerializeField] internal bool forceViewMode; [SerializeField] private SearchFunctor<Action<SearchItem, bool>> m_SelectHandler; [SerializeField] private SearchFunctor<Action<SearchItem>> m_TrackingHandler; [SerializeField] private SearchFunctor<Func<SearchItem, bool>> m_FilterHandler; [SerializeField] private SearchFunctor<Action<SearchContext, string, string>> m_GroupChanged; [NonSerialized] private SearchGlobalEventHandlerManager m_GlobalEventManager = new SearchGlobalEventHandlerManager(); internal SearchGlobalEventHandlerManager globalEventManager => m_GlobalEventManager; [SerializeField] private string m_ActiveQueryGuid; private ISearchQuery m_ActiveQuery; internal ISearchQuery activeQuery { get { if (m_ActiveQuery == null && !string.IsNullOrEmpty(m_ActiveQueryGuid)) { ISearchQuery loadedActiveQuery = SearchQuery.searchQueries.FirstOrDefault(query => query.guid == m_ActiveQueryGuid) ?? (ISearchQuery)SearchQueryAsset.savedQueries.FirstOrDefault(query => query.guid == m_ActiveQueryGuid); m_ActiveQuery = loadedActiveQuery; m_ActiveQueryGuid = null; } return m_ActiveQuery; } set { m_ActiveQuery = value; Dispatcher.Emit(SearchEvent.ActiveQueryChanged, new SearchEventPayload(this, value)); } } public bool hideTabs; public string sessionId; public string sessionName; public bool excludeClearItem; public SearchTable tableConfig; public bool ignoreSaveSearches; public bool hideAllGroup; public GUIContent windowTitle; public string title; public float itemSize; public Rect position; public SearchViewFlags flags; public string group; internal bool isPicker => HasFlag(SearchViewFlags.ObjectPicker); internal bool isSimplePicker => isPicker && !HasFlag(SearchViewFlags.ObjectPickerAdvancedUI); public bool hasQueryPanel { get { if (HasFlag(SearchViewFlags.DisableSavedSearchQuery)) return false; if (isPicker) return !isSimplePicker; return true; } } internal bool hasQueryBuilderToggle { get { if (HasFlag(SearchViewFlags.DisableBuilderModeToggle)) return false; if (isPicker) return !isSimplePicker; return true; } } public bool isQueryPanelVisible => hasQueryPanel && HasFlag(SearchViewFlags.OpenLeftSidePanel); internal int[] m_SelectedIds; internal int[] selectedIds { get { if (m_SelectedIds == null) m_SelectedIds = new int[0]; return m_SelectedIds; } set { m_SelectedIds = value; } } [SerializeField] public bool queryBuilderEnabled; public Action<SearchItem, bool> selectHandler { get => m_SelectHandler?.handler; set => m_SelectHandler = new SearchFunctor<Action<SearchItem, bool>>(value); } public Action<SearchItem> trackingHandler { get => m_TrackingHandler?.handler; set => m_TrackingHandler = new SearchFunctor<Action<SearchItem>>(value); } internal Func<SearchItem, bool> filterHandler { get => m_FilterHandler?.handler; set => m_FilterHandler = new SearchFunctor<Func<SearchItem, bool>>(value); } public Action<SearchContext, string, string> groupChanged { get => m_GroupChanged?.handler; set => m_GroupChanged = new SearchFunctor<Action<SearchContext, string, string>>(value); } public bool hasWindowSize => position.width > 0f && position.height > 0; public Vector2 windowSize => hasWindowSize ? position.size : defaultSize; [SerializeField] bool m_ContextUseExplicitProvidersAsNormalProviders; public SearchContext context { get { if (m_Context == null && m_WasDeserialized && Utils.IsMainProcess()) BuildContext(); return m_Context; } internal set { m_Context = value ?? throw new ArgumentNullException(nameof(value)); } } internal bool hasContext => m_Context != null; public string text { get { if (m_Context != null) return m_Context.searchText; return searchText; } set { searchText = value; if (m_Context != null) m_Context.searchText = value; } } internal string initialQuery { get; set; } internal SearchViewState() : this(null, null) {} public SearchViewState(SearchContext context) : this(context, null) {} public SearchViewState(SearchContext context, SearchViewFlags flags) : this(context, null) { SetSearchViewFlags(flags); } public SearchViewState(SearchContext context, Action<SearchItem, bool> selectHandler) { m_Context = context; sessionId = Guid.NewGuid().ToString("N"); this.selectHandler = selectHandler; trackingHandler = null; filterHandler = null; title = "item"; itemSize = (float)DisplayMode.Grid; position = Rect.zero; initialQuery = searchText = context?.searchText ?? string.Empty; tableConfig = null; providerIds = emptyProviders; } public SearchViewState(SearchContext context, Action<UnityEngine.Object, bool> selectObjectHandler, Action<UnityEngine.Object> trackingObjectHandler, string typeName, Type filterType) : this(context, null) { if (filterType == null && !string.IsNullOrEmpty(typeName)) { filterType = TypeCache.GetTypesDerivedFrom<UnityEngine.Object>().FirstOrDefault(t => t.Name == typeName); if (filterType is null) throw new ArgumentNullException(nameof(filterType)); } context.filterType = filterType; selectHandler = (item, canceled) => selectObjectHandler?.Invoke(Utils.ToObject(item, filterType), canceled); filterHandler = (item) => item == SearchItem.clear || (IsObjectMatchingType(item ?? SearchItem.clear, filterType ?? typeof(UnityEngine.Object))); trackingHandler = (item) => trackingObjectHandler?.Invoke(Utils.ToObject(item, filterType)); title = filterType?.Name ?? typeName; } public SearchViewState(SearchContext context, SearchTable tableConfig, SearchViewFlags flags = SearchViewFlags.None) : this(context, flags | SearchViewFlags.TableView) { group = null; this.tableConfig = tableConfig; } public static SearchViewState CreatePickerState(string title, SearchContext context, Action<UnityEngine.Object, bool> selectObjectHandler, Action<UnityEngine.Object> trackingObjectHandler, string typeName, Type filterType, SearchViewFlags flags = SearchViewFlags.None) { return new SearchViewState(context, selectObjectHandler, trackingObjectHandler, typeName, filterType) { title = title }.SetSearchViewFlags(flags | SearchViewFlags.ObjectPicker); } public static SearchViewState CreatePickerState( string title, SearchContext context, Action<SearchItem, bool> selectHandler, Action<SearchItem> trackingHandler = null, Func<SearchItem, bool> filterHandler = null, SearchViewFlags flags = SearchViewFlags.None) { return new SearchViewState(context, selectHandler) { title = title, trackingHandler = trackingHandler, filterHandler = filterHandler }.SetSearchViewFlags(flags | SearchViewFlags.ObjectPicker); } internal SearchViewState SetSearchViewFlags(SearchViewFlags flags) { if (m_Context != null) { context.options |= ToSearchFlags(flags); } this.flags = flags; if (flags.HasAny(SearchViewFlags.CompactView)) { itemSize = 0; forceViewMode = true; } if (flags.HasAny(SearchViewFlags.ListView)) { itemSize = (float)DisplayMode.List; forceViewMode = true; } if (flags.HasAny(SearchViewFlags.GridView)) { itemSize = (float)DisplayMode.Grid; forceViewMode = true; } if (flags.HasAny(SearchViewFlags.TableView)) { itemSize = (float)DisplayMode.Table; forceViewMode = true; } if (flags.HasAny(SearchViewFlags.IgnoreSavedSearches)) { ignoreSaveSearches = true; } if (flags.HasAny(SearchViewFlags.OpenInTextMode)) queryBuilderEnabled = false; else if (flags.HasAny(SearchViewFlags.OpenInBuilderMode) || isSimplePicker) queryBuilderEnabled = true; return this; } internal void Assign(SearchViewState state) { // Be sure to create a copy of the context Assign(state, state.context != null ? new SearchContext(state.context) : null); } internal void Assign(SearchViewState state, SearchContext searchContext) { var previousSearchView = context?.searchView; if (searchContext != null) { context = searchContext; if (context != null) context.searchView = previousSearchView; } searchFlags = searchContext?.options ?? state.searchFlags; searchText = searchContext?.searchText ?? state.searchText; providerIds = searchContext?.GetProviders().Select(p => p.id).ToArray() ?? state.providerIds.ToArray(); if (tableConfig != null && state.tableConfig?.columns?.Length > 0) tableConfig.columns = state.tableConfig?.columns.ToArray(); else tableConfig = state.tableConfig?.Clone(); if (this == state) return; sessionId = state.sessionId; sessionName = state.sessionName; excludeClearItem = state.excludeClearItem; ignoreSaveSearches = state.ignoreSaveSearches; activeQuery = state.activeQuery; initialQuery = state.initialQuery; title = state.title; itemSize = state.itemSize; position = state.position; flags = state.flags; forceViewMode = state.forceViewMode; group = state.group; queryBuilderEnabled = state.queryBuilderEnabled; } internal void BuildContext() { if (providerIds != null && providerIds.Length > 0) m_Context = SearchService.CreateContext(providerIds, searchText ?? string.Empty, searchFlags); else m_Context = SearchService.CreateContext(searchText ?? string.Empty, searchFlags | SearchFlags.OpenDefault); m_Context.useExplicitProvidersAsNormalProviders = m_ContextUseExplicitProvidersAsNormalProviders; m_WasDeserialized = false; } internal static SearchFlags ToSearchFlags(SearchViewFlags flags) { var sf = SearchFlags.None; if (flags.HasAny(SearchViewFlags.Debug)) sf |= SearchFlags.Debug; if (flags.HasAny(SearchViewFlags.NoIndexing)) sf |= SearchFlags.NoIndexing; if (flags.HasAny(SearchViewFlags.Packages)) sf |= SearchFlags.Packages; return sf; } static bool IsObjectMatchingType(in SearchItem item, in Type filterType) { if (item == SearchItem.clear) return true; var objType = item.ToType(filterType); if (objType == null) return false; return filterType.IsAssignableFrom(objType); } public static SearchViewState LoadDefaults() { var viewState = new SearchViewState(); return viewState.LoadDefaults(); } internal SearchViewState LoadDefaults(SearchFlags additionalFlags = SearchFlags.None) { var runningTests = Utils.IsRunningTests(); if (string.IsNullOrEmpty(title)) title = "Unity"; if (!forceViewMode && !runningTests) itemSize = SearchSettings.itemIconSize; hideTabs = SearchSettings.hideTabs; if (!runningTests && flags.HasNone(SearchViewFlags.OpenInBuilderMode) && flags.HasNone(SearchViewFlags.OpenInTextMode)) queryBuilderEnabled = SearchSettings.queryBuilder; if (hasContext) { context.options |= additionalFlags; if (runningTests) context.options |= SearchFlags.Dockable; } return this; } public void OnBeforeSerialize() { if (context == null) return; searchFlags = context.options; searchText = context.searchText; providerIds = GetProviderIds().ToArray(); m_ActiveQueryGuid = m_ActiveQuery?.guid; m_ContextUseExplicitProvidersAsNormalProviders = context.useExplicitProvidersAsNormalProviders; } public void OnAfterDeserialize() { m_WasDeserialized = true; initialQuery = searchText; if (tableConfig != null && tableConfig.columns?.Length == 0) tableConfig = null; } public IEnumerable<string> GetProviderIds() { if (m_Context != null) return m_Context.GetProviders().Select(p => p.id); return providerIds; } internal SearchProvider GetProviderById(string providerId) { if (m_Context != null) return m_Context.GetProviders().FirstOrDefault(p => p.active && p.id == providerId); return null; } public IEnumerable<string> GetProviderTypes() { var providers = m_Context != null ? m_Context.GetProviders() : SearchService.GetProviders(providerIds); return providers.Select(p => p.type).Distinct(); } public bool HasFlag(SearchViewFlags flags) => (this.flags & flags) != 0; public override string ToString() { return $"[{sessionId}] {text} ({flags})"; } } }
UnityCsReference/Modules/QuickSearch/Editor/UI/SearchViewState.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/UI/SearchViewState.cs", "repo_id": "UnityCsReference", "token_count": 7671 }
438
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEditor.UIElements; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.Search { class SearchQueryBuilderView : SearchElement, ISearchField, INotifyValueChanged<string> { public static readonly string ussClassName = "search-query-builder"; private QueryBuilder m_QueryBuilder; private TextField m_TextField; private readonly SearchFieldBase<TextField, string> m_SearchField; private Action m_RefreshBuilderOff; int ISearchField.controlID => (int)m_SearchField.controlid; int ISearchField.cursorIndex => m_TextField?.cursorIndex ?? -1; string ISearchField.text => m_TextField?.text ?? context.searchText; private bool m_UseSearchGlobalEventHandler; string INotifyValueChanged<string>.value { get => m_QueryBuilder?.searchText; set { if (m_QueryBuilder == null || (m_QueryBuilder.hasOwnText && string.Equals(value, m_QueryBuilder.searchText, StringComparison.Ordinal))) return; if (panel != null) { var previousValue = m_QueryBuilder.searchText; ((INotifyValueChanged<string>)this).SetValueWithoutNotify(value); using (ChangeEvent<string> evt = ChangeEvent<string>.GetPooled(previousValue, m_QueryBuilder.searchText)) { evt.target = this; SendEvent(evt); } } else { ((INotifyValueChanged<string>)this).SetValueWithoutNotify(value); } } } internal QueryBuilder builder => m_QueryBuilder; internal TextField searchField => m_TextField; public SearchQueryBuilderView(string name, ISearchView viewModel, SearchFieldBase<TextField, string> searchField, bool useSearchGlobalEventHandler) : base(name, viewModel, ussClassName) { m_SearchField = searchField; m_UseSearchGlobalEventHandler = useSearchGlobalEventHandler; } protected override void OnAttachToPanel(AttachToPanelEvent evt) { base.OnAttachToPanel(evt); if (m_UseSearchGlobalEventHandler) { RegisterGlobalEventHandler<KeyDownEvent>(KeyEventHandler, 0); } else { RegisterCallback<KeyDownEvent>(OnKeyDown, useTrickleDown: TrickleDown.TrickleDown); } On(SearchEvent.RefreshBuilder, RefreshBuilder); On(SearchEvent.SearchContextChanged, Rebuild); m_TextField = m_SearchField.Q<TextField>(); m_TextField.RemoveFromHierarchy(); RefreshBuilder(); m_SearchField.value = m_QueryBuilder.wordText; m_TextField.RegisterCallback<ChangeEvent<string>>(OnQueryChanged); } protected override void OnDetachFromPanel(DetachFromPanelEvent evt) { m_TextField?.UnregisterCallback<ChangeEvent<string>>(OnQueryChanged); m_TextField = null; m_RefreshBuilderOff?.Invoke(); if (m_UseSearchGlobalEventHandler) { UnregisterGlobalEventHandler<KeyDownEvent>(KeyEventHandler); } else { UnregisterCallback<KeyDownEvent>(OnKeyDown); } Off(SearchEvent.RefreshBuilder, RefreshBuilder); Off(SearchEvent.SearchContextChanged, Rebuild); base.OnDetachFromPanel(evt); } private void Rebuild(ISearchEvent evt) { m_QueryBuilder = null; DeferRefreshBuilder(); } private void OnQueryChanged(ChangeEvent<string> evt) { if (m_QueryBuilder != null) { m_QueryBuilder.wordText = evt.newValue; m_ViewModel.SetSelection(); } } private void OnKeyDown(KeyDownEvent evt) { if (evt.imguiEvent != null && m_QueryBuilder != null) { if (KeyEventHandler(evt)) evt.StopImmediatePropagation(); } } private bool KeyEventHandler(KeyDownEvent evt) { if (m_QueryBuilder == null) return false; var isHandled = m_QueryBuilder.HandleGlobalKeyDown(evt) || m_QueryBuilder.HandleKeyEvent(evt.imguiEvent); if (isHandled) Focus(); return isHandled; } private void DeferRefreshBuilder() { m_RefreshBuilderOff?.Invoke(); m_RefreshBuilderOff = Utils.CallDelayed(RefreshBuilder, 0.1f); } private void RefreshBuilder(ISearchEvent evt) { DeferRefreshBuilder(); } private void RefreshBuilder() { Clear(); if (m_QueryBuilder != null) m_QueryBuilder.Build(); else m_QueryBuilder = new QueryBuilder(context, this); foreach (var b in m_QueryBuilder.EnumerateBlocks()) Add(b.CreateGUI()); if (context.options.HasAny(SearchFlags.Debug)) Debug.LogWarning($"Refresh query builder {m_QueryBuilder.searchText} ({m_QueryBuilder.blocks.Count})"); m_TextField?.SetValueWithoutNotify(m_QueryBuilder.wordText); Emit(SearchEvent.BuilderRefreshed); } void ISearchField.Focus() { m_SearchField.Focus(); } VisualElement ISearchField.GetTextElement() { return m_TextField; } void INotifyValueChanged<string>.SetValueWithoutNotify(string newValue) { if (m_QueryBuilder == null || (m_QueryBuilder.hasOwnText && string.Equals(newValue, m_QueryBuilder.searchText, StringComparison.Ordinal))) return; m_QueryBuilder.searchText = newValue; DeferRefreshBuilder(); } } }
UnityCsReference/Modules/QuickSearch/Editor/UITK/SearchQueryBuilderView.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/UITK/SearchQueryBuilderView.cs", "repo_id": "UnityCsReference", "token_count": 3038 }
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 System.Threading; namespace UnityEditor.Search { class RetriableOperation<T> where T : Exception { public const uint DefaultRetryCount = 5; public static readonly TimeSpan DefaultSleepTimeMs = TimeSpan.FromMilliseconds(5); Action m_Operation; uint m_RetryCount; TimeSpan m_SleepTime; public RetriableOperation(Action operation, uint retryCount, TimeSpan sleepTime) { m_Operation = operation ?? throw new ArgumentNullException(nameof(operation)); m_RetryCount = retryCount; m_SleepTime = sleepTime; } public void Execute() { var retry = m_RetryCount; do { try { m_Operation(); break; } catch (T) { if (retry <= 0) throw; if (m_SleepTime > TimeSpan.Zero) Thread.Sleep(m_SleepTime); } } while (retry-- > 0); } public static void Execute(Action operation, uint retryCount, TimeSpan sleepTimeMs) { var retriableOperation = new RetriableOperation<T>(operation, retryCount, sleepTimeMs); retriableOperation.Execute(); } public static void Execute(Action operation) { Execute(operation, DefaultRetryCount, DefaultSleepTimeMs); } } }
UnityCsReference/Modules/QuickSearch/Editor/Utilities/RetriableOperation.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/Utilities/RetriableOperation.cs", "repo_id": "UnityCsReference", "token_count": 837 }
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.Collections.Generic; using JetBrains.Annotations; using UnityEngine; namespace UnityEditor.SceneTemplate { class SceneTemplatePreferences { const string k_PreferencesPath = "Preferences/SceneTemplates"; const string k_PreferencesKeyPrefix = "SceneTemplatePreferences."; internal enum NewDefaultSceneOverride { SceneTemplate, DefaultBuiltin } public NewDefaultSceneOverride newDefaultSceneOverride; static SceneTemplatePreferences s_Instance; [UsedImplicitly, SettingsProvider] static SettingsProvider CreateSettings() { return new SettingsProvider(k_PreferencesPath, SettingsScope.User) { keywords = L10n.Tr(new[] { "unity", "editor", "scene", "clone", "template" }), activateHandler = (text, rootElement) => { }, label = L10n.Tr("Scene Template"), guiHandler = OnGUIHandler }; } static void OnGUIHandler(string obj) { var prefs = Get(); using (new SettingsWindow.GUIScope()) { EditorGUI.BeginChangeCheck(); prefs.newDefaultSceneOverride = (NewDefaultSceneOverride)EditorGUILayout.EnumPopup(L10n.TextContent("Default Scene", "Which scene to open when no other scenes were previously opened."), prefs.newDefaultSceneOverride); if (EditorGUI.EndChangeCheck()) { Save(); } } } public static SceneTemplatePreferences Get() { if (s_Instance == null) { s_Instance = new SceneTemplatePreferences(); s_Instance.newDefaultSceneOverride = (NewDefaultSceneOverride)EditorPrefs.GetInt(GetPreferencesKey("newDefaultSceneOverride"), (int)NewDefaultSceneOverride.DefaultBuiltin); } return s_Instance; } public static void Save(SceneTemplatePreferences prefs = null) { prefs ??= Get(); EditorPrefs.SetInt(GetPreferencesKey("newDefaultSceneOverride"), (int)prefs.newDefaultSceneOverride); } internal static void ResetDefaults() { var prefs = Get(); prefs.newDefaultSceneOverride = NewDefaultSceneOverride.DefaultBuiltin; Save(); } static string GetPreferencesKey(string name) { return $"{k_PreferencesKeyPrefix}{name}"; } } }
UnityCsReference/Modules/SceneTemplateEditor/SceneTemplatePreferences.cs/0
{ "file_path": "UnityCsReference/Modules/SceneTemplateEditor/SceneTemplatePreferences.cs", "repo_id": "UnityCsReference", "token_count": 1220 }
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 System.Collections.Generic; using UnityEngine.Bindings; namespace UnityEditor.ShaderFoundry { using LinkAccessorKind = BlockLinkOverrideInternal.LinkAccessorInternal.Kind; [NativeHeader("Modules/ShaderFoundry/Public/BlockLinkOverride.h")] internal struct BlockLinkOverrideInternal : IInternalType<BlockLinkOverrideInternal> { internal struct LinkAccessorInternal : IInternalType<LinkAccessorInternal> { internal enum Kind : ushort { // THIS ENUM MUST BE KEPT IN SYNC WITH THE ENUM IN BlockLinkOverride.h Invalid = 0, MemberAccess = 1, ArrayAccess = 2, } internal Kind m_Kind; internal FoundryHandle m_AccessorHandle; internal extern static LinkAccessorInternal Invalid(); internal extern bool IsValid(); // IInternalType LinkAccessorInternal IInternalType<LinkAccessorInternal>.ConstructInvalid() => Invalid(); } internal struct LinkElementInternal : IInternalType<LinkElementInternal> { internal FoundryHandle m_TypeHandle; // ShaderType internal FoundryHandle m_CastTypeHandle; // ShaderType internal FoundryHandle m_NamespaceHandle; // string internal FoundryHandle m_NameHandle; // string internal FoundryHandle m_ConstantExpressionHandle; // string internal FoundryHandle m_AccessorListHandle; // List<LinkAccessor> internal extern static LinkElementInternal Invalid(); internal extern bool IsValid(); // IInternalType LinkElementInternal IInternalType<LinkElementInternal>.ConstructInvalid() => Invalid(); } internal FoundryHandle m_InterfaceFieldHandle; internal FoundryHandle m_ArgumentHandle; internal extern static BlockLinkOverrideInternal Invalid(); internal extern bool IsValid(); // IInternalType BlockLinkOverrideInternal IInternalType<BlockLinkOverrideInternal>.ConstructInvalid() => Invalid(); } [FoundryAPI] internal readonly struct BlockLinkOverride : IEquatable<BlockLinkOverride>, IPublicType<BlockLinkOverride> { // data members readonly ShaderContainer container; readonly internal FoundryHandle handle; readonly BlockLinkOverrideInternal linkOverride; // IPublicType ShaderContainer IPublicType.Container => Container; bool IPublicType.IsValid => IsValid; FoundryHandle IPublicType.Handle => handle; BlockLinkOverride IPublicType<BlockLinkOverride>.ConstructFromHandle(ShaderContainer container, FoundryHandle handle) => new BlockLinkOverride(container, handle); public ShaderContainer Container => container; public bool IsValid => (container != null && handle.IsValid && linkOverride.IsValid()); internal readonly struct LinkAccessor : IEquatable<LinkAccessor>, IPublicType<LinkAccessor> { // data members readonly ShaderContainer container; readonly internal FoundryHandle handle; readonly BlockLinkOverrideInternal.LinkAccessorInternal accessor; // IPublicType ShaderContainer IPublicType.Container => Container; bool IPublicType.IsValid => IsValid; FoundryHandle IPublicType.Handle => handle; LinkAccessor IPublicType<LinkAccessor>.ConstructFromHandle(ShaderContainer container, FoundryHandle handle) => new LinkAccessor(container, handle); public ShaderContainer Container => container; public bool IsValid => (container != null && handle.IsValid && accessor.IsValid()); public bool IsMemberAccessor => IsKind(LinkAccessorKind.MemberAccess); public bool IsArrayAccessor => IsKind(LinkAccessorKind.ArrayAccess); public string MemberAccessor => GetAccessor(LinkAccessorKind.MemberAccess); public string ArrayAccessor => GetAccessor(LinkAccessorKind.ArrayAccess); bool IsKind(BlockLinkOverrideInternal.LinkAccessorInternal.Kind expectedKind) { return accessor.m_Kind == expectedKind; } string GetAccessor(BlockLinkOverrideInternal.LinkAccessorInternal.Kind expectedKind) { if (IsKind(expectedKind)) return container?.GetString(accessor.m_AccessorHandle); return string.Empty; } // private internal LinkAccessor(ShaderContainer container, FoundryHandle handle) { this.container = container; this.handle = handle; ShaderContainer.Get(container, handle, out accessor); } public static LinkAccessor Invalid => new LinkAccessor(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 LinkAccessor other && this.Equals(other); public bool Equals(LinkAccessor other) => EqualityChecks.ReferenceEquals(this.handle, this.container, other.handle, other.container); public override int GetHashCode() => (container, handle).GetHashCode(); public static bool operator==(LinkAccessor lhs, LinkAccessor rhs) => lhs.Equals(rhs); public static bool operator!=(LinkAccessor lhs, LinkAccessor rhs) => !lhs.Equals(rhs); static LinkAccessor BuildAccessor(ShaderContainer container, LinkAccessorKind kind, FoundryHandle accessorHandle) { var linkAccessorInternal = new BlockLinkOverrideInternal.LinkAccessorInternal(); linkAccessorInternal.m_Kind = kind; linkAccessorInternal.m_AccessorHandle = accessorHandle; var returnTypeHandle = container.Add(linkAccessorInternal); return new LinkAccessor(container, returnTypeHandle); } public class MemberAccessBuilder { ShaderContainer container; public string memberAccessor; public ShaderContainer Container => container; public MemberAccessBuilder(ShaderContainer container, string memberAccessor) { this.container = container; this.memberAccessor = memberAccessor; } public LinkAccessor Build() => BuildAccessor(container, LinkAccessorKind.MemberAccess, container.AddString(memberAccessor)); } public class ArrayAccessBuilder { ShaderContainer container; public string arrayAccessor; public ShaderContainer Container => container; public ArrayAccessBuilder(ShaderContainer container, string arrayAccessor) { this.container = container; this.arrayAccessor = arrayAccessor; } public LinkAccessor Build() => BuildAccessor(container, LinkAccessorKind.ArrayAccess, container.AddString(arrayAccessor)); } } internal readonly struct LinkElement : IEquatable<LinkElement>, IPublicType<LinkElement> { // data members readonly ShaderContainer container; readonly internal FoundryHandle handle; readonly BlockLinkOverrideInternal.LinkElementInternal element; // IPublicType ShaderContainer IPublicType.Container => Container; bool IPublicType.IsValid => IsValid; FoundryHandle IPublicType.Handle => handle; LinkElement IPublicType<LinkElement>.ConstructFromHandle(ShaderContainer container, FoundryHandle handle) => new LinkElement(container, handle); public ShaderContainer Container => container; public bool IsValid => (container != null && handle.IsValid && element.IsValid()); public ShaderType Type => new ShaderType(container, element.m_TypeHandle); public ShaderType CastType => new ShaderType(container, element.m_CastTypeHandle); public string Namespace => container?.GetString(element.m_NamespaceHandle) ?? string.Empty; public string Name => container?.GetString(element.m_NameHandle) ?? string.Empty; public string ConstantExpression => container?.GetString(element.m_ConstantExpressionHandle) ?? string.Empty; public IEnumerable<LinkAccessor> Accessors => element.m_AccessorListHandle.AsListEnumerable<LinkAccessor>(Container, (container, handle) => new LinkAccessor(container, handle)); // private internal LinkElement(ShaderContainer container, FoundryHandle handle) { this.container = container; this.handle = handle; ShaderContainer.Get(container, handle, out element); } public static LinkElement Invalid => new LinkElement(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 LinkElement other && this.Equals(other); public bool Equals(LinkElement other) => EqualityChecks.ReferenceEquals(this.handle, this.container, other.handle, other.container); public override int GetHashCode() => (container, handle).GetHashCode(); public static bool operator==(LinkElement lhs, LinkElement rhs) => lhs.Equals(rhs); public static bool operator!=(LinkElement lhs, LinkElement rhs) => !lhs.Equals(rhs); public class Builder { ShaderContainer container; public ShaderType type { get; set; } = ShaderType.Invalid; public ShaderType castType { get; set; } = ShaderType.Invalid; public string namespaceName { get; set; } public string name { get; set; } List<LinkAccessor> m_Accessors; public ShaderContainer Container => container; public Builder(ShaderContainer container, string name) { this.container = container; this.name = name; } public void AddAccessor(LinkAccessor linkAccessor) { if (m_Accessors == null) m_Accessors = new List<LinkAccessor>(); m_Accessors.Add(linkAccessor); } public LinkElement Build() { var linkElementInternal = new BlockLinkOverrideInternal.LinkElementInternal(); linkElementInternal.m_TypeHandle = type.handle; linkElementInternal.m_CastTypeHandle = castType.handle; linkElementInternal.m_NamespaceHandle = container.AddString(namespaceName); linkElementInternal.m_NameHandle = container.AddString(name); linkElementInternal.m_AccessorListHandle = HandleListInternal.Build(container, m_Accessors, (a) => (a.handle)); var returnTypeHandle = container.Add(linkElementInternal); return new LinkElement(container, returnTypeHandle); } } public class ConstantExpressionBuilder { ShaderContainer container; public string constantExpression { get; set; } public ShaderContainer Container => container; public ConstantExpressionBuilder(ShaderContainer container, string constantExpression) { this.container = container; this.constantExpression = constantExpression; } public LinkElement Build() { var linkElementInternal = new BlockLinkOverrideInternal.LinkElementInternal(); linkElementInternal.m_ConstantExpressionHandle = container.AddString(constantExpression); var returnTypeHandle = container.Add(linkElementInternal); return new LinkElement(container, returnTypeHandle); } } } // The interface field is applied to the block sequence element (e.g. block input or output). public LinkElement InterfaceField => new LinkElement(container, linkOverride.m_InterfaceFieldHandle); // The argument is applied to the block sequence (e.g. the input or output being matched against). public LinkElement Argument => new LinkElement(container, linkOverride.m_ArgumentHandle); // private internal BlockLinkOverride(ShaderContainer container, FoundryHandle handle) { this.container = container; this.handle = handle; ShaderContainer.Get(container, handle, out linkOverride); } public static BlockLinkOverride Invalid => new BlockLinkOverride(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 BlockLinkOverride other && this.Equals(other); public bool Equals(BlockLinkOverride other) => EqualityChecks.ReferenceEquals(this.handle, this.container, other.handle, other.container); public override int GetHashCode() => (container, handle).GetHashCode(); public static bool operator==(BlockLinkOverride lhs, BlockLinkOverride rhs) => lhs.Equals(rhs); public static bool operator!=(BlockLinkOverride lhs, BlockLinkOverride rhs) => !lhs.Equals(rhs); public class Builder { ShaderContainer container; internal LinkElement interfaceField; internal LinkElement argument; public ShaderContainer Container => container; public Builder(ShaderContainer container, LinkElement interfaceField, LinkElement argument) { this.container = container; this.interfaceField = interfaceField; this.argument = argument; } public BlockLinkOverride Build() { var linkOverrideInternal = new BlockLinkOverrideInternal(); linkOverrideInternal.m_InterfaceFieldHandle = interfaceField.handle; linkOverrideInternal.m_ArgumentHandle = argument.handle; var returnTypeHandle = container.Add(linkOverrideInternal); return new BlockLinkOverride(container, returnTypeHandle); } } } }
UnityCsReference/Modules/ShaderFoundry/ScriptBindings/BlockLinkOverride.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/ShaderFoundry/ScriptBindings/BlockLinkOverride.bindings.cs", "repo_id": "UnityCsReference", "token_count": 6046 }
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 UnityEngine.Bindings; namespace UnityEditor.ShaderFoundry { [NativeHeader("Modules/ShaderFoundry/Public/FunctionParameter.h")] internal struct FunctionParameterInternal : IInternalType<FunctionParameterInternal> { // these enums must match the declarations in FunctionParameter.h internal enum Flags { kFlagsInput = 1 << 0, kFlagsOutput = 1 << 1, kFlagsInputOutput = 3, }; internal FoundryHandle m_NameHandle; internal FoundryHandle m_TypeHandle; internal FoundryHandle m_AttributeListHandle; internal UInt32 m_Flags; // TODO no need to make this extern, can duplicate it here internal static extern FunctionParameterInternal Invalid(); internal bool IsValid => (m_NameHandle.IsValid && (m_Flags != 0)); internal extern string GetName(ShaderContainer container); internal extern static bool ValueEquals(ShaderContainer aContainer, FoundryHandle aHandle, ShaderContainer bContainer, FoundryHandle bHandle); // IInternalType FunctionParameterInternal IInternalType<FunctionParameterInternal>.ConstructInvalid() => Invalid(); } [FoundryAPI] internal readonly struct FunctionParameter : IEquatable<FunctionParameter>, IPublicType<FunctionParameter> { // data members readonly ShaderContainer container; internal readonly FoundryHandle handle; readonly FunctionParameterInternal param; // IPublicType ShaderContainer IPublicType.Container => Container; bool IPublicType.IsValid => IsValid; FoundryHandle IPublicType.Handle => handle; FunctionParameter IPublicType<FunctionParameter>.ConstructFromHandle(ShaderContainer container, FoundryHandle handle) => new FunctionParameter(container, handle); // public API public ShaderContainer Container => container; public bool IsValid => (container != null) && handle.IsValid && (param.IsValid); public string Name => param.GetName(container); public ShaderType Type => new ShaderType(container, param.m_TypeHandle); public IEnumerable<ShaderAttribute> Attributes => param.m_AttributeListHandle.AsListEnumerable<ShaderAttribute>(container, (container, handle) => (new ShaderAttribute(container, handle))); public bool IsInput => ((param.m_Flags & (UInt32)FunctionParameterInternal.Flags.kFlagsInput) != 0); public bool IsOutput => ((param.m_Flags & (UInt32)FunctionParameterInternal.Flags.kFlagsOutput) != 0); internal FunctionParameterInternal.Flags Flags => (FunctionParameterInternal.Flags)param.m_Flags; internal bool HasFlag(FunctionParameterInternal.Flags flags) => Flags.HasFlag(flags); // private internal FunctionParameter(ShaderContainer container, FoundryHandle handle) { this.container = container; this.handle = handle; ShaderContainer.Get(container, handle, out param); } public static FunctionParameter Invalid => new FunctionParameter(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 FunctionParameter other && this.Equals(other); public bool Equals(FunctionParameter other) => EqualityChecks.ReferenceEquals(this.handle, this.container, other.handle, other.container); public override int GetHashCode() => (container, handle).GetHashCode(); public static bool operator==(FunctionParameter lhs, FunctionParameter rhs) => lhs.Equals(rhs); public static bool operator!=(FunctionParameter lhs, FunctionParameter rhs) => !lhs.Equals(rhs); public bool ValueEquals(in FunctionParameter other) { return FunctionParameterInternal.ValueEquals(container, handle, other.container, other.handle); } public class Builder { ShaderContainer container; internal string name; internal ShaderType type; internal List<ShaderAttribute> attributes; internal UInt32 flags; public ShaderContainer Container => container; public Builder(ShaderContainer container, string name, ShaderType type, bool input, bool output) { this.container = container; this.name = name; this.type = type; this.flags = (input ? (UInt32)FunctionParameterInternal.Flags.kFlagsInput : 0) | (output ? (UInt32)FunctionParameterInternal.Flags.kFlagsOutput : 0); } internal Builder(ShaderContainer container, string name, ShaderType type, UInt32 flags) { this.container = container; this.name = name; this.type = type; this.flags = flags; } public void AddAttribute(ShaderAttribute attribute) { if (attributes == null) attributes = new List<ShaderAttribute>(); attributes.Add(attribute); } public FunctionParameter Build() { var functionParamInternal = new FunctionParameterInternal(); functionParamInternal.m_NameHandle = container.AddString(name); functionParamInternal.m_TypeHandle = type.handle; functionParamInternal.m_AttributeListHandle = HandleListInternal.Build(container, attributes, (a) => (a.handle)); functionParamInternal.m_Flags = flags; FoundryHandle returnHandle = container.Add(functionParamInternal); return new FunctionParameter(Container, returnHandle); } } } }
UnityCsReference/Modules/ShaderFoundry/ScriptBindings/FunctionParameter.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/ShaderFoundry/ScriptBindings/FunctionParameter.bindings.cs", "repo_id": "UnityCsReference", "token_count": 2238 }
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; using System.Collections.Generic; using UnityEngine.Bindings; namespace UnityEditor.ShaderFoundry { [NativeHeader("Modules/ShaderFoundry/Public/ShaderAttributeParameter.h")] internal struct ShaderAttributeParameterInternal : IInternalType<ShaderAttributeParameterInternal> { internal FoundryHandle m_NameHandle; internal FoundryHandle m_ValueHandle; internal extern static ShaderAttributeParameterInternal Invalid(); internal extern bool IsValid(); internal extern string GetName(ShaderContainer container); internal extern string GetValue(ShaderContainer container); internal extern bool ValueIsString(ShaderContainer container); internal extern bool ValueIsArray(ShaderContainer container); internal extern static bool ValueEquals(ShaderContainer aContainer, FoundryHandle aHandle, ShaderContainer bContainer, FoundryHandle bHandle); // IInternalType ShaderAttributeParameterInternal IInternalType<ShaderAttributeParameterInternal>.ConstructInvalid() => Invalid(); } [FoundryAPI] internal readonly struct ShaderAttributeParameter : IEquatable<ShaderAttributeParameter>, IPublicType<ShaderAttributeParameter> { readonly ShaderContainer container; readonly internal FoundryHandle handle; readonly ShaderAttributeParameterInternal param; // IPublicType ShaderContainer IPublicType.Container => Container; bool IPublicType.IsValid => IsValid; FoundryHandle IPublicType.Handle => handle; ShaderAttributeParameter IPublicType<ShaderAttributeParameter>.ConstructFromHandle(ShaderContainer container, FoundryHandle handle) => new ShaderAttributeParameter(container, handle); internal ShaderAttributeParameter(ShaderContainer container, FoundryHandle handle) { this.container = container; this.handle = handle; ShaderContainer.Get(container, handle, out param); } public ShaderContainer Container => container; public bool IsValid => (container != null) && (param.IsValid()); public string Name => param.GetName(container); public string Value { get { if (container == null || !ValueIsString) throw new InvalidOperationException("Invalid call to 'ShaderAttributeParameter.Value'. Value is not a string. Check ValueIsString before calling."); return param.GetValue(container); } } public IEnumerable<ShaderAttributeParameter> Values { get { if (container == null || !ValueIsArray) throw new InvalidOperationException("Invalid call to 'ShaderAttributeParameter.Values'. Values is not a List. Check ValueIsArray before calling."); var handleType = container.GetDataTypeFromHandle(param.m_ValueHandle); var localContainer = Container; var list = new HandleListInternal(param.m_ValueHandle); return list.Select<ShaderAttributeParameter>(localContainer, (handle) => (new ShaderAttributeParameter(localContainer, handle))); } } public bool ValueIsString => param.ValueIsString(container); // The value is an array of sub attributes. This is equivalent to "param = [value, value]". public bool ValueIsArray => param.ValueIsArray(container); public static ShaderAttributeParameter Invalid => new ShaderAttributeParameter(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 ShaderAttributeParameter other && this.Equals(other); public bool Equals(ShaderAttributeParameter other) => EqualityChecks.ReferenceEquals(this.handle, this.container, other.handle, other.container); public override int GetHashCode() => (container, handle).GetHashCode(); public static bool operator==(ShaderAttributeParameter lhs, ShaderAttributeParameter rhs) => lhs.Equals(rhs); public static bool operator!=(ShaderAttributeParameter lhs, ShaderAttributeParameter rhs) => !lhs.Equals(rhs); public bool ValueEquals(in ShaderAttributeParameter other) { return ShaderAttributeParameterInternal.ValueEquals(container, handle, other.container, other.handle); } public class Builder { ShaderContainer container; internal string m_Name; internal string m_Value; internal List<ShaderAttributeParameter> m_Values; public ShaderContainer Container => container; public Builder(ShaderContainer container, string name, string value) { this.container = container; m_Name = name; m_Value = value; m_Values = null; } public Builder(ShaderContainer container, string name, List<ShaderAttributeParameter> values) { this.container = container; m_Name = name; m_Value = null; m_Values = values; } public ShaderAttributeParameter Build() { var paramInternal = new ShaderAttributeParameterInternal(); paramInternal.m_NameHandle = container.AddString(m_Name); if (m_Values == null) paramInternal.m_ValueHandle = container.AddString(m_Value); else paramInternal.m_ValueHandle = HandleListInternal.Build(container, m_Values, (v) => v.handle); var returnHandle = container.Add(paramInternal); return new ShaderAttributeParameter(container, returnHandle); } } } }
UnityCsReference/Modules/ShaderFoundry/ScriptBindings/ShaderAttributeParameter.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/ShaderFoundry/ScriptBindings/ShaderAttributeParameter.bindings.cs", "repo_id": "UnityCsReference", "token_count": 2293 }
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.Runtime.InteropServices; using UnityEngine.Scripting; using UnityEngine.Bindings; using System.Globalization; namespace UnityEngine { // This function exists because UnityEngine.dll is compiled against .NET 3.5, but .NET Core removes all the overloads // except this one. So to prevent our code compiling against the (string, object, object) version and use the params // version instead, we reroute through this. // TODO: remove this when the dependency goes away. [VisibleToOtherModules] internal sealed partial class UnityString { public static string Format(string fmt, params object[] args) { return String.Format(CultureInfo.InvariantCulture.NumberFormat, fmt, args); } } }
UnityCsReference/Modules/SharedInternals/UnityString.cs/0
{ "file_path": "UnityCsReference/Modules/SharedInternals/UnityString.cs", "repo_id": "UnityCsReference", "token_count": 287 }
445
// Unity C# 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 System.Collections.Generic; using UnityEngine; namespace UnityEditor.ShortcutManagement { [Serializable] public struct KeyCombination : IEquatable<KeyCombination> { [SerializeField] internal KeyCode m_KeyCode; [SerializeField] ShortcutModifiers m_Modifiers; // Linux may send key masks and they will be greater than the shortcut index length. // Check implemented at getter and not at assignment because binding validator // should be able to work out what the original key code was by accessing internal field. public KeyCode keyCode => (int)m_KeyCode < Directory.MaxIndexedEntries ? m_KeyCode : KeyCode.None; public ShortcutModifiers modifiers => m_Modifiers; static Dictionary<KeyCode, string> s_KeyCodeToMenuItemKeyCodeString = new Dictionary<KeyCode, string>() { { KeyCode.LeftArrow, "LEFT" }, { KeyCode.UpArrow, "UP" }, { KeyCode.RightArrow, "RIGHT" }, { KeyCode.DownArrow, "DOWN" }, { KeyCode.PageDown, "PGDN" }, { KeyCode.PageUp, "PGUP" }, { KeyCode.Home, "HOME" }, { KeyCode.Insert, "INS" }, { KeyCode.Delete, "DEL" }, { KeyCode.End, "END" }, { KeyCode.Tab, "TAB" }, { KeyCode.Space, "SPACE"}, { KeyCode.Backspace, "BACKSPACE"}, // UUM-40161 // Even though ShortcutManager doesn't allow enter key bindings, // we must have this conversion to be able to handle menu shortcut // string which can have enter key bindings. { KeyCode.Return, "ENTER" }, { KeyCode.F1, "F1" }, { KeyCode.F2, "F2" }, { KeyCode.F3, "F3" }, { KeyCode.F4, "F4" }, { KeyCode.F5, "F5" }, { KeyCode.F6, "F6" }, { KeyCode.F7, "F7" }, { KeyCode.F8, "F8" }, { KeyCode.F9, "F9" }, { KeyCode.F10, "F10" }, { KeyCode.F11, "F11" }, { KeyCode.F12, "F12" }, { KeyCode.Mouse0, "M0" }, { KeyCode.Mouse1, "M1" }, { KeyCode.Mouse2, "M2" }, { KeyCode.Mouse3, "M3" }, { KeyCode.Mouse4, "M4" }, { KeyCode.Mouse5, "M5" }, { KeyCode.Mouse6, "M6" }, }; static Dictionary<string, KeyCode> s_MenuItemKeyCodeStringToKeyCode; static KeyCombination() { // Populate s_MenuItemKeyCodeStringToKeyCode by reversing s_KeyCodeToMenuItemKeyCodeString s_MenuItemKeyCodeStringToKeyCode = new Dictionary<string, KeyCode>(s_KeyCodeToMenuItemKeyCodeString.Count); foreach (var entry in s_KeyCodeToMenuItemKeyCodeString) { s_MenuItemKeyCodeStringToKeyCode.Add(entry.Value, entry.Key); } } public KeyCombination(KeyCode keyCode, ShortcutModifiers shortcutModifiers = ShortcutModifiers.None) { m_KeyCode = keyCode; m_Modifiers = shortcutModifiers; } internal static KeyCombination FromInput(Event evt) { return FromKeyboardInput(evt.keyCode, evt.modifiers); } internal static KeyCombination FromKeyboardInput(Event evt) { return FromKeyboardInput(evt.keyCode, evt.modifiers); } internal static KeyCombination FromKeyboardInput(KeyCode keyCode, EventModifiers modifiers) { return new KeyCombination(keyCode, ConvertEventModifiersToShortcutModifiers(modifiers, false)); } internal static KeyCombination FromKeyboardInputAndAddEventModifiers(KeyCombination combination, EventModifiers modifiers) { return new KeyCombination(combination.keyCode, combination.modifiers | ConvertEventModifiersToShortcutModifiers(modifiers, false)); } internal static KeyCombination FromKeyboardInputAndRemoveEventModifiers(KeyCombination combination, EventModifiers modifiers) { var convertedEventModifier = ConvertEventModifiersToShortcutModifiers(modifiers, false); var newModifiers = combination.modifiers & ~convertedEventModifier; return new KeyCombination(combination.keyCode, newModifiers); } internal static KeyCombination FromPrefKeyKeyboardEvent(Event evt) { return new KeyCombination(evt.keyCode, ConvertEventModifiersToShortcutModifiers(evt.modifiers, true)); } static ShortcutModifiers ConvertEventModifiersToShortcutModifiers(EventModifiers eventModifiers, bool coalesceCommandAndControl) { ShortcutModifiers modifiers = ShortcutModifiers.None; if ((eventModifiers & EventModifiers.Alt) != 0) modifiers |= ShortcutModifiers.Alt; if ((eventModifiers & EventModifiers.Shift) != 0) modifiers |= ShortcutModifiers.Shift; if (coalesceCommandAndControl) { if ((eventModifiers & (EventModifiers.Command | EventModifiers.Control)) != 0) modifiers |= ShortcutModifiers.Action; } else { if (Application.platform == RuntimePlatform.OSXEditor) { if ((eventModifiers & EventModifiers.Command) != 0) modifiers |= ShortcutModifiers.Action; if ((eventModifiers & EventModifiers.Control) != 0) modifiers |= ShortcutModifiers.Control; } else if ((eventModifiers & EventModifiers.Control) != 0) modifiers |= ShortcutModifiers.Action; } return modifiers; } public bool alt => (modifiers & ShortcutModifiers.Alt) == ShortcutModifiers.Alt; public bool action => (modifiers & ShortcutModifiers.Action) == ShortcutModifiers.Action; public bool shift => (modifiers & ShortcutModifiers.Shift) == ShortcutModifiers.Shift; public bool control => (modifiers & ShortcutModifiers.Control) == ShortcutModifiers.Control; internal Event ToKeyboardEvent() { Event e = new Event(); e.type = EventType.KeyDown; e.alt = alt; e.command = action && Application.platform == RuntimePlatform.OSXEditor; e.control = action && Application.platform != RuntimePlatform.OSXEditor || control; e.shift = shift; e.keyCode = keyCode; return e; } internal static string SequenceToString(IEnumerable<KeyCombination> keyCombinations) { if (!keyCombinations.Any()) return ""; var builder = new StringBuilder(); builder.Append(keyCombinations.First()); foreach (var keyCombination in keyCombinations.Skip(1)) { builder.Append(", "); builder.Append(keyCombination); } return builder.ToString(); } public override string ToString() { var builder = new StringBuilder(); VisualizeModifiers(modifiers, builder); VisualizeKeyCode(keyCode, builder); return builder.ToString(); } internal string ToMenuShortcutString() { if (keyCode == KeyCode.None) return string.Empty; var builder = new StringBuilder(); if ((modifiers & ShortcutModifiers.Alt) != 0) builder.Append("&"); if ((modifiers & ShortcutModifiers.Shift) != 0) builder.Append("#"); if ((modifiers & ShortcutModifiers.Action) != 0) builder.Append("%"); if ((modifiers & ShortcutModifiers.Control) != 0) builder.Append("^"); if (modifiers == ShortcutModifiers.None) builder.Append("_"); KeyCodeToMenuItemKeyCodeString(keyCode, builder); return builder.ToString(); } static void KeyCodeToMenuItemKeyCodeString(KeyCode keyCode, StringBuilder builder) { string keyCodeString; if (s_KeyCodeToMenuItemKeyCodeString.TryGetValue(keyCode, out keyCodeString)) { builder.Append(keyCodeString); return; } var character = (char)keyCode; if (character >= ' ' && character <= '@' || character >= '[' && character <= '~') builder.Append(character.ToString()); } internal static bool TryParseMenuItemBindingString(string menuItemBindingString, out KeyCombination keyCombination) { if (string.IsNullOrEmpty(menuItemBindingString)) { keyCombination = default(KeyCombination); return false; } var modifiers = ShortcutModifiers.None; var startIndex = 0; var shortcutStarted = false; bool found; do { found = true; if (startIndex >= menuItemBindingString.Length) break; switch (menuItemBindingString[startIndex]) { case '&': modifiers |= ShortcutModifiers.Alt; startIndex++; break; case '%': modifiers |= ShortcutModifiers.Action; startIndex++; break; case '#': modifiers |= ShortcutModifiers.Shift; startIndex++; break; case '^': modifiers |= ShortcutModifiers.Control; startIndex++; break; case '_': startIndex++; break; default: found = false; break; } shortcutStarted |= found; } while (found); var keyCodeString = menuItemBindingString.Substring(startIndex, menuItemBindingString.Length - startIndex); KeyCode keyCode; ShortcutModifiers additionalModifiers; if (!shortcutStarted || !TryParseMenuItemKeyCodeString(keyCodeString, out keyCode, out additionalModifiers)) { keyCombination = default(KeyCombination); return false; } modifiers |= additionalModifiers; keyCombination = new KeyCombination(keyCode, modifiers); return true; } static bool TryParseMenuItemKeyCodeString(string keyCodeString, out KeyCode keyCode, out ShortcutModifiers additionalModifiers) { keyCode = default(KeyCode); additionalModifiers = ShortcutModifiers.None; if (string.IsNullOrEmpty(keyCodeString)) return false; if (s_MenuItemKeyCodeStringToKeyCode.TryGetValue(keyCodeString.ToUpperInvariant(), out keyCode)) return true; if (keyCodeString.Length != 1) return false; var character = char.ToLowerInvariant(keyCodeString[0]); keyCode = (KeyCode)character; return Enum.IsDefined(typeof(KeyCode), keyCode); } internal static string SequenceToMenuString(IEnumerable<KeyCombination> keyCombinations) { if (!keyCombinations.Any()) return ""; //TODO: once we start supporting chords we need to figure out how to represent that for menus. return keyCombinations.Single().ToMenuShortcutString(); } static void VisualizeModifiers(ShortcutModifiers modifiers, StringBuilder builder) { if (Application.platform == RuntimePlatform.OSXEditor) { if ((modifiers & ShortcutModifiers.Alt) != 0) builder.Append("⌥"); if ((modifiers & ShortcutModifiers.Shift) != 0) builder.Append("⇧"); if ((modifiers & ShortcutModifiers.Action) != 0) builder.Append("⌘"); if ((modifiers & ShortcutModifiers.Control) != 0) builder.Append("^"); } else { if ((modifiers & ShortcutModifiers.Action | modifiers & ShortcutModifiers.Control) != 0) builder.Append("Ctrl+"); if ((modifiers & ShortcutModifiers.Alt) != 0) builder.Append("Alt+"); if ((modifiers & ShortcutModifiers.Shift) != 0) builder.Append("Shift+"); } } static void VisualizeKeyCode(KeyCode keyCode, StringBuilder builder) { if (!TryFormatKeycode(keyCode, builder)) builder.Append(keyCode.ToString()); } static Dictionary<KeyCode, string> s_KeyCodeNamesMacOS = new Dictionary<KeyCode, string> { { KeyCode.Backspace, "⌫" }, { KeyCode.Tab, "⇥" }, { KeyCode.Return, "↩" }, { KeyCode.Escape, "⎋" }, { KeyCode.Delete, "⌦" }, { KeyCode.UpArrow, "↑" }, { KeyCode.DownArrow, "↓" }, { KeyCode.RightArrow, "→" }, { KeyCode.LeftArrow, "←" }, { KeyCode.Home, "↖" }, { KeyCode.End, "↘" }, { KeyCode.PageUp, "⇞" }, { KeyCode.PageDown, "⇟" }, }; static Dictionary<KeyCode, string> s_KeyCodeNamesNotMacOS = new Dictionary<KeyCode, string> { { KeyCode.Return, "Enter" }, { KeyCode.Escape, "Esc" }, { KeyCode.Delete, "Del" }, { KeyCode.UpArrow, "Up Arrow" }, { KeyCode.DownArrow, "Down Arrow" }, { KeyCode.RightArrow, "Right Arrow" }, { KeyCode.LeftArrow, "Left Arrow" }, { KeyCode.PageUp, "Page Up" }, { KeyCode.PageDown, "Page Down" }, }; static Dictionary<KeyCode, string> s_KeyCodeNamesCommon = new Dictionary<KeyCode, string> { { KeyCode.Exclaim, "!" }, { KeyCode.DoubleQuote, "\"" }, { KeyCode.Hash, "#" }, { KeyCode.Dollar, "$" }, { KeyCode.Percent, "%" }, { KeyCode.Ampersand, "&" }, { KeyCode.Quote, "'" }, { KeyCode.LeftParen, "(" }, { KeyCode.RightParen, ")" }, { KeyCode.Asterisk, "*" }, { KeyCode.Plus, "+" }, { KeyCode.Comma, "," }, { KeyCode.Minus, "-" }, { KeyCode.Period, "." }, { KeyCode.Slash, "/" }, { KeyCode.Alpha0, "0" }, { KeyCode.Alpha1, "1" }, { KeyCode.Alpha2, "2" }, { KeyCode.Alpha3, "3" }, { KeyCode.Alpha4, "4" }, { KeyCode.Alpha5, "5" }, { KeyCode.Alpha6, "6" }, { KeyCode.Alpha7, "7" }, { KeyCode.Alpha8, "8" }, { KeyCode.Alpha9, "9" }, { KeyCode.Colon, ":" }, { KeyCode.Semicolon, ";" }, { KeyCode.Less, "<" }, { KeyCode.Equals, "=" }, { KeyCode.Greater, ">" }, { KeyCode.Question, "?" }, { KeyCode.At, "@" }, { KeyCode.LeftBracket, "[" }, { KeyCode.Backslash, "\\" }, { KeyCode.RightBracket, "]" }, { KeyCode.Caret, "^" }, { KeyCode.Underscore, "_" }, { KeyCode.BackQuote, "`" }, { KeyCode.LeftCurlyBracket, "{" }, { KeyCode.Pipe, "|" }, { KeyCode.RightCurlyBracket, "}" }, { KeyCode.Tilde, "~" }, { KeyCode.Keypad0, "Num 0" }, { KeyCode.Keypad1, "Num 1" }, { KeyCode.Keypad2, "Num 2" }, { KeyCode.Keypad3, "Num 3" }, { KeyCode.Keypad4, "Num 4" }, { KeyCode.Keypad5, "Num 5" }, { KeyCode.Keypad6, "Num 6" }, { KeyCode.Keypad7, "Num 7" }, { KeyCode.Keypad8, "Num 8" }, { KeyCode.Keypad9, "Num 9" }, { KeyCode.KeypadPeriod, "Num ." }, { KeyCode.KeypadDivide, "Num /" }, { KeyCode.KeypadMultiply, "Num *" }, { KeyCode.KeypadMinus, "Num -" }, { KeyCode.KeypadPlus, "Num +" }, { KeyCode.KeypadEnter, "Num Enter" }, { KeyCode.KeypadEquals, "Num =" }, { KeyCode.WheelUp, "Wheel Up"}, { KeyCode.WheelDown, "Wheel Down"}, { KeyCode.Mouse0, "Mouse 0"}, { KeyCode.Mouse1, "Mouse 1"}, { KeyCode.Mouse2, "Mouse 2"}, { KeyCode.Mouse3, "Mouse 3"}, { KeyCode.Mouse4, "Mouse 4"}, { KeyCode.Mouse5, "Mouse 5"}, { KeyCode.Mouse6, "Mouse 6"}, }; internal static readonly KeyCode[] k_MouseKeyCodes = new KeyCode[7] { KeyCode.Mouse0, KeyCode.Mouse1, KeyCode.Mouse2, KeyCode.Mouse3, KeyCode.Mouse4, KeyCode.Mouse5, KeyCode.Mouse6 }; internal static readonly Dictionary<KeyCode, EventModifiers> k_KeyCodeToEventModifiers = new() { { KeyCode.None, EventModifiers.None}, { KeyCode.LeftAlt, EventModifiers.Alt}, { KeyCode.RightAlt, EventModifiers.Alt}, { KeyCode.LeftControl, EventModifiers.Control}, { KeyCode.RightControl, EventModifiers.Control}, { KeyCode.LeftCommand, EventModifiers.Command}, { KeyCode.RightCommand, EventModifiers.Command}, { KeyCode.LeftShift, EventModifiers.Shift}, { KeyCode.RightShift, EventModifiers.Shift} }; static bool TryFormatKeycode(KeyCode code, StringBuilder builder) { string name; if (Application.platform == RuntimePlatform.OSXEditor) { if (s_KeyCodeNamesMacOS.TryGetValue(code, out name)) { builder.Append(name); return true; } } else { if (s_KeyCodeNamesNotMacOS.TryGetValue(code, out name)) { builder.Append(name); return true; } } if (s_KeyCodeNamesCommon.TryGetValue(code, out name)) { builder.Append(name); return true; } return false; } public bool Equals(KeyCombination other) { bool modifiersMatch; if (Application.platform != RuntimePlatform.OSXEditor) { const ShortcutModifiers controlMergeMask = ShortcutModifiers.Action | ShortcutModifiers.Control; bool thisHasControl = (modifiers & controlMergeMask) != 0; bool otherHasControl = (other.modifiers & controlMergeMask) != 0; ShortcutModifiers thisModifiers = m_Modifiers & ~controlMergeMask; ShortcutModifiers otherModifiers = other.m_Modifiers & ~controlMergeMask; modifiersMatch = thisModifiers == otherModifiers && thisHasControl == otherHasControl; } else { modifiersMatch = m_Modifiers == other.m_Modifiers; } return m_KeyCode == other.m_KeyCode && modifiersMatch; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is KeyCombination && Equals((KeyCombination)obj); } public override int GetHashCode() { unchecked { return ((int)m_KeyCode * 397) ^ (int)m_Modifiers; } } } }
UnityCsReference/Modules/ShortcutManagerEditor/KeyCombination.cs/0
{ "file_path": "UnityCsReference/Modules/ShortcutManagerEditor/KeyCombination.cs", "repo_id": "UnityCsReference", "token_count": 10293 }
446
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using System.Runtime.InteropServices; using UnityEngine.Bindings; namespace UnityEditor { [NativeType("Modules/SketchUpEditor/SketchUpImporter.h")] [System.Serializable] [StructLayout(LayoutKind.Sequential)] public struct SketchUpImportCamera { public Vector3 position; public Vector3 lookAt; public Vector3 up; public float fieldOfView; public float aspectRatio; public float orthoSize; public float nearPlane; public float farPlane; public bool isPerspective; } [NativeType("Modules/SketchUpEditor/SketchUpImporter.h")] [System.Serializable] [StructLayout(LayoutKind.Sequential)] public struct SketchUpImportScene { public SketchUpImportCamera camera; public string name; } [NativeType("Modules/SketchUpEditor/SketchUpNodeInfo.h")] [System.Serializable] [StructLayout(LayoutKind.Sequential)] internal struct SketchUpNodeInfo { public string name; public int parent; public bool enabled; public int nodeIndex; } [NativeHeader("Modules/SketchUpEditor/SketchUpImporter.h")] public sealed partial class SketchUpImporter : ModelImporter { extern public SketchUpImportScene[] GetScenes(); extern public SketchUpImportCamera GetDefaultCamera(); [NativeName("GetSketchUpImportNodes")] extern internal SketchUpNodeInfo[] GetNodes(); public extern double latitude { get; } public extern double longitude { get; } public extern double northCorrection { get; } } }
UnityCsReference/Modules/SketchUpEditor/Mono/SketchUp.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/SketchUpEditor/Mono/SketchUp.bindings.cs", "repo_id": "UnityCsReference", "token_count": 679 }
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.Collections.Generic; using UnityEngine; using UnityEngine.UIElements; using UnityEngine.UIElements.StyleSheets; namespace UnityEditor.StyleSheets { class StyleSheetBuilderHelper { public StyleSheetBuilder builder { get; private set; } public UssExportOptions options { get; private set; } public StyleSheet sheet { get; private set; } public StyleSheetBuilderHelper(UssExportOptions opts = null) { builder = new StyleSheetBuilder(); options = opts ?? new UssExportOptions(); } public StyleRule BeginRule(string comment = "", int line = 0) { var rule = builder.BeginRule(line); options.AddComment(rule, comment); return rule; } public void EndRule() { builder.EndRule(); } public void AddProperty(string name, Color value, string comment = "") { var property = builder.BeginProperty(name); options.AddComment(property, comment); builder.AddValue(value); builder.EndProperty(); } public void AddProperty(string name, bool value, string comment = "") { var property = builder.BeginProperty(name); options.AddComment(property, comment); builder.AddValue(value ? StyleValueKeyword.True : StyleValueKeyword.False); builder.EndProperty(); } public void AddProperty(string name, string value, string comment = "") { var property = builder.BeginProperty(name); options.AddComment(property, comment); builder.AddValue(value, StyleValueType.Enum); builder.EndProperty(); } public void AddPropertyString(string name, string value, string comment = "") { var property = builder.BeginProperty(name); options.AddComment(property, comment); builder.AddValue(value, StyleValueType.String); builder.EndProperty(); } public void AddPropertyResource(string name, string value, string comment = "") { var property = builder.BeginProperty(name); options.AddComment(property, comment); builder.AddValue(value, StyleValueType.ResourcePath); builder.EndProperty(); } public void AddProperty(string name, StyleValueKeyword value, string comment = "") { var property = builder.BeginProperty(name); options.AddComment(property, comment); builder.AddValue(value); builder.EndProperty(); } public void AddProperty(string name, float value, string comment = "") { var property = builder.BeginProperty(name); options.AddComment(property, comment); builder.AddValue(value); builder.EndProperty(); } public void AddProperty(string name, Vector2 offset, string comment = "") { var property = builder.BeginProperty(name); options.AddComment(property, comment); builder.AddValue(offset.x); builder.AddValue(offset.y); builder.EndProperty(); } public void AddImport(StyleSheet.ImportStruct importStruct) { builder.AddImport(importStruct); } public void PopulateSheet() { PopulateSheet(ScriptableObject.CreateInstance<StyleSheet>()); } public void PopulateSheet(StyleSheet dest) { sheet = dest; builder.BuildTo(sheet); } public string ToUsstring() { if (sheet == null) { PopulateSheet(); } return StyleSheetToUss.ToUssString(sheet, options); } #region StyleSheetManipulation public static void CopyProperty(StyleSheet sheet, UssComments comments, StyleProperty property, StyleSheetBuilderHelper helper) { var propertyCopy = helper.builder.BeginProperty(property.name); helper.options.comments.AddComment(propertyCopy, comments.Get(property)); foreach (var value in property.values) { switch (value.valueType) { case StyleValueType.Color: helper.builder.AddValue(sheet.ReadColor(value)); break; case StyleValueType.Enum: helper.builder.AddValue(sheet.ReadEnum(value), StyleValueType.Enum); break; case StyleValueType.Float: helper.builder.AddValue(sheet.ReadFloat(value)); break; case StyleValueType.Dimension: helper.builder.AddValue(sheet.ReadDimension(value)); break; case StyleValueType.Keyword: helper.builder.AddValue(sheet.ReadKeyword(value)); break; case StyleValueType.ResourcePath: helper.builder.AddValue(sheet.ReadResourcePath(value), StyleValueType.ResourcePath); break; case StyleValueType.String: helper.builder.AddValue(sheet.ReadString(value), StyleValueType.String); break; } } helper.builder.EndProperty(); } public static void PopulateProperties(IEnumerable<StyleProperty> properties, Dictionary<string, PropertyPair> pairs, bool item1) { foreach (var property in properties) { PropertyPair pair; if (!pairs.TryGetValue(property.name, out pair)) { pair = new PropertyPair { name = property.name }; pairs.Add(property.name, pair); } if (item1) { pair.p1 = property; } else { pair.p2 = property; } } } public static void BuildSelector(StyleComplexSelector complexSelector, StyleSheetBuilderHelper helper) { using (helper.builder.BeginComplexSelector(complexSelector.specificity)) { foreach (var selector in complexSelector.selectors) { helper.builder.AddSimpleSelector(selector.parts, selector.previousRelationship); } } } public static void CopySelector(StyleSheet sheet, UssComments comments, StyleComplexSelector complexSelector, StyleSheetBuilderHelper helper) { helper.BeginRule(comments.Get(complexSelector.rule)); BuildSelector(complexSelector, helper); foreach (var property in complexSelector.rule.properties) { CopyProperty(sheet, comments, property, helper); } helper.EndRule(); } #endregion } }
UnityCsReference/Modules/StyleSheetsEditor/Converters/StyleSheetBuilderHelper.cs/0
{ "file_path": "UnityCsReference/Modules/StyleSheetsEditor/Converters/StyleSheetBuilderHelper.cs", "repo_id": "UnityCsReference", "token_count": 3516 }
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; namespace UnityEngine { [Obsolete("Use SubsystemWithProvider instead.", false)] public abstract class Subsystem : ISubsystem { abstract public bool running { get; } abstract public void Start(); abstract public void Stop(); public void Destroy() { if (SubsystemManager.RemoveDeprecatedSubsystem(this)) OnDestroy(); } abstract protected void OnDestroy(); internal ISubsystemDescriptor m_SubsystemDescriptor; } [Obsolete("Use SubsystemWithProvider<> instead.", false)] public abstract class Subsystem<TSubsystemDescriptor> #pragma warning disable CS0618 : Subsystem #pragma warning restore CS0618 where TSubsystemDescriptor : ISubsystemDescriptor { public TSubsystemDescriptor SubsystemDescriptor => (TSubsystemDescriptor)m_SubsystemDescriptor; } }
UnityCsReference/Modules/Subsystems/Subsystem.deprecated.cs/0
{ "file_path": "UnityCsReference/Modules/Subsystems/Subsystem.deprecated.cs", "repo_id": "UnityCsReference", "token_count": 389 }
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; using UnityEngine.Rendering; namespace UnityEngine { partial class Terrain { [Obsolete("Enum type MaterialType is not used any more.", false)] public enum MaterialType { BuiltInStandard = 0, BuiltInLegacyDiffuse, BuiltInLegacySpecular, Custom } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("splatmapDistance is deprecated, please use basemapDistance instead. (UnityUpgradable) -> basemapDistance", true)] public float splatmapDistance { get { return basemapDistance; } set { basemapDistance = value; } } [Obsolete("castShadows is deprecated, please use shadowCastingMode instead.")] public bool castShadows { get { return shadowCastingMode != ShadowCastingMode.Off; } set { shadowCastingMode = value ? ShadowCastingMode.TwoSided : ShadowCastingMode.Off; } } [Obsolete("Property materialType is not used any more. Set materialTemplate directly.", false)] public MaterialType materialType { get { return MaterialType.Custom; } set {} } [Obsolete("Property legacySpecular is not used any more. Set materialTemplate directly.", false)] public Color legacySpecular { get { return Color.gray; } set {} } [Obsolete("Property legacyShininess is not used any more. Set materialTemplate directly.", false)] public float legacyShininess { get { return 0.078125f; } set {} } [Obsolete("Use TerrainData.SyncHeightmap to notify all Terrain instances using the TerrainData.", false)] public void ApplyDelayedHeightmapModification() { terrainData?.SyncHeightmap(); } } }
UnityCsReference/Modules/Terrain/Public/Terrain.deprecated.cs/0
{ "file_path": "UnityCsReference/Modules/Terrain/Public/Terrain.deprecated.cs", "repo_id": "UnityCsReference", "token_count": 857 }
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; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEditor; using UnityEngine; using UnityEditor.Overlays; using UnityEditor.Toolbars; using UnityEditor.EditorTools; using UnityEditor.UIElements; using UnityEngine.TerrainUtils; using UnityEngine.UIElements; namespace UnityEditor.TerrainTools { [CustomEditor(typeof(TerrainPaintToolWithOverlaysBase), editorForChildClasses: true)] internal class TerrainToolEditor : Editor, ICreateHorizontalToolbar { private Vector2 m_ScrollPos; private IMGUIContainer m_ImgContainer; static Dictionary<Type, (MethodInfo, bool)> m_ToolTypeToGUIFunc = new (); // true for non-obsolete, false for obsolete private static bool? m_IsTerrainToolsInstalled; // this value gets cleared on domain reload private static bool IsTerrainToolsPackageInstalled() { if (m_IsTerrainToolsInstalled.HasValue) { return m_IsTerrainToolsInstalled.Value; } var upm = UnityEditor.PackageManager.PackageInfo.GetAllRegisteredPackages(); var terrainPackageInfo = upm.Where(pi => pi.name == "com.unity.terrain-tools").ToArray(); Debug.Assert(terrainPackageInfo.Length <= 1, "Only one version of terrain-tools package allowed to be installed"); m_IsTerrainToolsInstalled = terrainPackageInfo.Length != 0; // equals 0 means no package installed, equals 1 means package is installed return m_IsTerrainToolsInstalled.Value; } public OverlayToolbar CreateHorizontalToolbarContent() { var toolbar = new OverlayToolbar(); var editor = TerrainInspector.s_activeTerrainInspectorInstance; var tool = target as TerrainPaintToolWithOverlaysBase; if (!editor || !tool) return toolbar; toolbar.Add(new EditorToolbarDropdown($"{tool.GetName()} Settings", () => { var m = Event.current.mousePosition; PopupWindow.Show(new Rect(m.x, m.y, 10, 20), new TerrainSettingsPopup()); })); return toolbar; } class TerrainSettingsPopup : PopupWindowContent { private Vector2 m_ScrollPos; public override Vector2 GetWindowSize() { var editor = TerrainInspector.s_activeTerrainInspectorInstance; var tool = EditorToolManager.GetActiveTool() as TerrainPaintToolWithOverlaysBase; if (editor && tool) { if (!tool.HasToolSettings) { // appropriate size for no tool settings message return new Vector2(230, 30); } // else tool settings // different sizes based on tooltype / package installed perhaps if (tool.Category == TerrainCategory.NeighborTerrains) { return new Vector2(400, 60); } if (tool.Category == TerrainCategory.Materials || tool.Category == TerrainCategory.Foliage || tool.Category == TerrainCategory.CustomBrushes) { return new Vector2(400, 250); } // if package installed if (IsTerrainToolsPackageInstalled()) { // stamp and noise foliage and materials should be longer if (tool.GetName() == "Stamp Terrain" || tool.GetName() == "Sculpt/Noise") { return new Vector2(400, 250); } if (tool.GetName() == "Transform/Smudge" || tool.GetName() == "Effects/Sharpen Peaks" || tool.GetName() == "Effects/Contrast") { return new Vector2(400, 80); } if (tool.GetName() == "Transform/Twist" || tool.GetName() == "Transform/Pinch" || tool.GetName() == "Smooth Height") { return new Vector2(400, 100); } // need to do something about erosion too (same size, but a little longer maybe) if (tool.GetName() == "Erosion/Wind" || tool.GetName() == "Erosion/Hydraulic" || tool.GetName() == "Erosion/Thermal") { return new Vector2(400, 160); } // else everything else should be smaller return new Vector2(400, 120); } // else package is NOT installed if (tool.GetName() == "Smooth Height") { return new Vector2(400, 35); } return new Vector2(400, 75); // every other tool without package } // if code reaches here, tool is null return new Vector2(400, 250); // return some default } public override void OnGUI(Rect rect) { var editor = TerrainInspector.s_activeTerrainInspectorInstance; var tool = EditorToolManager.GetActiveTool() as TerrainPaintToolWithOverlaysBase; if (editor && tool) { m_ScrollPos = EditorGUILayout.BeginScrollView(m_ScrollPos); TerrainToolEditor.OnGUI(tool); EditorGUILayout.EndScrollView(); } } } public void CreateIMGContainer() { m_ImgContainer = new IMGUIContainer(); m_ImgContainer.style.minWidth = 300; m_ImgContainer.style.maxWidth = 400; m_ImgContainer.style.maxHeight = 600; m_ImgContainer.onGUIHandler = () => { // adjust brush mask width here to force brush mask sizes EditorGUIUtility.currentViewWidth = 430; OnGUI(); EditorGUILayout.Space(); // spacer for bottom offset }; } public override VisualElement CreateInspectorGUI() { CreateIMGContainer(); return m_ImgContainer; } public static void OnGUI(TerrainPaintToolWithOverlaysBase tool) { if (!tool) { return; } if (!tool.Terrain && Selection.activeGameObject) { tool.Terrain = Selection.activeGameObject.GetComponent<Terrain>(); } if (!tool.Terrain) { return; } if (tool.HasToolSettings) { Type type = tool.GetType(); if (!m_ToolTypeToGUIFunc.ContainsKey(type)) { // store the tool type to function ONCE MethodInfo funcWithoutBoolean = type.GetMethod("OnToolSettingsGUI", new [] {typeof(Terrain), typeof(IOnInspectorGUI)}); // not obsolete MethodInfo funcWithBoolean = type.GetMethod("OnToolSettingsGUI", new [] {typeof(Terrain), typeof(IOnInspectorGUI), typeof(bool)}); // obsolete if (funcWithoutBoolean == null || funcWithBoolean == null) return; if (funcWithoutBoolean.DeclaringType != funcWithoutBoolean.GetBaseDefinition().DeclaringType) { // non obsolete method is overriden m_ToolTypeToGUIFunc[type] = (funcWithoutBoolean, true); } else if (funcWithBoolean.DeclaringType != funcWithBoolean.GetBaseDefinition().DeclaringType) { // obsolete method is overriden m_ToolTypeToGUIFunc[type] = (funcWithBoolean, false); } else { return; // shouldnt get here } } // invoke obsolete or non obsolete method depending on value of Item2 (bool) m_ToolTypeToGUIFunc[type].Item1 .Invoke(tool, m_ToolTypeToGUIFunc[type].Item2 ? new object[] {tool.Terrain, new OnInspectorGUIContext()} : new object[] {tool.Terrain, new OnInspectorGUIContext(), false}); } else { GUILayout.Label("This tool has no extra tool settings!"); } } public void OnGUI() { var editor = TerrainInspector.s_activeTerrainInspectorInstance; var tool = target as TerrainPaintToolWithOverlaysBase; if (!editor || !tool) return; m_ScrollPos = EditorGUILayout.BeginScrollView(m_ScrollPos); OnGUI(tool); // helper function for GUI EditorGUILayout.EndScrollView(); } } }
UnityCsReference/Modules/TerrainEditor/Overlays/ToolEditors.cs/0
{ "file_path": "UnityCsReference/Modules/TerrainEditor/Overlays/ToolEditors.cs", "repo_id": "UnityCsReference", "token_count": 4716 }
451
// 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.TerrainTools; namespace UnityEditor { internal class TerrainModificationProcessor : AssetModificationProcessor { public static string[] OnWillSaveAssets(string[] paths) { PaintContext.ApplyDelayedActions(); return paths; } } internal class TerrainEditorUtility { internal static void RemoveTree(Terrain terrain, int index) { TerrainData terrainData = terrain.terrainData; if (terrainData == null) return; Undo.RegisterCompleteObjectUndo(terrainData, "Remove tree"); terrainData.RemoveTreePrototype(index); } internal static void RemoveDetail(Terrain terrain, int index) { TerrainData terrainData = terrain.terrainData; if (terrainData == null) return; Undo.RegisterCompleteObjectUndo(terrainData, "Remove detail object"); terrainData.RemoveDetailPrototype(index); } internal static bool IsLODTreePrototype(GameObject prefab) { return prefab != null && prefab.GetComponent<LODGroup>() != null; } } } //namespace
UnityCsReference/Modules/TerrainEditor/Utilities/TerrainEditorUtility.cs/0
{ "file_path": "UnityCsReference/Modules/TerrainEditor/Utilities/TerrainEditorUtility.cs", "repo_id": "UnityCsReference", "token_count": 575 }
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.Runtime.CompilerServices; // Allow internal visibility to the following assemblies [assembly: InternalsVisibleTo("Unity.TextMeshPro")] [assembly: InternalsVisibleTo("Unity.FontEngine")] [assembly: InternalsVisibleTo("Unity.TextCore.FontEngine")] [assembly: InternalsVisibleTo("Unity.TextCore.FontEngine.Tools")] [assembly: InternalsVisibleTo("UnityEngine.TextCoreModule")] [assembly: InternalsVisibleTo("UnityEngine.TextCoreTextModule")] // Used internally for testing and a few enterprise users. [assembly: InternalsVisibleTo("UnityEngine.TextCore.Tools")] [assembly: InternalsVisibleTo("Unity.TextCore.Editor")] [assembly: InternalsVisibleTo("UnityEditor.TextCoreTextModule")] [assembly: InternalsVisibleTo("Unity.TextMeshPro.Editor")] [assembly: InternalsVisibleTo("Unity.TextMeshPro.Tests")] [assembly: InternalsVisibleTo("Unity.TextCore.Tests")] [assembly: InternalsVisibleTo("Unity.FontEngine.Tests")] [assembly: InternalsVisibleTo("Unity.UIElements.Tests")] [assembly: InternalsVisibleTo("Unity.UIElements.PlayModeTests")] // Make internal visible to UIElements module. [assembly: InternalsVisibleTo("UnityEngine.UIElementsModule")] [assembly: InternalsVisibleTo("Unity.UIElements")] [assembly: InternalsVisibleTo("Unity.UIElements.Text")] [assembly: InternalsVisibleTo("UnityEditor.TextCoreTextEngineModule")] [assembly: InternalsVisibleTo("Unity.TextCore.Editor.Tests")] [assembly: InternalsVisibleTo("Unity.TextMeshPro.Editor")] [assembly: InternalsVisibleTo("Unity.TextMeshPro.Editor.Tests")]
UnityCsReference/Modules/TextCoreTextEngine/Managed/AssemblyInfo.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreTextEngine/Managed/AssemblyInfo.cs", "repo_id": "UnityCsReference", "token_count": 515 }
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; using System.Collections.Generic; using System.Text; using UnityEngine.Bindings; using UnityEngine.TextCore.LowLevel; namespace UnityEngine.TextCore.Text { // ================================================================================ // Properties and functions related to character and glyph additions as well as // tacking glyphs that need to be added to various font asset atlas textures. // ================================================================================ public partial class FontAsset { // List and HashSet used for tracking font assets whose font atlas texture and character data needs updating. static List<FontAsset> k_FontAssets_FontFeaturesUpdateQueue = new List<FontAsset>(); static HashSet<int> k_FontAssets_FontFeaturesUpdateQueueLookup = new HashSet<int>(); static List<FontAsset> k_FontAssets_KerningUpdateQueue = new List<FontAsset>(); static HashSet<int> k_FontAssets_KerningUpdateQueueLookup = new HashSet<int>(); static List<Texture2D> k_FontAssets_AtlasTexturesUpdateQueue = new List<Texture2D>(); static HashSet<int> k_FontAssets_AtlasTexturesUpdateQueueLookup = new HashSet<int>(); /// <summary> /// Internal static array used to avoid allocations when using the GetGlyphPairAdjustmentTable(). /// </summary> internal static uint[] k_GlyphIndexArray; internal static void RegisterFontAssetForFontFeatureUpdate(FontAsset fontAsset) { int instanceID = fontAsset.instanceID; if (k_FontAssets_FontFeaturesUpdateQueueLookup.Add(instanceID)) k_FontAssets_FontFeaturesUpdateQueue.Add(fontAsset); } internal static void RegisterFontAssetForKerningUpdate(FontAsset fontAsset) { int instanceID = fontAsset.instanceID; if (k_FontAssets_KerningUpdateQueueLookup.Add(instanceID)) k_FontAssets_KerningUpdateQueue.Add(fontAsset); } /// <summary> /// Function called to update the font atlas texture and character data of font assets to which /// new characters were added. /// </summary> internal static void UpdateFontFeaturesForFontAssetsInQueue() { int count = k_FontAssets_FontFeaturesUpdateQueue.Count; for (int i = 0; i < count; i++) { k_FontAssets_FontFeaturesUpdateQueue[i].UpdateGPOSFontFeaturesForNewlyAddedGlyphs(); } if (count > 0) { k_FontAssets_FontFeaturesUpdateQueue.Clear(); k_FontAssets_FontFeaturesUpdateQueueLookup.Clear(); } count = k_FontAssets_KerningUpdateQueue.Count; for (int i = 0; i < count; i++) { k_FontAssets_KerningUpdateQueue[i].UpdateGlyphAdjustmentRecordsForNewGlyphs(); } if (count > 0) { k_FontAssets_KerningUpdateQueue.Clear(); k_FontAssets_KerningUpdateQueueLookup.Clear(); } } /// <summary> /// Register Atlas Texture for Apply() /// </summary> /// <param name="texture">The texture on which to call Apply().</param> internal static void RegisterAtlasTextureForApply(Texture2D texture) { int instanceID = texture.GetInstanceID(); if (k_FontAssets_AtlasTexturesUpdateQueueLookup.Add(instanceID)) k_FontAssets_AtlasTexturesUpdateQueue.Add(texture); } internal static void UpdateAtlasTexturesInQueue() { int count = k_FontAssets_AtlasTexturesUpdateQueueLookup.Count; for (int i = 0; i < count; i++) k_FontAssets_AtlasTexturesUpdateQueue[i].Apply(false, false); if (count > 0) { k_FontAssets_AtlasTexturesUpdateQueue.Clear(); k_FontAssets_AtlasTexturesUpdateQueueLookup.Clear(); } } [VisibleToOtherModules("UnityEngine.IMGUIModule", "UnityEngine.UIElementsModule")] internal static void UpdateFontAssetsInUpdateQueue() { UpdateAtlasTexturesInQueue(); UpdateFontFeaturesForFontAssetsInQueue(); } /// <summary> /// Try adding the characters from the provided string to the font asset. /// </summary> /// <param name="unicodes">Array that contains the characters to add to the font asset.</param> /// <param name="includeFontFeatures"></param> /// <returns>Returns true if all the characters were successfully added to the font asset. Return false otherwise.</returns> public bool TryAddCharacters(uint[] unicodes, bool includeFontFeatures = false) { return TryAddCharacters(unicodes, out _, includeFontFeatures); } /// <summary> /// Try adding the characters from the provided string to the font asset. /// </summary> /// <param name="unicodes">Array that contains the characters to add to the font asset.</param> /// <param name="missingUnicodes">Array containing the characters that could not be added to the font asset.</param> /// <param name="includeFontFeatures"></param> /// <returns>Returns true if all the characters were successfully added to the font asset. Return false otherwise.</returns> public bool TryAddCharacters(uint[] unicodes, out uint[] missingUnicodes, bool includeFontFeatures = false) { using var profilerScope = k_TryAddCharactersMarker.Auto(); // Make sure font asset is set to dynamic and that we have a valid list of characters. if (unicodes == null || unicodes.Length == 0 || m_AtlasPopulationMode == AtlasPopulationMode.Static) { if (m_AtlasPopulationMode == AtlasPopulationMode.Static) Debug.LogWarning("Unable to add characters to font asset [" + this.name + "] because its AtlasPopulationMode is set to Static.", this); else Debug.LogWarning("Unable to add characters to font asset [" + this.name + "] because the provided Unicode list is Null or Empty.", this); missingUnicodes = null; return false; } // Load font face. if (LoadFontFace() != FontEngineError.Success) { missingUnicodes = new uint[unicodes.Length]; var index = 0; foreach (var unicode in unicodes) { missingUnicodes[index++] = unicode; } return false; } // Make sure font asset has been initialized if (m_CharacterLookupDictionary == null || m_GlyphLookupDictionary == null) ReadFontAssetDefinition(); // guaranteed to be non-null at this point var characterLookupDictionary = m_CharacterLookupDictionary!; var glyphLookupDictionary = m_GlyphLookupDictionary!; // Clear lists used to track which character and glyphs were added or missing. m_GlyphsToAdd.Clear(); m_GlyphsToAddLookup.Clear(); m_CharactersToAdd.Clear(); m_CharactersToAddLookup.Clear(); s_MissingCharacterList.Clear(); var isMissingCharacters = false; var unicodeCount = unicodes.Length; for (int i = 0; i < unicodeCount; i++) { uint unicode = unicodes[i]; // Check if character is already contained in the character table. if (characterLookupDictionary.ContainsKey(unicode)) continue; // Get the index of the glyph for this Unicode value. var glyphIndex = FontEngine.GetGlyphIndex(unicode); // Skip missing glyphs if (glyphIndex == 0) { // Special handling for characters with potential alternative glyph representations switch (unicode) { case 0xA0: // Non Breaking Space <NBSP> // Use Space glyphIndex = FontEngine.GetGlyphIndex(0x20); break; case 0xAD: // Soft Hyphen <SHY> case 0x2011: // Non Breaking Hyphen // Use Hyphen Minus glyphIndex = FontEngine.GetGlyphIndex(0x2D); break; } // Skip to next character if no potential alternative glyph representation is present in font file. if (glyphIndex == 0) { // Add character to list of missing characters. s_MissingCharacterList.Add(unicode); isMissingCharacters = true; continue; } } var character = new Character(unicode, glyphIndex); // Check if glyph is already contained in the font asset as the same glyph might be referenced by multiple characters. if (glyphLookupDictionary.TryGetValue(glyphIndex, out var value)) { // Add a reference to the source text asset and glyph character.glyph = value; character.textAsset = this; m_CharacterTable.Add(character); characterLookupDictionary.Add(unicode, character); continue; } // Make sure glyph index has not already been added to list of glyphs to add. if (m_GlyphsToAddLookup.Add(glyphIndex)) m_GlyphsToAdd.Add(glyphIndex); // Make sure unicode / character has not already been added. if (m_CharactersToAddLookup.Add(unicode)) m_CharactersToAdd.Add(character); } if (m_GlyphsToAdd.Count == 0) { //Debug.LogWarning("No characters will be added to font asset [" + this.name + "] either because they are already present in the font asset or missing from the font file."); missingUnicodes = unicodes; return isMissingCharacters ? false : true; } // Resize the Atlas Texture to the appropriate size if (m_AtlasTextures[m_AtlasTextureIndex].width <= 1 || m_AtlasTextures[m_AtlasTextureIndex].height <= 1) { m_AtlasTextures[m_AtlasTextureIndex].Reinitialize(m_AtlasWidth, m_AtlasHeight); FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]); } Glyph[] glyphs; var allGlyphsAddedToTexture = FontEngine.TryAddGlyphsToTexture(m_GlyphsToAdd, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex], out glyphs, out int glyphsAddedCount); // Add new glyphs to relevant font asset data structure { var additionalCapacity = glyphs.Length; EnsureAdditionalCapacity(m_GlyphTable, additionalCapacity); EnsureAdditionalCapacity(glyphLookupDictionary, additionalCapacity); EnsureAdditionalCapacity(m_GlyphIndexListNewlyAdded, additionalCapacity); EnsureAdditionalCapacity(m_GlyphIndexList, additionalCapacity); } for (int i = 0; i < glyphsAddedCount && glyphs[i] != null; i++) { Glyph glyph = glyphs[i]; var glyphIndex = glyph.index; glyph.atlasIndex = m_AtlasTextureIndex; // Add new glyph to glyph table. m_GlyphTable.Add(glyph); glyphLookupDictionary.Add(glyphIndex, glyph); m_GlyphIndexListNewlyAdded.Add(glyphIndex); m_GlyphIndexList.Add(glyphIndex); } // Clear glyph index list to allow m_GlyphsToAdd.Clear(); // Add new characters to relevant data structures as well as track glyphs that could not be added to the current atlas texture. { var additionalCapacity = m_CharactersToAdd.Count; EnsureAdditionalCapacity(m_GlyphsToAdd, additionalCapacity); EnsureAdditionalCapacity(m_CharacterTable, additionalCapacity); EnsureAdditionalCapacity(characterLookupDictionary, additionalCapacity); } for (int i = 0; i < m_CharactersToAdd.Count; i++) { var character = m_CharactersToAdd[i]; if (glyphLookupDictionary.TryGetValue(character.glyphIndex, out var glyph) == false) { m_GlyphsToAdd.Add(character.glyphIndex); continue; } // Add a reference to the source text asset and glyph character.glyph = glyph; character.textAsset = this; m_CharacterTable.Add(character); characterLookupDictionary.Add(character.unicode, character); // Remove character from list to add m_CharactersToAdd.RemoveAt(i); i--; } // Try adding missing glyphs to if (m_IsMultiAtlasTexturesEnabled && allGlyphsAddedToTexture == false) { while (allGlyphsAddedToTexture == false) allGlyphsAddedToTexture = TryAddGlyphsToNewAtlasTexture(); } // Get Font Features for the given characters if (includeFontFeatures) { UpdateFontFeaturesForNewlyAddedGlyphs(); } // Makes the changes to the font asset persistent. RegisterResourceForUpdate?.Invoke(this); // Populate list of missing characters foreach (var character in m_CharactersToAdd) { s_MissingCharacterList.Add(character.unicode); } missingUnicodes = null; if (s_MissingCharacterList.Count > 0) missingUnicodes = s_MissingCharacterList.ToArray(); return allGlyphsAddedToTexture && !isMissingCharacters; } /// <summary> /// Try adding the characters from the provided string to the font asset. /// </summary> /// <param name="characters">String containing the characters to add to the font asset.</param> /// <param name="includeFontFeatures"></param> /// <returns>Returns true if all the characters were successfully added to the font asset. Return false otherwise.</returns> public bool TryAddCharacters(string characters, bool includeFontFeatures = false) { return TryAddCharacters(characters, out _, includeFontFeatures); } /// <summary> /// Try adding the characters from the provided string to the font asset. /// </summary> /// <param name="characters">String containing the characters to add to the font asset.</param> /// <param name="missingCharacters">String containing the characters that could not be added to the font asset.</param> /// <param name="includeFontFeatures"></param> /// <returns>Returns true if all the characters were successfully added to the font asset. Return false otherwise.</returns> public bool TryAddCharacters(string characters, out string missingCharacters, bool includeFontFeatures = false) { var charactersUInt = new uint[characters.Length]; for (int i = 0; i < characters.Length; i++) { charactersUInt[i] = characters[i]; } bool success = TryAddCharacters(charactersUInt, out uint[] missingCharactersUInt, includeFontFeatures); if (missingCharactersUInt == null || missingCharactersUInt.Length <= 0) { missingCharacters = null; return success; } StringBuilder stringBuilder = new StringBuilder(missingCharactersUInt.Length); foreach (uint value in missingCharactersUInt) { stringBuilder.Append((char)value); } missingCharacters = stringBuilder.ToString(); return success; } internal bool TryAddGlyphVariantIndexInternal(uint unicode, uint nextCharacter, uint variantGlyphIndex) { return m_VariantGlyphIndexes.TryAdd((unicode, nextCharacter), variantGlyphIndex); } internal bool TryGetGlyphVariantIndexInternal(uint unicode, uint nextCharacter, out uint variantGlyphIndex) { return m_VariantGlyphIndexes.TryGetValue((unicode, nextCharacter), out variantGlyphIndex); } internal bool TryAddGlyphInternal(uint glyphIndex, out Glyph glyph) { using (k_TryAddGlyphMarker.Auto()) { glyph = null; // Check if glyph is already present in the font asset. if (glyphLookupTable.TryGetValue(glyphIndex, out glyph)) { return true; } // Load font face. if (LoadFontFace() != FontEngineError.Success) return false; return TryAddGlyphToAtlas(glyphIndex, out glyph); } } /// <summary> /// Try adding character using Unicode value to font asset. /// Function assumes internal user has already checked to make sure the character is not already contained in the font asset. /// </summary> /// <param name="unicode">The Unicode value of the character.</param> /// <param name="character">The character data if successfully added to the font asset. Null otherwise.</param> /// <param name="getFontFeatures">Determines if Ligatures are populated or not</param> /// <param name="populateLigatures"></param> /// <returns>Returns true if the character has been added. False otherwise.</returns> internal bool TryAddCharacterInternal(uint unicode, FontStyles fontStyle, TextFontWeight fontWeight, out Character character, bool populateLigatures = true) { using (k_TryAddCharacterMarker.Auto()) { character = null; // Check if the Unicode character is already known to be missing from the source font file. if (m_MissingUnicodesFromFontFile.Contains(unicode)) { return false; } // Load font face. if (LoadFontFace() != FontEngineError.Success) { return false; } uint glyphIndex = FontEngine.GetGlyphIndex(unicode); if (glyphIndex == 0) { // Special handling for characters with potential alternative glyph representations switch (unicode) { case 0xA0: // Non Breaking Space <NBSP> // Use Space glyphIndex = FontEngine.GetGlyphIndex(0x20); break; case 0xAD: // Soft Hyphen <SHY> case 0x2011: // Non Breaking Hyphen // Use Hyphen Minus glyphIndex = FontEngine.GetGlyphIndex(0x2D); break; } // Return if no potential alternative glyph representation is present in font file. if (glyphIndex == 0) { m_MissingUnicodesFromFontFile.Add(unicode); return false; } } // Check if glyph is already contained in the font asset as the same glyph might be referenced by multiple characters. if (glyphLookupTable.ContainsKey(glyphIndex)) { character = CreateCharacterAndAddToCache(unicode, m_GlyphLookupDictionary[glyphIndex], fontStyle, fontWeight); // Makes the changes to the font asset persistent. RegisterResourceForUpdate?.Invoke(this); return true; } Glyph glyph = null; if (TryAddGlyphToAtlas(glyphIndex, out glyph, populateLigatures)) { // Add new character character = CreateCharacterAndAddToCache(unicode, glyph, fontStyle, fontWeight); return true; } return false; } } bool TryAddGlyphToAtlas(uint glyphIndex, out Glyph glyph, bool populateLigatures = true) { glyph = null; if (m_AtlasTextures[m_AtlasTextureIndex].isReadable == false) { Debug.LogWarning($"Unable to add the requested glyph to font asset [{this.name}]'s atlas texture. Please make the texture [{m_AtlasTextures[m_AtlasTextureIndex].name}] readable.", m_AtlasTextures[m_AtlasTextureIndex]); return false; } // Resize the Atlas Texture to the appropriate size if (m_AtlasTextures[m_AtlasTextureIndex].width <= 1 || m_AtlasTextures[m_AtlasTextureIndex].height <= 1) { m_AtlasTextures[m_AtlasTextureIndex].Reinitialize(m_AtlasWidth, m_AtlasHeight); FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]); } // Set texture upload mode to batching texture.Apply() FontEngine.SetTextureUploadMode(false); if (TryAddGlyphToTexture(glyphIndex, out glyph, populateLigatures)) return true; // Add glyph which did not fit in current atlas texture to new atlas texture. if (m_IsMultiAtlasTexturesEnabled) { // Create new atlas texture SetupNewAtlasTexture(); if(TryAddGlyphToTexture(glyphIndex, out glyph, populateLigatures)) return true; } return false; } bool TryAddGlyphToTexture(uint glyphIndex, out Glyph glyph, bool populateLigatures = true) { if (FontEngine.TryAddGlyphToTexture(glyphIndex, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex], out glyph)) { // Update glyph atlas index glyph.atlasIndex = m_AtlasTextureIndex; // Add new glyph to glyph table. m_GlyphTable.Add(glyph); m_GlyphLookupDictionary.Add(glyphIndex, glyph); m_GlyphIndexList.Add(glyphIndex); m_GlyphIndexListNewlyAdded.Add(glyphIndex); if (m_GetFontFeatures/*&& TMP_Settings.getFontFeaturesAtRuntime*/) { if (populateLigatures) { UpdateGSUBFontFeaturesForNewGlyphIndex(glyphIndex); RegisterFontAssetForFontFeatureUpdate(this); } else { RegisterFontAssetForKerningUpdate(this); } } RegisterAtlasTextureForApply(m_AtlasTextures[m_AtlasTextureIndex]); FontEngine.SetTextureUploadMode(true); // Makes the changes to the font asset persistent. RegisterResourceForUpdate?.Invoke(this); return true; } return false; } bool TryAddGlyphsToNewAtlasTexture() { // Create and prepare new atlas texture SetupNewAtlasTexture(); Glyph[] glyphs; // Try adding remaining glyphs in the newly created atlas texture bool allGlyphsAddedToTexture = FontEngine.TryAddGlyphsToTexture(m_GlyphsToAdd, m_AtlasPadding, GlyphPackingMode.BestShortSideFit, m_FreeGlyphRects, m_UsedGlyphRects, m_AtlasRenderMode, m_AtlasTextures[m_AtlasTextureIndex], out glyphs, out int glyphsAddedCount); // Add new glyphs to relevant data structures. for (int i = 0; i < glyphsAddedCount && glyphs[i] != null; i++) { Glyph glyph = glyphs[i]; uint glyphIndex = glyph.index; glyph.atlasIndex = m_AtlasTextureIndex; // Add new glyph to glyph table. m_GlyphTable.Add(glyph); m_GlyphLookupDictionary.Add(glyphIndex, glyph); m_GlyphIndexListNewlyAdded.Add(glyphIndex); m_GlyphIndexList.Add(glyphIndex); } // Clear glyph index list to allow us to track glyphs m_GlyphsToAdd.Clear(); // Add new characters to relevant data structures as well as track glyphs that could not be added to the current atlas texture. for (int i = 0; i < m_CharactersToAdd.Count; i++) { Character character = m_CharactersToAdd[i]; Glyph glyph; if (m_GlyphLookupDictionary.TryGetValue(character.glyphIndex, out glyph) == false) { m_GlyphsToAdd.Add(character.glyphIndex); continue; } // Add a reference to the source text asset and glyph character.glyph = glyph; character.textAsset = this; m_CharacterTable.Add(character); m_CharacterLookupDictionary.Add(character.unicode, character); // Remove character m_CharactersToAdd.RemoveAt(i); i -= 1; } return allGlyphsAddedToTexture; } void SetupNewAtlasTexture() { m_AtlasTextureIndex += 1; // Check size of atlas texture array if (m_AtlasTextures.Length == m_AtlasTextureIndex) Array.Resize(ref m_AtlasTextures, m_AtlasTextures.Length * 2); // Initialize new atlas texture TextureFormat texFormat = ((GlyphRasterModes)m_AtlasRenderMode & GlyphRasterModes.RASTER_MODE_COLOR) == GlyphRasterModes.RASTER_MODE_COLOR ? TextureFormat.RGBA32 : TextureFormat.Alpha8; m_AtlasTextures[m_AtlasTextureIndex] = new Texture2D(m_AtlasWidth, m_AtlasHeight, texFormat, false); FontEngine.ResetAtlasTexture(m_AtlasTextures[m_AtlasTextureIndex]); // Clear packing GlyphRects int packingModifier = ((GlyphRasterModes)m_AtlasRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP ? 0 : 1; m_FreeGlyphRects.Clear(); m_FreeGlyphRects.Add(new GlyphRect(0, 0, m_AtlasWidth - packingModifier, m_AtlasHeight - packingModifier)); m_UsedGlyphRects.Clear(); // Add new texture as sub asset to font asset Texture2D tex = m_AtlasTextures[m_AtlasTextureIndex]; tex.name = atlasTexture.name + " " + m_AtlasTextureIndex; OnFontAssetTextureChanged?.Invoke(tex, this); } Character CreateCharacterAndAddToCache(uint unicode, Glyph glyph, FontStyles fontStyle, TextFontWeight fontWeight) { Character character; // We want to make sure we only add the character to the CharacterTable once if (!m_CharacterLookupDictionary.TryGetValue(unicode, out character)) { character = new Character(unicode, this, glyph); m_CharacterTable.Add(character); AddCharacterToLookupCache(unicode, character, FontStyles.Normal, TextFontWeight.Regular); } if (fontStyle != FontStyles.Normal || fontWeight != TextFontWeight.Regular) AddCharacterToLookupCache(unicode, character, fontStyle, fontWeight); return character; } } }
UnityCsReference/Modules/TextCoreTextEngine/Managed/TextAssets/FontAsset/FontAssetAtlasPopulation.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreTextEngine/Managed/TextAssets/FontAsset/FontAssetAtlasPopulation.cs", "repo_id": "UnityCsReference", "token_count": 13235 }
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.Collections.Generic; using System.Runtime.CompilerServices; using UnityEngine.Bindings; using UnityEngine.Profiling; using UnityEngine.TextCore.LowLevel; using System; using System.Text; using System.Globalization; using Unity.Jobs.LowLevel.Unsafe; using System.Threading.Tasks; namespace UnityEngine.TextCore.Text { internal partial class TextGenerator { // Character codes const int k_Tab = 9, k_LineFeed = 10, k_VerticalTab = 11, k_CarriageReturn = 13, k_Space = 32, k_DoubleQuotes = 34, k_NumberSign = 35, k_PercentSign = 37, k_SingleQuote = 39, k_Plus = 43, k_Period = 46, k_LesserThan = 60, k_Equal = 61, k_GreaterThan = 62, k_Underline = 95, k_NoBreakSpace = 0x00A0, k_SoftHyphen = 0x00AD, k_HyphenMinus = 0x002D, k_FigureSpace = 0x2007, k_Hyphen = 0x2010, k_NonBreakingHyphen = 0x2011, k_ZeroWidthSpace = 0x200B, k_NarrowNoBreakSpace = 0x202F, k_WordJoiner = 0x2060, k_HorizontalEllipsis = 0x2026, k_LineSeparator = 0x2028, k_ParagraphSeparator = 0x2029, k_RightSingleQuote = 8217, k_Square = 9633, k_HangulJamoStart = 0x1100, k_HangulJamoEnd = 0x11ff, k_CjkStart = 0x2E80, k_CjkEnd = 0x9FFF, k_HangulJameExtendedStart = 0xA960, k_HangulJameExtendedEnd = 0xA97F, k_HangulSyllablesStart = 0xAC00, k_HangulSyllablesEnd = 0xD7FF, k_CjkIdeographsStart = 0xF900, k_CjkIdeographsEnd = 0xFAFF, k_CjkFormsStart = 0xFE30, k_CjkFormsEnd = 0xFE4F, k_CjkHalfwidthStart = 0xFF00, k_CjkHalfwidthEnd = 0xFFEF, k_EndOfText = 0x03; const float k_FloatUnset = -32767; const int k_MaxCharacters = 8; // Determines the initial allocation and size of the character array / buffer. static TextGenerator s_TextGenerator; [VisibleToOtherModules("UnityEngine.UIElementsModule")] internal static bool IsExecutingJob { get; set; } [VisibleToOtherModules("UnityEngine.UIElementsModule")] internal static TextGenerator GetTextGenerator() { if (s_TextGenerator == null) s_TextGenerator = new TextGenerator(); return s_TextGenerator; } public void GenerateText(TextGenerationSettings settings, TextInfo textInfo) { bool canWriteOnAsset = !IsExecutingJob; if (settings.fontAsset == null || settings.fontAsset.characterLookupTable == null) { Debug.LogWarning("Can't Generate Mesh, No Font Asset has been assigned."); return; } if (textInfo == null) { // TODO: If no textInfo is passed, we want to use an internal one instead of creating a new one everytime. Debug.LogError("Null TextInfo provided to TextGenerator. Cannot update its content."); return; } Profiler.BeginSample("TextGenerator.GenerateText"); Prepare(settings, textInfo); // Update font asset atlas textures and font features. if (canWriteOnAsset) FontAsset.UpdateFontAssetsInUpdateQueue(); GenerateTextMesh(settings, textInfo); Profiler.EndSample(); } /// <summary> /// Internal array containing the converted source text used in the text parsing process. /// </summary> private TextBackingContainer m_TextBackingArray = new TextBackingContainer(4); /// <summary> /// Array containing the Unicode characters to be parsed. /// </summary> internal TextProcessingElement[] m_TextProcessingArray = new TextProcessingElement[8]; /// <summary> /// The number of Unicode characters that have been parsed and contained in the m_InternalParsingBuffer /// </summary> internal int m_InternalTextProcessingArraySize; /// <summary> /// Determines if the data structures allocated to contain the geometry of the text object will be reduced in size if the number of characters required to display the text is reduced by more than 256 characters. /// This reduction has the benefit of reducing the amount of vertex data being submitted to the graphic device but results in GC when it occurs. /// </summary> bool vertexBufferAutoSizeReduction { get { return m_VertexBufferAutoSizeReduction; } set { m_VertexBufferAutoSizeReduction = value; } } [SerializeField] protected bool m_VertexBufferAutoSizeReduction = false; private char[] m_HtmlTag = new char[256]; // Maximum length of rich text tag. This is pre-allocated to avoid GC. internal HighlightState m_HighlightState = new HighlightState(Color.white, Offset.zero); protected bool m_IsIgnoringAlignment; /// <summary> /// Property indicating whether the text is Truncated or using Ellipsis. /// </summary> public bool isTextTruncated { get { return m_IsTextTruncated; } } protected bool m_IsTextTruncated; /// <summary> /// Delegate for the OnMissingCharacter event called when the requested Unicode character is missing from the font asset. /// </summary> /// <param name="unicode">The Unicode of the missing character.</param> /// <param name="stringIndex">The index of the missing character in the source string.</param> /// <param name="text">The source text that contains the missing character.</param> /// <param name="fontAsset">The font asset that is missing the requested characters.</param> /// <param name="textComponent">The text component where the requested character is missing.</param> public delegate void MissingCharacterEventCallback(uint unicode, int stringIndex, TextInfo text, FontAsset fontAsset); /// <summary> /// Event delegate to be called when the requested Unicode character is missing from the font asset. /// </summary> public static event MissingCharacterEventCallback OnMissingCharacter; Vector3[] m_RectTransformCorners = new Vector3[4]; float m_MarginWidth; float m_MarginHeight; float m_PreferredWidth; float m_PreferredHeight; FontAsset m_CurrentFontAsset; Material m_CurrentMaterial; int m_CurrentMaterialIndex; TextProcessingStack<MaterialReference> m_MaterialReferenceStack = new TextProcessingStack<MaterialReference>(new MaterialReference[16]); float m_Padding; SpriteAsset m_CurrentSpriteAsset; int m_TotalCharacterCount; float m_FontSize; float m_FontScaleMultiplier; float m_CurrentFontSize; TextProcessingStack<float> m_SizeStack = new TextProcessingStack<float>(16); // STYLE TAGS protected TextProcessingStack<int>[] m_TextStyleStacks = new TextProcessingStack<int>[8]; protected int m_TextStyleStackDepth = 0; FontStyles m_FontStyleInternal = FontStyles.Normal; FontStyleStack m_FontStyleStack; TextFontWeight m_FontWeightInternal = TextFontWeight.Regular; TextProcessingStack<TextFontWeight> m_FontWeightStack = new TextProcessingStack<TextFontWeight>(8); TextAlignment m_LineJustification; TextProcessingStack<TextAlignment> m_LineJustificationStack = new TextProcessingStack<TextAlignment>(16); float m_BaselineOffset; TextProcessingStack<float> m_BaselineOffsetStack = new TextProcessingStack<float>(new float[16]); Color32 m_FontColor32; Color32 m_HtmlColor; Color32 m_UnderlineColor; Color32 m_StrikethroughColor; TextProcessingStack<Color32> m_ColorStack = new TextProcessingStack<Color32>(new Color32[16]); TextProcessingStack<Color32> m_UnderlineColorStack = new TextProcessingStack<Color32>(new Color32[16]); TextProcessingStack<Color32> m_StrikethroughColorStack = new TextProcessingStack<Color32>(new Color32[16]); TextProcessingStack<Color32> m_HighlightColorStack = new TextProcessingStack<Color32>(new Color32[16]); TextProcessingStack<HighlightState> m_HighlightStateStack = new TextProcessingStack<HighlightState>(new HighlightState[16]); TextProcessingStack<int> m_ItalicAngleStack = new TextProcessingStack<int>(new int[16]); TextColorGradient m_ColorGradientPreset; TextProcessingStack<TextColorGradient> m_ColorGradientStack = new TextProcessingStack<TextColorGradient>(new TextColorGradient[16]); bool m_ColorGradientPresetIsTinted; TextProcessingStack<int> m_ActionStack = new TextProcessingStack<int>(new int[16]); float m_LineOffset; float m_LineHeight; bool m_IsDrivenLineSpacing; float m_CSpacing; float m_MonoSpacing; bool m_DuoSpace; float m_XAdvance; float m_TagLineIndent; float m_TagIndent; TextProcessingStack<float> m_IndentStack = new TextProcessingStack<float>(new float[16]); bool m_TagNoParsing; int m_CharacterCount; int m_FirstCharacterOfLine; int m_LastCharacterOfLine; int m_FirstVisibleCharacterOfLine; int m_LastVisibleCharacterOfLine; float m_MaxLineAscender; float m_MaxLineDescender; int m_LineNumber; int m_LineVisibleCharacterCount; int m_LineVisibleSpaceCount; int m_FirstOverflowCharacterIndex; int m_PageNumber; float m_MarginLeft; float m_MarginRight; float m_Width; Extents m_MeshExtents; float m_MaxCapHeight; float m_MaxAscender; float m_MaxDescender; bool m_IsNewPage; bool m_IsNonBreakingSpace; WordWrapState m_SavedWordWrapState; WordWrapState m_SavedLineState; WordWrapState m_SavedEllipsisState = new WordWrapState(); WordWrapState m_SavedLastValidState = new WordWrapState(); WordWrapState m_SavedSoftLineBreakState = new WordWrapState(); TextElementType m_TextElementType; bool m_isTextLayoutPhase; int m_SpriteIndex; Color32 m_SpriteColor; TextElement m_CachedTextElement; Color32 m_HighlightColor; float m_CharWidthAdjDelta; float m_MaxFontSize; float m_MinFontSize; int m_AutoSizeIterationCount; int m_AutoSizeMaxIterationCount = 100; float m_StartOfLineAscender; float m_LineSpacingDelta; internal MaterialReference[] m_MaterialReferences = new MaterialReference[8]; int m_SpriteCount = 0; TextProcessingStack<int> m_StyleStack = new TextProcessingStack<int>(new int[16]); TextProcessingStack<WordWrapState> m_EllipsisInsertionCandidateStack = new TextProcessingStack<WordWrapState>(8, 8); int m_SpriteAnimationId; int m_ItalicAngle; Vector3 m_FXScale; Quaternion m_FXRotation; int m_LastBaseGlyphIndex; float m_PageAscender; RichTextTagAttribute[] m_XmlAttribute = new RichTextTagAttribute[8]; private float[] m_AttributeParameterValues = new float[16]; Dictionary<int, int> m_MaterialReferenceIndexLookup = new Dictionary<int, int>(); bool m_IsCalculatingPreferredValues; bool m_TintSprite; protected SpecialCharacter m_Ellipsis; protected SpecialCharacter m_Underline; TextElementInfo[] m_InternalTextElementInfo; /// <summary> /// This is the main function that is responsible for creating / displaying the text. /// </summary> [VisibleToOtherModules("UnityEngine.UIElementsModule")] internal void GenerateTextMesh(TextGenerationSettings generationSettings, TextInfo textInfo) { // Early exit if no font asset was assigned. This should not be needed since LiberationSans SDF will be assigned by default. if (generationSettings.fontAsset == null || generationSettings.fontAsset.characterLookupTable == null) { Debug.LogWarning("Can't Generate Mesh! No Font Asset has been assigned."); return; } // Clear TextInfo if (textInfo != null) textInfo.Clear(); // Early exit if we don't have any Text to generate. if (m_TextProcessingArray == null || m_TextProcessingArray.Length == 0 || m_TextProcessingArray[0].unicode == 0) { // Clear mesh and upload changes to the mesh. ClearMesh(true, textInfo); m_PreferredWidth = 0; m_PreferredHeight = 0; return; } float fontSizeDelta = 0; // *** PHASE I of Text Generation *** ParsingPhase(textInfo, generationSettings, out uint charCode, out float maxVisibleDescender); // Check Auto Sizing and increase font size to fill text container. #region Check Auto-Sizing (Upper Font Size Bounds) fontSizeDelta = m_MaxFontSize - m_MinFontSize; if ( /* !m_isCharacterWrappingEnabled && */ generationSettings.autoSize && fontSizeDelta > 0.051f && m_FontSize < generationSettings.fontSizeMax && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount) { // Reset character width adjustment delta if (m_CharWidthAdjDelta < generationSettings.charWidthMaxAdj / 100) m_CharWidthAdjDelta = 0; m_MinFontSize = m_FontSize; float sizeDelta = Mathf.Max((m_MaxFontSize - m_FontSize) / 2, 0.05f); m_FontSize += sizeDelta; m_FontSize = Mathf.Min((int)(m_FontSize * 20 + 0.5f) / 20f, generationSettings.charWidthMaxAdj); return; } #endregion End Auto-sizing Check if (m_AutoSizeIterationCount >= m_AutoSizeMaxIterationCount) Debug.Log("Auto Size Iteration Count: " + m_AutoSizeIterationCount + ". Final Point Size: " + m_FontSize); // If there are no visible characters or only character is End of Text (0x03)... no need to continue if (m_CharacterCount == 0 || (m_CharacterCount == 1 && charCode == k_EndOfText)) { ClearMesh(true, textInfo); return; } // *** PHASE II of Text Generation *** LayoutPhase(textInfo, generationSettings, maxVisibleDescender); // Phase III - Update Mesh Vertex Data // *** UPLOAD MESH DATA *** for (int i = 1; i < textInfo.materialCount; i++) { // Clear unused vertices textInfo.meshInfo[i].ClearUnusedVertices(); // Sort the geometry of the sub-text objects if needed. if (generationSettings.geometrySortingOrder != VertexSortingOrder.Normal) textInfo.meshInfo[i].SortGeometry(VertexSortingOrder.Reverse); } } } }
UnityCsReference/Modules/TextCoreTextEngine/Managed/TextGenerator.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreTextEngine/Managed/TextGenerator.cs", "repo_id": "UnityCsReference", "token_count": 6617 }
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.Diagnostics; namespace UnityEngine.TextCore.Text { /// <summary> /// Structure used to track basic XML tags which are binary (on / off) /// </summary> internal struct FontStyleStack { public byte bold; public byte italic; public byte underline; public byte strikethrough; public byte highlight; public byte superscript; public byte subscript; public byte uppercase; public byte lowercase; public byte smallcaps; /// <summary> /// Clear the basic XML tag stack. /// </summary> public void Clear() { bold = 0; italic = 0; underline = 0; strikethrough = 0; highlight = 0; superscript = 0; subscript = 0; uppercase = 0; lowercase = 0; smallcaps = 0; } public byte Add(FontStyles style) { switch (style) { case FontStyles.Bold: bold++; return bold; case FontStyles.Italic: italic++; return italic; case FontStyles.Underline: underline++; return underline; case FontStyles.UpperCase: uppercase++; return uppercase; case FontStyles.LowerCase: lowercase++; return lowercase; case FontStyles.Strikethrough: strikethrough++; return strikethrough; case FontStyles.Superscript: superscript++; return superscript; case FontStyles.Subscript: subscript++; return subscript; case FontStyles.Highlight: highlight++; return highlight; } return 0; } public byte Remove(FontStyles style) { switch (style) { case FontStyles.Bold: if (bold > 1) bold--; else bold = 0; return bold; case FontStyles.Italic: if (italic > 1) italic--; else italic = 0; return italic; case FontStyles.Underline: if (underline > 1) underline--; else underline = 0; return underline; case FontStyles.UpperCase: if (uppercase > 1) uppercase--; else uppercase = 0; return uppercase; case FontStyles.LowerCase: if (lowercase > 1) lowercase--; else lowercase = 0; return lowercase; case FontStyles.Strikethrough: if (strikethrough > 1) strikethrough--; else strikethrough = 0; return strikethrough; case FontStyles.Highlight: if (highlight > 1) highlight--; else highlight = 0; return highlight; case FontStyles.Superscript: if (superscript > 1) superscript--; else superscript = 0; return superscript; case FontStyles.Subscript: if (subscript > 1) subscript--; else subscript = 0; return subscript; } return 0; } } /// <summary> /// Structure used to track XML tags of various types. /// </summary> /// <typeparam name="T"></typeparam> [DebuggerDisplay("Item count = {m_Count}")] internal struct TextProcessingStack<T> { public T[] itemStack; public int index; T m_DefaultItem; int m_Capacity; int m_RolloverSize; int m_Count; const int k_DefaultCapacity = 4; /// <summary> /// Constructor to create a new item stack. /// </summary> /// <param name="stack"></param> public TextProcessingStack(T[] stack) { itemStack = stack; m_Capacity = stack.Length; index = 0; m_RolloverSize = 0; m_DefaultItem = default; m_Count = 0; } /// <summary> /// Constructor for a new item stack with the given capacity. /// </summary> /// <param name="capacity"></param> public TextProcessingStack(int capacity) { itemStack = new T[capacity]; m_Capacity = capacity; index = 0; m_RolloverSize = 0; m_DefaultItem = default; m_Count = 0; } public TextProcessingStack(int capacity, int rolloverSize) { itemStack = new T[capacity]; m_Capacity = capacity; index = 0; m_RolloverSize = rolloverSize; m_DefaultItem = default; m_Count = 0; } /// <summary> /// /// </summary> public int Count { get { return m_Count; } } /// <summary> /// Returns the current item on the stack. /// </summary> public T current { get { if (index > 0) return itemStack[index - 1]; return itemStack[0]; } } /// <summary> /// /// </summary> public int rolloverSize { get { return m_RolloverSize; } set { m_RolloverSize = value; //if (m_Capacity < m_RolloverSize) // Array.Resize(ref itemStack, m_RolloverSize); } } /// <summary> /// Set stack elements to default item. /// </summary> /// <param name="stack">The stack of elements.</param> /// <param name="item"></param> internal static void SetDefault(TextProcessingStack<T>[] stack, T item) { for (int i = 0; i < stack.Length; i++) stack[i].SetDefault(item); } /// <summary> /// Function to clear and reset stack to first item. /// </summary> public void Clear() { index = 0; m_Count = 0; } /// <summary> /// Function to set the first item on the stack and reset index. /// </summary> /// <param name="item"></param> public void SetDefault(T item) { if (itemStack == null) { m_Capacity = k_DefaultCapacity; itemStack = new T[m_Capacity]; m_DefaultItem = default; } itemStack[0] = item; index = 1; m_Count = 1; } /// <summary> /// Function to add a new item to the stack. /// </summary> /// <param name="item"></param> public void Add(T item) { if (index < itemStack.Length) { itemStack[index] = item; index += 1; } } /// <summary> /// Function to retrieve an item from the stack. /// </summary> /// <returns></returns> public T Remove() { index -= 1; m_Count -= 1; if (index <= 0) { m_Count = 0; index = 1; return itemStack[0]; } return itemStack[index - 1]; } public void Push(T item) { if (index == m_Capacity) { m_Capacity *= 2; if (m_Capacity == 0) m_Capacity = k_DefaultCapacity; Array.Resize(ref itemStack, m_Capacity); } itemStack[index] = item; if (m_RolloverSize == 0) { index += 1; m_Count += 1; } else { index = (index + 1) % m_RolloverSize; m_Count = m_Count < m_RolloverSize ? m_Count + 1 : m_RolloverSize; } } public T Pop() { if (index == 0 && m_RolloverSize == 0) return default; if (m_RolloverSize == 0) index -= 1; else { index = (index - 1) % m_RolloverSize; index = index < 0 ? index + m_RolloverSize : index; } T item = itemStack[index]; itemStack[index] = m_DefaultItem; m_Count = m_Count > 0 ? m_Count - 1 : 0; return item; } /// <summary> /// /// </summary> /// <returns></returns> public T Peek() { if (index == 0) return m_DefaultItem; return itemStack[index - 1]; } /// <summary> /// Function to retrieve the current item from the stack. /// </summary> /// <returns>itemStack <T></returns> public T CurrentItem() { if (index > 0) return itemStack[index - 1]; return itemStack[0]; } /// <summary> /// Function to retrieve the previous item without affecting the stack. /// </summary> /// <returns></returns> public T PreviousItem() { if (index > 1) return itemStack[index - 2]; return itemStack[0]; } } }
UnityCsReference/Modules/TextCoreTextEngine/Managed/TextProcessingStacks.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreTextEngine/Managed/TextProcessingStacks.cs", "repo_id": "UnityCsReference", "token_count": 6102 }
456
// 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; namespace UnityEditor.TextCore.Text { [CustomPropertyDrawer(typeof(GlyphRect))] internal class GlyphRectPropertyDrawer : PropertyDrawer { private static readonly GUIContent k_GlyphRectLabel = new GUIContent("Glyph Rect", "A rectangle (rect) that represents the position of the glyph in the atlas texture."); private static readonly GUIContent k_XPropertyLabel = new GUIContent("X:", "The X coordinate of the glyph in the atlas texture."); private static readonly GUIContent k_YPropertyLabel = new GUIContent("Y:", "The Y coordinate of the glyph in the atlas texture."); private static readonly GUIContent k_WidthPropertyLabel = new GUIContent("W:", "The width of the glyph in the atlas texture."); private static readonly GUIContent k_HeightPropertyLabel = new GUIContent("H:", "The height of the glyph in the atlas texture."); public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { //EditorGUI.BeginProperty(position, label, property); SerializedProperty prop_X = property.FindPropertyRelative("m_X"); SerializedProperty prop_Y = property.FindPropertyRelative("m_Y"); SerializedProperty prop_Width = property.FindPropertyRelative("m_Width"); SerializedProperty prop_Height = property.FindPropertyRelative("m_Height"); // We get Rect since a valid position may not be provided by the caller. Rect rect = new Rect(position.x, position.y, position.width, 49); EditorGUI.LabelField(new Rect(rect.x, rect.y - 2.5f, rect.width, 18), k_GlyphRectLabel); EditorGUIUtility.labelWidth = 20f; EditorGUIUtility.fieldWidth = 20f; //GUI.enabled = false; float width = (rect.width - 75f) / 4; EditorGUI.PropertyField(new Rect(rect.x + width * 0, rect.y + 20, width - 5f, 18), prop_X, k_XPropertyLabel); EditorGUI.PropertyField(new Rect(rect.x + width * 1, rect.y + 20, width - 5f, 18), prop_Y, k_YPropertyLabel); EditorGUI.PropertyField(new Rect(rect.x + width * 2, rect.y + 20, width - 5f, 18), prop_Width, k_WidthPropertyLabel); EditorGUI.PropertyField(new Rect(rect.x + width * 3, rect.y + 20, width - 5f, 18), prop_Height, k_HeightPropertyLabel); //EditorGUI.EndProperty(); } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return 45f; } } }
UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/PropertyDrawers/GlyphRectPropertyDrawer.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/PropertyDrawers/GlyphRectPropertyDrawer.cs", "repo_id": "UnityCsReference", "token_count": 1016 }
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.Collections.Generic; using UnityEngine; using UnityEngine.TextCore.Text; namespace UnityEditor.TextCore.Text { internal static class TM_EditorStyles { public static GUIStyle panelTitle; public static GUIStyle sectionHeader; public static GUIStyle textAreaBoxWindow; public static GUIStyle label; public static GUIStyle leftLabel; public static GUIStyle centeredLabel; public static GUIStyle rightLabel; public static Texture2D sectionHeaderStyleTexture; static TM_EditorStyles() { // Section Header CreateSectionHeaderStyle(); // Labels panelTitle = new GUIStyle(EditorStyles.label) { fontStyle = FontStyle.Bold }; label = leftLabel = new GUIStyle(EditorStyles.label) { alignment = TextAnchor.MiddleLeft, richText = true, wordWrap = true, stretchWidth = true }; centeredLabel = new GUIStyle(EditorStyles.label) { alignment = TextAnchor.MiddleCenter, richText = true, wordWrap = true, stretchWidth = true }; rightLabel = new GUIStyle(EditorStyles.label) { alignment = TextAnchor.MiddleRight, richText = true, wordWrap = true, stretchWidth = true }; textAreaBoxWindow = new GUIStyle(EditorStyles.textArea) { richText = true }; } internal static void CreateSectionHeaderStyle() { sectionHeader = new GUIStyle(EditorStyles.textArea) { fixedHeight = 22, richText = true, overflow = new RectOffset(9, 0, 0, 0), padding = new RectOffset(0, 0, 4, 0) }; sectionHeaderStyleTexture = new Texture2D(1, 1); if (EditorGUIUtility.isProSkin) sectionHeaderStyleTexture.SetPixel(1, 1, new Color(0.4f, 0.4f, 0.4f, 0.5f)); else sectionHeaderStyleTexture.SetPixel(1, 1, new Color(0.6f, 0.6f, 0.6f, 0.5f)); sectionHeaderStyleTexture.Apply(); sectionHeader.normal.background = sectionHeaderStyleTexture; } internal static void RefreshEditorStyles() { if (sectionHeader.normal.background == null) { Texture2D sectionHeaderStyleTexture = new Texture2D(1, 1); if (EditorGUIUtility.isProSkin) sectionHeaderStyleTexture.SetPixel(1, 1, new Color(0.4f, 0.4f, 0.4f, 0.5f)); else sectionHeaderStyleTexture.SetPixel(1, 1, new Color(0.6f, 0.6f, 0.6f, 0.5f)); sectionHeaderStyleTexture.Apply(); sectionHeader.normal.background = sectionHeaderStyleTexture; } } } internal class TextCoreEditorUtilities { /// <summary> /// Function which returns a string containing a sequence of Decimal character ranges. /// </summary> /// <param name="characterSet"></param> /// <returns></returns> internal static string GetDecimalCharacterSequence(int[] characterSet) { if (characterSet == null || characterSet.Length == 0) return string.Empty; string characterSequence = string.Empty; int count = characterSet.Length; int first = characterSet[0]; int last = first; for (int i = 1; i < count; i++) { if (characterSet[i - 1] + 1 == characterSet[i]) { last = characterSet[i]; } else { if (first == last) characterSequence += first + ","; else characterSequence += first + "-" + last + ","; first = last = characterSet[i]; } } // handle the final group if (first == last) characterSequence += first; else characterSequence += first + "-" + last; return characterSequence; } /// <summary> /// Function which returns a string containing a sequence of Unicode (Hex) character ranges. /// </summary> /// <param name="characterSet"></param> /// <returns></returns> internal static string GetUnicodeCharacterSequence(int[] characterSet) { if (characterSet == null || characterSet.Length == 0) return string.Empty; string characterSequence = string.Empty; int count = characterSet.Length; int first = characterSet[0]; int last = first; for (int i = 1; i < count; i++) { if (characterSet[i - 1] + 1 == characterSet[i]) { last = characterSet[i]; } else { if (first == last) characterSequence += first.ToString("X2") + ","; else characterSequence += first.ToString("X2") + "-" + last.ToString("X2") + ","; first = last = characterSet[i]; } } // handle the final group if (first == last) characterSequence += first.ToString("X2"); else characterSequence += first.ToString("X2") + "-" + last.ToString("X2"); return characterSequence; } internal static Material[] FindMaterialReferences(FontAsset fontAsset) { List<Material> refs = new List<Material>(); Material mat = fontAsset.material; refs.Add(mat); // Get materials matching the search pattern. string searchPattern = "t:Material" + " " + fontAsset.name.Split(new char[] { ' ' })[0]; string[] materialAssetGUIDs = AssetDatabase.FindAssets(searchPattern); for (int i = 0; i < materialAssetGUIDs.Length; i++) { string materialPath = AssetDatabase.GUIDToAssetPath(materialAssetGUIDs[i]); Material targetMaterial = AssetDatabase.LoadAssetAtPath<Material>(materialPath); if (targetMaterial.HasProperty(TextShaderUtilities.ID_MainTex) && targetMaterial.GetTexture(TextShaderUtilities.ID_MainTex) != null && mat.GetTexture(TextShaderUtilities.ID_MainTex) != null && targetMaterial.GetTexture(TextShaderUtilities.ID_MainTex).GetInstanceID() == mat.GetTexture(TextShaderUtilities.ID_MainTex).GetInstanceID()) { if (!refs.Contains(targetMaterial)) refs.Add(targetMaterial); } else { // TODO: Find a more efficient method to unload resources. //Resources.UnloadAsset(targetMaterial.GetTexture(TextShaderUtilities.ID_MainTex)); } } return refs.ToArray(); } /// <summary> /// /// </summary> /// <param name="rect"></param> /// <param name="thickness"></param> /// <param name="color"></param> internal static void DrawBox(Rect rect, float thickness, Color color) { EditorGUI.DrawRect(new Rect(rect.x - thickness, rect.y + thickness, rect.width + thickness * 2, thickness), color); EditorGUI.DrawRect(new Rect(rect.x - thickness, rect.y + thickness, thickness, rect.height - thickness * 2), color); EditorGUI.DrawRect(new Rect(rect.x - thickness, rect.y + rect.height - thickness * 2, rect.width + thickness * 2, thickness), color); EditorGUI.DrawRect(new Rect(rect.x + rect.width, rect.y + thickness, thickness, rect.height - thickness * 2), color); } /// <summary> /// Function to return the horizontal alignment grid value. /// </summary> /// <param name="value"></param> /// <returns></returns> internal static int GetHorizontalAlignmentGridValue(int value) { if ((value & 0x1) == 0x1) return 0; else if ((value & 0x2) == 0x2) return 1; else if ((value & 0x4) == 0x4) return 2; else if ((value & 0x8) == 0x8) return 3; else if ((value & 0x10) == 0x10) return 4; else if ((value & 0x20) == 0x20) return 5; return 0; } /// <summary> /// Function to return the vertical alignment grid value. /// </summary> /// <param name="value"></param> /// <returns></returns> internal static int GetVerticalAlignmentGridValue(int value) { if ((value & 0x100) == 0x100) return 0; if ((value & 0x200) == 0x200) return 1; if ((value & 0x400) == 0x400) return 2; if ((value & 0x800) == 0x800) return 3; if ((value & 0x1000) == 0x1000) return 4; if ((value & 0x2000) == 0x2000) return 5; return 0; } internal static void DrawColorProperty(Rect rect, SerializedProperty property) { int oldIndent = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; if (EditorGUIUtility.wideMode) { EditorGUI.PropertyField(new Rect(rect.x, rect.y, 50f, rect.height), property, GUIContent.none); rect.x += 50f; rect.width = Mathf.Min(100f, rect.width - 55f); } else { rect.height /= 2f; rect.width = Mathf.Min(100f, rect.width - 5f); EditorGUI.PropertyField(rect, property, GUIContent.none); rect.y += rect.height; } EditorGUI.BeginChangeCheck(); string colorString = EditorGUI.TextField(rect, string.Format("#{0}", ColorUtility.ToHtmlStringRGBA(property.colorValue))); if (EditorGUI.EndChangeCheck()) { Color color; if (ColorUtility.TryParseHtmlString(colorString, out color)) { property.colorValue = color; } } EditorGUI.indentLevel = oldIndent; } internal static bool EditorToggle(Rect position, bool value, GUIContent content, GUIStyle style) { var id = GUIUtility.GetControlID(content, FocusType.Keyboard, position); var evt = Event.current; // Toggle selected toggle on space or return key if (GUIUtility.keyboardControl == id && evt.type == EventType.KeyDown && (evt.keyCode == KeyCode.Space || evt.keyCode == KeyCode.Return || evt.keyCode == KeyCode.KeypadEnter)) { value = !value; evt.Use(); GUI.changed = true; } if (evt.type == EventType.MouseDown && position.Contains(Event.current.mousePosition)) { GUIUtility.keyboardControl = id; EditorGUIUtility.editingTextField = false; HandleUtility.Repaint(); } return GUI.Toggle(position, id, value, content, style); } } }
UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/TextCoreEditorUtilities.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/TextCoreEditorUtilities.cs", "repo_id": "UnityCsReference", "token_count": 5559 }
458
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEngine.Bindings; namespace UnityEditor { public enum FontTextureCase { Dynamic = -2, Unicode = -1, [InspectorName("ASCII default set")] ASCII = 0, ASCIIUpperCase = 1, ASCIILowerCase = 2, CustomSet = 3 } public enum FontRenderingMode { Smooth = 0, HintedSmooth = 1, HintedRaster = 2, OSDefault = 3, } public enum AscentCalculationMode { [InspectorName("Legacy version 2 mode (glyph bounding boxes)")] Legacy2x = 0, [InspectorName("Face ascender metric")] FaceAscender = 1, [InspectorName("Face bounding box metric")] FaceBoundingBox = 2 } [NativeHeader("Modules/TextRenderingEditor/TrueTypeFontImporter.h")] public sealed class TrueTypeFontImporter : AssetImporter { public extern int fontSize { get; set; } public extern bool includeFontData { get; set; } public extern AscentCalculationMode ascentCalculationMode { get; set; } public extern string customCharacters { get; set; } public extern int characterSpacing { get; set; } public extern int characterPadding { get; set; } public extern FontRenderingMode fontRenderingMode { get; set; } public extern bool shouldRoundAdvanceValue { get; set; } [NativeProperty("FontNameFromTTFData", false, TargetType.Function)] public extern string fontTTFName { get; } [NativeProperty("ForceTextureCase", false, TargetType.Function)] public extern FontTextureCase fontTextureCase { get; set; } [NativeProperty("MarshalledFontReferences", false, TargetType.Function)] public extern Font[] fontReferences { [return:Unmarshalled] get; [param:Unmarshalled] set; } [NativeProperty("MarshalledFontNames", false, TargetType.Function)] public extern string[] fontNames { [return:Unmarshalled] get; [param:Unmarshalled] set; } internal extern bool IsFormatSupported(); public extern Font GenerateEditableFont(string path); internal extern Font[] MarshalledLookupFallbackFontReferences([Unmarshalled] string[] names); internal Font[] LookupFallbackFontReferences([Unmarshalled] string[] names) { return MarshalledLookupFallbackFontReferences(names); } } }
UnityCsReference/Modules/TextRenderingEditor/TrueTypeFontImporter.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/TextRenderingEditor/TrueTypeFontImporter.bindings.cs", "repo_id": "UnityCsReference", "token_count": 947 }
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.Collections; using System; using UnityEngine; namespace TreeEditor { /* Perlin noise use example: Perlin perlin = new Perlin(); var value : float = perlin.Noise(2); var value : float = perlin.Noise(2, 3, ); var value : float = perlin.Noise(2, 3, 4); SmoothRandom use example: var p = SmoothRandom.GetVector3(3); */ public class SmoothRandom { public static Vector3 GetVector3(float speed) { float time = Time.time * 0.01F * speed; return new Vector3(Get().HybridMultifractal(time, 15.73F, 0.58F), Get().HybridMultifractal(time, 63.94F, 0.58F), Get().HybridMultifractal(time, 0.2F, 0.58F)); } public static float Get(float speed) { float time = Time.time * 0.01F * speed; return Get().HybridMultifractal(time * 0.01F, 15.7F, 0.65F); } private static FractalNoise Get() { if (s_Noise == null) s_Noise = new FractalNoise(1.27F, 2.04F, 8.36F); return s_Noise; } private static FractalNoise s_Noise; } public class Perlin { // Original C code derived from // http://astronomy.swin.edu.au/~pbourke/texture/perlin/perlin.c // http://astronomy.swin.edu.au/~pbourke/texture/perlin/perlin.h const int B = 0x100; const int BM = 0xff; const int N = 0x1000; int[] p = new int[B + B + 2]; float[,] g3 = new float[B + B + 2, 3]; float[,] g2 = new float[B + B + 2, 2]; float[] g1 = new float[B + B + 2]; float s_curve(float t) { return t * t * (3.0F - 2.0F * t); } float lerp(float t, float a, float b) { return a + t * (b - a); } void setup(float value, out int b0, out int b1, out float r0, out float r1) { float t = value + N; b0 = ((int)t) & BM; b1 = (b0 + 1) & BM; r0 = t - (int)t; r1 = r0 - 1.0F; } float at2(float rx, float ry, float x, float y) { return rx * x + ry * y; } float at3(float rx, float ry, float rz, float x, float y, float z) { return rx * x + ry * y + rz * z; } public float Noise(float arg) { int bx0, bx1; float rx0, rx1, sx, u, v; setup(arg, out bx0, out bx1, out rx0, out rx1); sx = s_curve(rx0); u = rx0 * g1[p[bx0]]; v = rx1 * g1[p[bx1]]; return (lerp(sx, u, v)); } public float Noise(float x, float y) { int bx0, bx1, by0, by1, b00, b10, b01, b11; float rx0, rx1, ry0, ry1, sx, sy, a, b, u, v; int i, j; setup(x, out bx0, out bx1, out rx0, out rx1); setup(y, out by0, out by1, out ry0, out ry1); i = p[bx0]; j = p[bx1]; b00 = p[i + by0]; b10 = p[j + by0]; b01 = p[i + by1]; b11 = p[j + by1]; sx = s_curve(rx0); sy = s_curve(ry0); u = at2(rx0, ry0, g2[b00, 0], g2[b00, 1]); v = at2(rx1, ry0, g2[b10, 0], g2[b10, 1]); a = lerp(sx, u, v); u = at2(rx0, ry1, g2[b01, 0], g2[b01, 1]); v = at2(rx1, ry1, g2[b11, 0], g2[b11, 1]); b = lerp(sx, u, v); return lerp(sy, a, b); } public float Noise(float x, float y, float z) { int bx0, bx1, by0, by1, bz0, bz1, b00, b10, b01, b11; float rx0, rx1, ry0, ry1, rz0, rz1, sy, sz, a, b, c, d, t, u, v; int i, j; setup(x, out bx0, out bx1, out rx0, out rx1); setup(y, out by0, out by1, out ry0, out ry1); setup(z, out bz0, out bz1, out rz0, out rz1); i = p[bx0]; j = p[bx1]; b00 = p[i + by0]; b10 = p[j + by0]; b01 = p[i + by1]; b11 = p[j + by1]; t = s_curve(rx0); sy = s_curve(ry0); sz = s_curve(rz0); u = at3(rx0, ry0, rz0, g3[b00 + bz0, 0], g3[b00 + bz0, 1], g3[b00 + bz0, 2]); v = at3(rx1, ry0, rz0, g3[b10 + bz0, 0], g3[b10 + bz0, 1], g3[b10 + bz0, 2]); a = lerp(t, u, v); u = at3(rx0, ry1, rz0, g3[b01 + bz0, 0], g3[b01 + bz0, 1], g3[b01 + bz0, 2]); v = at3(rx1, ry1, rz0, g3[b11 + bz0, 0], g3[b11 + bz0, 1], g3[b11 + bz0, 2]); b = lerp(t, u, v); c = lerp(sy, a, b); u = at3(rx0, ry0, rz1, g3[b00 + bz1, 0], g3[b00 + bz1, 2], g3[b00 + bz1, 2]); v = at3(rx1, ry0, rz1, g3[b10 + bz1, 0], g3[b10 + bz1, 1], g3[b10 + bz1, 2]); a = lerp(t, u, v); u = at3(rx0, ry1, rz1, g3[b01 + bz1, 0], g3[b01 + bz1, 1], g3[b01 + bz1, 2]); v = at3(rx1, ry1, rz1, g3[b11 + bz1, 0], g3[b11 + bz1, 1], g3[b11 + bz1, 2]); b = lerp(t, u, v); d = lerp(sy, a, b); return lerp(sz, c, d); } void normalize2(ref float x, ref float y) { float s; s = (float)Math.Sqrt(x * x + y * y); x = x / s; y = y / s; } void normalize3(ref float x, ref float y, ref float z) { float s; s = (float)Math.Sqrt(x * x + y * y + z * z); x = x / s; y = y / s; z = z / s; } public Perlin() { SetSeed(0); } public void SetSeed(int seed) { int i, j, k; System.Random rnd = new System.Random(seed); for (i = 0; i < B; i++) { p[i] = i; g1[i] = (float)(rnd.Next(B + B) - B) / B; for (j = 0; j < 2; j++) g2[i, j] = (float)(rnd.Next(B + B) - B) / B; normalize2(ref g2[i, 0], ref g2[i, 1]); for (j = 0; j < 3; j++) g3[i, j] = (float)(rnd.Next(B + B) - B) / B; normalize3(ref g3[i, 0], ref g3[i, 1], ref g3[i, 2]); } while (--i != 0) { k = p[i]; p[i] = p[j = rnd.Next(B)]; p[j] = k; } for (i = 0; i < B + 2; i++) { p[B + i] = p[i]; g1[B + i] = g1[i]; for (j = 0; j < 2; j++) g2[B + i, j] = g2[i, j]; for (j = 0; j < 3; j++) g3[B + i, j] = g3[i, j]; } } } public class FractalNoise { public FractalNoise(float inH, float inLacunarity, float inOctaves) : this(inH, inLacunarity, inOctaves, null) { } public FractalNoise(float inH, float inLacunarity, float inOctaves, Perlin noise) { m_Lacunarity = inLacunarity; m_Octaves = inOctaves; m_IntOctaves = (int)inOctaves; m_Exponent = new float[m_IntOctaves + 1]; float frequency = 1.0F; for (int i = 0; i < m_IntOctaves + 1; i++) { m_Exponent[i] = (float)Math.Pow(m_Lacunarity, -inH); frequency *= m_Lacunarity; } if (noise == null) m_Noise = new Perlin(); else m_Noise = noise; } public float HybridMultifractal(float x, float y, float offset) { float weight, signal, remainder, result; result = (m_Noise.Noise(x, y) + offset) * m_Exponent[0]; weight = result; x *= m_Lacunarity; y *= m_Lacunarity; int i; for (i = 1; i < m_IntOctaves; i++) { if (weight > 1.0F) weight = 1.0F; signal = (m_Noise.Noise(x, y) + offset) * m_Exponent[i]; result += weight * signal; weight *= signal; x *= m_Lacunarity; y *= m_Lacunarity; } remainder = m_Octaves - m_IntOctaves; result += remainder * m_Noise.Noise(x, y) * m_Exponent[i]; return result; } public float RidgedMultifractal(float x, float y, float offset, float gain) { float weight, signal, result; int i; signal = Mathf.Abs(m_Noise.Noise(x, y)); signal = offset - signal; signal *= signal; result = signal; weight = 1.0F; for (i = 1; i < m_IntOctaves; i++) { x *= m_Lacunarity; y *= m_Lacunarity; weight = signal * gain; weight = Mathf.Clamp01(weight); signal = Mathf.Abs(m_Noise.Noise(x, y)); signal = offset - signal; signal *= signal; signal *= weight; result += signal * m_Exponent[i]; } return result; } public float BrownianMotion(float x, float y) { float value, remainder; long i; value = 0.0F; for (i = 0; i < m_IntOctaves; i++) { value = m_Noise.Noise(x, y) * m_Exponent[i]; x *= m_Lacunarity; y *= m_Lacunarity; } remainder = m_Octaves - m_IntOctaves; value += remainder * m_Noise.Noise(x, y) * m_Exponent[i]; return value; } private Perlin m_Noise; private float[] m_Exponent; private int m_IntOctaves; private float m_Octaves; private float m_Lacunarity; } /* /// This is an alternative implementation of perlin noise public class Noise { public float Noise(float x) { return Noise(x, 0.5F); } public float Noise(float x, float y) { int Xint = (int)x; int Yint = (int)y; float Xfrac = x - Xint; float Yfrac = y - Yint; float x0y0 = Smooth_Noise(Xint, Yint); //find the noise values of the four corners float x1y0 = Smooth_Noise(Xint+1, Yint); float x0y1 = Smooth_Noise(Xint, Yint+1); float x1y1 = Smooth_Noise(Xint+1, Yint+1); //interpolate between those values according to the x and y fractions float v1 = Interpolate(x0y0, x1y0, Xfrac); //interpolate in x direction (y) float v2 = Interpolate(x0y1, x1y1, Xfrac); //interpolate in x direction (y+1) float fin = Interpolate(v1, v2, Yfrac); //interpolate in y direction return fin; } private float Interpolate(float x, float y, float a) { float b = 1-a; float fac1 = (float)(3*b*b - 2*b*b*b); float fac2 = (float)(3*a*a - 2*a*a*a); return x*fac1 + y*fac2; //add the weighted factors } private float GetRandomValue(int x, int y) { x = (x+m_nNoiseWidth) % m_nNoiseWidth; y = (y+m_nNoiseHeight) % m_nNoiseHeight; float fVal = (float)m_aNoise[(int)(m_fScaleX*x), (int)(m_fScaleY*y)]; return fVal/255*2-1f; } private float Smooth_Noise(int x, int y) { float corners = ( Noise2d(x-1, y-1) + Noise2d(x+1, y-1) + Noise2d(x-1, y+1) + Noise2d(x+1, y+1) ) / 16.0f; float sides = ( Noise2d(x-1, y) +Noise2d(x+1, y) + Noise2d(x, y-1) + Noise2d(x, y+1) ) / 8.0f; float center = Noise2d(x, y) / 4.0f; return corners + sides + center; } private float Noise2d(int x, int y) { x = (x+m_nNoiseWidth) % m_nNoiseWidth; y = (y+m_nNoiseHeight) % m_nNoiseHeight; float fVal = (float)m_aNoise[(int)(m_fScaleX*x), (int)(m_fScaleY*y)]; return fVal/255*2-1f; } public Noise() { m_nNoiseWidth = 100; m_nNoiseHeight = 100; m_fScaleX = 1.0F; m_fScaleY = 1.0F; System.Random rnd = new System.Random(); m_aNoise = new int[m_nNoiseWidth,m_nNoiseHeight]; for (int x = 0; x<m_nNoiseWidth; x++) { for (int y = 0; y<m_nNoiseHeight; y++) { m_aNoise[x,y] = rnd.Next(255); } } } private int[,] m_aNoise; protected int m_nNoiseWidth, m_nNoiseHeight; private float m_fScaleX, m_fScaleY; } /* Yet another perlin noise implementation. This one is not even completely ported to C# float noise1[]; float noise2[]; float noise3[]; int indices[]; float PerlinSmoothStep (float t) { return t * t * (3.0f - 2.0f * t); } float PerlinLerp(float t, float a, float b) { return a + t * (b - a); } float PerlinRand() { return Random.rand () / float(RAND_MAX) * 2.0f - 1.0f; } PerlinNoise::PerlinNoise () { long i, j, k; float x, y, z, denom; Random rnd = new Random(); noise1 = new float[1 * (PERLIN_B + PERLIN_B + 2)]; noise2 = new float[2 * (PERLIN_B + PERLIN_B + 2)]; noise3 = new float[3 * (PERLIN_B + PERLIN_B + 2)]; indices = new long[PERLIN_B + PERLIN_B + 2]; for (i = 0; i < PERLIN_B; i++) { indices[i] = i; x = PerlinRand(); y = PerlinRand(); z = PerlinRand(); noise1[i] = x; denom = sqrt(x * x + y * y); if (denom > 0.0001f) denom = 1.0f / denom; j = i << 1; noise2[j + 0] = x * denom; noise2[j + 1] = y * denom; denom = sqrt(x * x + y * y + z * z); if (denom > 0.0001f) denom = 1.0f / denom; j += i; noise3[j + 0] = x * denom; noise3[j + 1] = y * denom; noise3[j + 2] = z * denom; } while (--i != 0) { j = rand() & PERLIN_BITMASK; std::swap (indices[i], indices[j]); } for (i = 0; i < PERLIN_B + 2; i++) { j = i + PERLIN_B; indices[j] = indices[i]; noise1[j] = noise1[i]; j = j << 1; k = i << 1; noise2[j + 0] = noise2[k + 0]; noise2[j + 1] = noise2[k + 1]; j += i + PERLIN_B; k += i + PERLIN_B; noise3[j + 0] = noise3[k + 0]; noise3[j + 1] = noise3[k + 1]; noise3[j + 2] = noise3[k + 2]; } } PerlinNoise::~PerlinNoise () { delete []noise1; delete []noise2; delete []noise3; delete []indices; } void PerlinSetup (float v, long& b0, long& b1, float& r0, float& r1); void PerlinSetup( float v, long& b0, long& b1, float& r0, float& r1) { v += PERLIN_N; long vInt = (long)v; b0 = vInt & PERLIN_BITMASK; b1 = (b0 + 1) & PERLIN_BITMASK; r0 = v - (float)vInt; r1 = r0 - 1.0f; } float PerlinNoise::Noise1 (float x) { long bx0, bx1; float rx0, rx1, sx, u, v; PerlinSetup(x, bx0, bx1, rx0, rx1); sx = PerlinSmoothStep(rx0); u = rx0 * noise1[indices[bx0]]; v = rx1 * noise1[indices[bx1]]; return PerlinLerp (sx, u, v); } float PerlinNoise::Noise2(float x, float y) { long bx0, bx1, by0, by1, b00, b01, b10, b11; float rx0, rx1, ry0, ry1, sx, sy, u, v, a, b; PerlinSetup (x, bx0, bx1, rx0, rx1); PerlinSetup (y, by0, by1, ry0, ry1); sx = PerlinSmoothStep (rx0); sy = PerlinSmoothStep (ry0); b00 = indices[indices[bx0] + by0] << 1; b10 = indices[indices[bx1] + by0] << 1; b01 = indices[indices[bx0] + by1] << 1; b11 = indices[indices[bx1] + by1] << 1; u = rx0 * noise2[b00 + 0] + ry0 * noise2[b00 + 1]; v = rx1 * noise2[b10 + 0] + ry0 * noise2[b10 + 1]; a = PerlinLerp (sx, u, v); u = rx0 * noise2[b01 + 0] + ry1 * noise2[b01 + 1]; v = rx1 * noise2[b11 + 0] + ry1 * noise2[b11 + 1]; b = PerlinLerp (sx, u, v); u = PerlinLerp (sy, a, b); return u; } float PerlinNoise::Noise3(float x, float y, float z) { long bx0, bx1, by0, by1, bz0, bz1, b00, b10, b01, b11; float rx0, rx1, ry0, ry1, rz0, rz1, *q, sy, sz, a, b, c, d, t, u, v; PerlinSetup (x, bx0, bx1, rx0, rx1); PerlinSetup (y, by0, by1, ry0, ry1); PerlinSetup (z, bz0, bz1, rz0, rz1); b00 = indices[indices[bx0] + by0] << 1; b10 = indices[indices[bx1] + by0] << 1; b01 = indices[indices[bx0] + by1] << 1; b11 = indices[indices[bx1] + by1] << 1; t = PerlinSmoothStep (rx0); sy = PerlinSmoothStep (ry0); sz = PerlinSmoothStep (rz0); #define at3(rx,ry,rz) ( rx * q[0] + ry * q[1] + rz * q[2] ) q = &noise3[b00 + bz0]; u = at3(rx0,ry0,rz0); q = &noise3[b10 + bz0]; v = at3(rx1,ry0,rz0); a = PerlinLerp(t, u, v); q = &noise3[b01 + bz0]; u = at3(rx0,ry1,rz0); q = &noise3[b11 + bz0]; v = at3(rx1,ry1,rz0); b = PerlinLerp(t, u, v); c = PerlinLerp(sy, a, b); q = &noise3[b00 + bz1]; u = at3(rx0,ry0,rz1); q = &noise3[b10 + bz1]; v = at3(rx1,ry0,rz1); a = PerlinLerp(t, u, v); q = &noise3[b01 + bz1]; u = at3(rx0,ry1,rz1); q = &noise3[b11 + bz1]; v = at3(rx1,ry1,rz1); b = PerlinLerp(t, u, v); d = PerlinLerp(sy, a, b); return PerlinLerp (sz, c, d); } */ }
UnityCsReference/Modules/TreeEditor/Includes/Perlin.cs/0
{ "file_path": "UnityCsReference/Modules/TreeEditor/Includes/Perlin.cs", "repo_id": "UnityCsReference", "token_count": 11461 }
460
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor.AnimatedValues; using UnityEngine; using UnityEngine.Profiling; using UnityEngine.Scripting; using UnityEditor; using UnityEditor.SceneManagement; using System.Collections.Generic; namespace TreeEditor { [CustomEditor(typeof(Tree))] internal class TreeEditor : Editor { private enum PropertyType { Normal = 0, FullUndo = 1, FullUpdate = 2, FullUndoUpdate = 3 } public enum EditMode { None = -1, MoveNode = 0, RotateNode = 1, Freehand = 2, Parameter = 3, Everything = 4, Delete = 5, CreateGroup = 6, Duplicate = 7 } private static Vector3 s_StartPosition; private static int s_SelectedPoint = -1; private static TreeNode s_SelectedNode; private static TreeGroup s_SelectedGroup; private static string[] geometryModeOptions = { L10n.Tr("Plane|"), L10n.Tr("Cross|"), L10n.Tr("TriCross|"), L10n.Tr("Billboard|"), L10n.Tr("Mesh|") }; private static string createNewTreeString = L10n.Tr("Create New Tree"); private static string createWindZoneString = L10n.Tr("Create Wind Zone"); private static string[] toolbarIconStringsBranch = { "TreeEditor.BranchTranslate", "TreeEditor.BranchRotate", "TreeEditor.BranchFreeHand", }; private static string[] toolbarContentStringsBranch = { L10n.Tr("Move Branch|Select a branch spline point and drag to move it."), L10n.Tr("Rotate Branch|Select a branch spline point and drag to rotate it."), L10n.Tr("Free Hand|Click on a branch spline node and drag to draw a new shape.") }; private static string[] toolbarIconStringsLeaf = { "TreeEditor.LeafTranslate", "TreeEditor.LeafRotate", }; private static string[] toolbarContentStringsLeaf = { L10n.Tr("Move Leaf|Select a leaf spline point and drag to move it."), L10n.Tr("Rotate Leaf|Select a leaf spline point and drag to rotate it.") }; private static string[] inspectorDistributionPopupOptions = { L10n.Tr("Random|"), L10n.Tr("Alternate|"), L10n.Tr("Opposite|"), L10n.Tr("Whorled|") }; private static string treeSeedString = L10n.Tr("Tree Seed|The global seed that affects the entire tree. Use it to randomize your tree, while keeping the general structure of it."); private static string areaSpreadString = L10n.Tr("Area Spread|Adjusts the spread of trunk nodes. Has an effect only if you have more than one trunk."); private static string groundOffsetString = L10n.Tr("Ground Offset|Adjusts the offset of trunk nodes on Y axis."); private static string lodQualityString = L10n.Tr("LOD Quality|Defines the level-of-detail for the entire tree. A low value will make the tree less complex, a high value will make the tree more complex. Check the statistics in the hierarchy view to see the current complexity of the mesh."); private static string ambientOcclusionString = L10n.Tr("Ambient Occlusion|Toggles ambient occlusion on or off."); private static string aoDensityString = L10n.Tr("AO Density|Adjusts the density of ambient occlusion."); private static string translucencyColorString = L10n.Tr("Translucency Color|The color that will be multiplied in when the leaves are backlit."); private static string transViewDepString = L10n.Tr("Trans. View Dep.|Translucency view dependency. Fully view dependent translucency is relative to the angle between the view direction and the light direction. View independent is relative to the angle between the leaf's normal vector and the light direction."); private static string alphaCutoffString = L10n.Tr("Alpha Cutoff|Alpha values from the base texture smaller than the alpha cutoff are clipped creating a cutout."); private static string shadowStrengthString = L10n.Tr("Shadow Strength|Makes the shadows on the leaves less harsh. Since it scales all the shadowing that the leaves receive, it should be used with care for trees that are e.g. in a shadow of a mountain."); private static string shadowOffsetString = L10n.Tr("Shadow Offset|Scales the values from the Shadow Offset texture set in the source material. It is used to offset the position of the leaves when collecting the shadows, so that the leaves appear as if they were not placed on one quad. It's especially important for billboarded leaves and they should have brighter values in the center of the texture and darker ones at the border. Start out with a black texture and add different shades of gray per leaf."); private static string[] leafMaterialOptions = { L10n.Tr("Full Res|"), L10n.Tr("Half Res|"), L10n.Tr("Quarter Res|"), L10n.Tr("One-8th Res|"), L10n.Tr("One-16th Res|") }; private static string shadowCasterResString = L10n.Tr("Shadow Caster Res.|Defines the resolution of the texture atlas containing alpha values from source diffuse textures. The atlas is used when the leaves are rendered as shadow casters. Using lower resolution might increase performance."); private static string lodMultiplierString = L10n.Tr("LOD Multiplier|Adjusts the quality of this group relative to tree's LOD Quality, so that it is of either higher or lower quality than the rest of the tree."); private static string[] categoryNamesOptions = { L10n.Tr("Branch Only|"), L10n.Tr("Branch + Fronds|"), L10n.Tr("Fronds Only|") }; private static string geometryModeString = L10n.Tr("Geometry Mode|Type of geometry for this branch group."); private static string branchMaterialString = L10n.Tr("Branch Material|The primary material for the branches."); private static string breakMaterialString = L10n.Tr("Break Material|Material for capping broken branches."); private static string frondMaterialString = L10n.Tr("Frond Material|Material for the fronds."); private static string lengthString = L10n.Tr("Length|Adjusts the length of the branches."); private static string relativeLengthString = L10n.Tr("Relative Length|Determines whether the radius of a branch is affected by its length."); private static string radiusString = L10n.Tr("Radius|Adjusts the radius of the branches, use the curve to fine-tune the radius along the length of the branches."); private static string capSmoothingString = L10n.Tr("Cap Smoothing|Defines the roundness of the cap/tip of the branches. Useful for cacti."); private static string crinklynessString = L10n.Tr("Crinkliness|Adjusts how crinkly/crooked the branches are, use the curve to fine-tune."); private static string seekSunString = L10n.Tr("Seek Sun|Use the curve to adjust how the branches are bent upwards/downwards and the slider to change the scale."); private static string noiseString = L10n.Tr("Noise|Overall noise factor, use the curve to fine-tune."); private static string noiseScaleUString = L10n.Tr("Noise Scale U|Scale of the noise around the branch, lower values will give a more wobbly look, while higher values gives a more stochastic look."); private static string noiseScaleVString = L10n.Tr("Noise Scale V|Scale of the noise along the branch, lower values will give a more wobbly look, while higher values gives a more stochastic look."); private static string flareRadiusString = L10n.Tr("Flare Radius|The radius of the flares, this is added to the main radius, so a zero value means no flares."); private static string flareHeightString = L10n.Tr("Flare Height|Defines how far up the trunk the flares start."); private static string flareNoiseString = L10n.Tr("Flare Noise|Defines the noise of the flares, lower values will give a more wobbly look, while higher values gives a more stochastic look."); private static string weldLengthString = L10n.Tr("Weld Length|Defines how far up the branch the weld spread starts."); private static string spreadTopString = L10n.Tr("Spread Top|Weld's spread factor on the top-side of the branch, relative to its parent branch. Zero means no spread."); private static string spreadBottomString = L10n.Tr("Spread Bottom|Weld's spread factor on the bottom-side of the branch, relative to its parent branch. Zero means no spread."); private static string breakChanceString = L10n.Tr("Break Chance|Chance of a branch breaking, i.e. 0 = no branches are broken, 0.5 = half of the branches are broken, 1.0 = all the branches are broken."); private static string breakLocationString = L10n.Tr("Break Location|This range defines where the branches will be broken. Relative to the length of the branch."); private static string frondCountString = L10n.Tr("Frond Count|Defines the number of fronds per branch. Fronds are always evenly spaced around the branch."); private static string frondWidthString = L10n.Tr("Frond Width|The width of the fronds, use the curve to adjust the specific shape along the length of the branch."); private static string frondRangeString = L10n.Tr("Frond Range|Defines the starting and ending point of the fronds."); private static string frondRotationString = L10n.Tr("Frond Rotation|Defines rotation around the parent branch."); private static string frondCreaseString = L10n.Tr("Frond Crease|Adjust to crease / fold the fronds."); private static string geometryModeLeafString = L10n.Tr("Geometry Mode|The type of geometry created. You can use a custom mesh, by selecting the Mesh option, ideal for flowers, fruits, etc."); private static string materialLeafString = L10n.Tr("Material|Material used for the leaves."); private static string meshString = L10n.Tr("Mesh|Mesh used for the leaves."); private static string sizeString = L10n.Tr("Size|Adjusts the size of the leaves, use the range to adjust the minimum and the maximum size."); private static string perpendicularAlignString = L10n.Tr("Perpendicular Align|Adjusts whether the leaves are aligned perpendicular to the parent branch."); private static string horizontalAlignString = L10n.Tr("Horizontal Align|Adjusts whether the leaves are aligned horizontally."); public static EditMode editMode { get { switch (Tools.current) { case Tool.View: s_EditMode = EditMode.None; break; case Tool.Move: s_EditMode = EditMode.MoveNode; break; case Tool.Rotate: s_EditMode = EditMode.RotateNode; break; case Tool.Scale: s_EditMode = EditMode.None; break; default: break; } return s_EditMode; } set { switch (value) { case EditMode.None: break; case EditMode.MoveNode: Tools.current = Tool.Move; break; case EditMode.RotateNode: Tools.current = Tool.Rotate; break; default: Tools.current = Tool.None; break; } s_EditMode = value; } } private static EditMode s_EditMode = EditMode.MoveNode; private static string s_SavedSourceMaterialsHash; private static float s_CutoutMaterialHashBeforeUndo; private bool m_WantCompleteUpdate = false; private bool m_WantedCompleteUpdateInPreviousFrame; private const float kSectionSpace = 10.0f; private const float kCurveSpace = 50.0f; private bool m_SectionHasCurves = true; private static int s_ShowCategory = -1; private readonly Rect m_CurveRangesA = new Rect(0, 0, 1, 1); // Range 0..1 private readonly Rect m_CurveRangesB = new Rect(0, -1, 1, 2); // Range -1..1 private static readonly Color s_GroupColor = new Color(1, 0, 1, 1); private static readonly Color s_NormalColor = new Color(1, 1, 0, 1); private readonly TreeEditorHelper m_TreeEditorHelper = new TreeEditorHelper(); // Section animation state private readonly AnimBool[] m_SectionAnimators = new AnimBool[6]; private Vector3 m_LockedWorldPos = Vector3.zero; private Matrix4x4 m_StartMatrix = Matrix4x4.identity; private Quaternion m_StartPointRotation = Quaternion.identity; private bool m_StartPointRotationDirty = false; private Quaternion m_GlobalToolRotation = Quaternion.identity; [MenuItem("GameObject/3D Object/Tree", false, 3001)] static void CreateNewTree(MenuCommand menuCommand) { // Assets Mesh meshAsset = new Mesh(); meshAsset.name = "Mesh"; Material materialSolidAsset = new Material(TreeEditorHelper.DefaultOptimizedBarkShader); materialSolidAsset.name = "Optimized Bark Material"; materialSolidAsset.hideFlags = HideFlags.NotEditable | HideFlags.HideInInspector; Material materialCutoutAsset = new Material(TreeEditorHelper.DefaultOptimizedLeafShader); materialCutoutAsset.name = "Optimized Leaf Material"; materialCutoutAsset.hideFlags = HideFlags.NotEditable | HideFlags.HideInInspector; // Create optimized tree mesh prefab the user can instantiate in the scene GameObject prefabInstance = new GameObject("Tree", typeof(Tree), typeof(MeshFilter), typeof(MeshRenderer)); // Create a tree prefab string path = "Assets/Tree.prefab"; path = AssetDatabase.GenerateUniqueAssetPath(path); GameObject prefabAsset = PrefabUtility.SaveAsPrefabAssetAndConnect(prefabInstance, path, InteractionMode.AutomatedAction); // saving the unfinished prefab here allows assets to be added prefabInstance.GetComponent<MeshFilter>().sharedMesh = meshAsset; // Add mesh, material and textures to the prefab TreeData data = ScriptableObject.CreateInstance<TreeData>(); data.name = "Tree Data"; data.Initialize(); data.optimizedSolidMaterial = materialSolidAsset; data.optimizedCutoutMaterial = materialCutoutAsset; data.mesh = meshAsset; prefabInstance.GetComponent<Tree>().data = data; AssetDatabase.AddObjectToAsset(meshAsset, prefabAsset); AssetDatabase.AddObjectToAsset(materialSolidAsset, prefabAsset); AssetDatabase.AddObjectToAsset(materialCutoutAsset, prefabAsset); AssetDatabase.AddObjectToAsset(data, prefabAsset); GameObjectUtility.SetDefaultParentForNewObject(prefabInstance, (menuCommand.context as GameObject)?.transform, true); // Store Creation undo // @TODO: THIS DOESN"T UNDO ASSET CREATION! Undo.RegisterCreatedObjectUndo(prefabInstance, createNewTreeString); Material[] materials; data.UpdateMesh(prefabInstance.transform.worldToLocalMatrix, out materials); AssignMaterials(prefabInstance.GetComponent<Renderer>(), materials); PrefabUtility.ApplyPrefabInstance(prefabInstance); StageUtility.PlaceGameObjectInCurrentStage(prefabInstance); Selection.activeObject = prefabInstance; Undo.RegisterCreatedObjectUndo(prefabInstance, "Create Tree"); } [RequiredByNativeCode] public static void ResetTree(Tree tree) { TreeData data = GetTreeData(tree); data.DeleteAll(); Material materialSolidAsset = new Material(TreeEditorHelper.DefaultOptimizedBarkShader); materialSolidAsset.name = "Optimized Bark Material"; materialSolidAsset.hideFlags = HideFlags.NotEditable | HideFlags.HideInInspector; Material materialCutoutAsset = new Material(TreeEditorHelper.DefaultOptimizedLeafShader); materialCutoutAsset.name = "Optimized Leaf Material"; materialCutoutAsset.hideFlags = HideFlags.NotEditable | HideFlags.HideInInspector; data.Initialize(); data.optimizedSolidMaterial.CopyPropertiesFromMaterial(materialSolidAsset); data.optimizedCutoutMaterial.CopyPropertiesFromMaterial(materialCutoutAsset); data.mesh.Clear(); DestroyImmediate(materialSolidAsset); DestroyImmediate(materialCutoutAsset); UpdateMesh(tree, false); s_SelectedGroup = data.root; s_SelectedNode = null; s_SelectedPoint = -1; Renderer treeRenderer = tree.GetComponent<Renderer>(); var hidden = !(s_SelectedGroup is TreeGroupRoot); EditorUtility.SetSelectedRenderState( treeRenderer, hidden ? EditorSelectedRenderState.Hidden : EditorSelectedRenderState.Wireframe | EditorSelectedRenderState.Highlight); } static TreeData GetTreeData(Tree tree) { if (tree == null) return null; return tree.data as TreeData; } static void PreviewMesh(Tree tree) { PreviewMesh(tree, true); } static void PreviewMesh(Tree tree, bool callExitGUI) { TreeData treeData = GetTreeData(tree); if (treeData == null) return; Profiler.BeginSample("TreeEditor.PreviewMesh"); Material[] materials; treeData.PreviewMesh(tree.transform.worldToLocalMatrix, out materials); AssignMaterials(tree.GetComponent<Renderer>(), materials); Profiler.EndSample(); // TreeEditor.PreviewMesh if (callExitGUI) { GUIUtility.ExitGUI(); } } static void UpdateMesh(Tree tree) { UpdateMesh(tree, true); } static void AssignMaterials(Renderer renderer, Material[] materials) { if (renderer != null) { if (materials == null) materials = new Material[0]; renderer.sharedMaterials = materials; } } static void UpdateMesh(Tree tree, bool callExitGUI) { TreeData treeData = GetTreeData(tree); if (treeData == null) return; Profiler.BeginSample("TreeEditor.UpdateMesh"); Material[] materials; treeData.UpdateMesh(tree.transform.worldToLocalMatrix, out materials); AssignMaterials(tree.GetComponent<Renderer>(), materials); // If a Tree is opened in Prefab Mode the Tree should be saved by the Prefab Mode logic (manual- or auto-save) // Note: When opened in Prefab Mode the Tree will be unpacked (have no connection to its Prefab). // so we have to dirty its scene instead. // IsPartOfNonAssetPrefabInstance checks if the gameObject is an instance of a prefab. // The additional check of the scene name is to ensure we don't write the prefab when updating an instance of a prefab // and not the prefab itself. if (tree.gameObject.scene.IsValid()) EditorSceneManager.MarkSceneDirty(tree.gameObject.scene); else if (PrefabUtility.IsPartOfNonAssetPrefabInstance(tree.gameObject)) PrefabUtility.ApplyPrefabInstance(tree.gameObject); s_SavedSourceMaterialsHash = treeData.materialHash; Profiler.EndSample(); // TreeEditor.UpdateMesh if (callExitGUI) { GUIUtility.ExitGUI(); } } [MenuItem("GameObject/3D Object/Wind Zone", false, 3002)] static void CreateWindZone(MenuCommand menuCommand) { // Create a wind zone GameObject wind = CreateDefaultWindZone(); GameObjectUtility.SetDefaultParentForNewObject(wind, (menuCommand.context as GameObject)?.transform, true); StageUtility.PlaceGameObjectInCurrentStage(wind); Selection.activeObject = wind; Undo.RegisterCreatedObjectUndo(wind, "Create Wind Zone"); } static GameObject CreateDefaultWindZone() { // Create a wind zone GameObject wind = ObjectFactory.CreateGameObject("WindZone", typeof(WindZone)); Undo.SetCurrentGroupName(createWindZoneString); return wind; } private float FindClosestOffset(TreeData data, Matrix4x4 objMatrix, TreeNode node, Ray mouseRay, ref float rotation) { TreeGroup group = data.GetGroup(node.groupID); if (group == null) return 0.0f; if (group.GetType() != typeof(TreeGroupBranch)) return 0.0f; // Must fetch data directly data.ValidateReferences(); Matrix4x4 matrix = objMatrix * node.matrix; float step = 1.0f / (node.spline.GetNodeCount() * 10.0f); float closestOffset = 0.0f; float closestDist = 10000000.0f; Vector3 closestSegment = Vector3.zero; Vector3 closestRay = Vector3.zero; Vector3 pointA = matrix.MultiplyPoint(node.spline.GetPositionAtTime(0.0f)); for (float t = step; t <= 1.0f; t += step) { Vector3 pointB = matrix.MultiplyPoint(node.spline.GetPositionAtTime(t)); float dist = 0.0f; float s = 0.0f; closestSegment = MathUtils.ClosestPtSegmentRay(pointA, pointB, mouseRay, out dist, out s, out closestRay); if (dist < closestDist) { closestOffset = t - step + (step * s); closestDist = dist; // // Compute local rotation around spline // // 1: Closest point on ray compared to sphere positioned at spline position.. // 2: Transform to local space of the spline (oriented to the spline) // 3: Compute angle in Degrees.. // float radius = node.GetRadiusAtTime(closestOffset); float tt = 0.0f; if (MathUtils.ClosestPtRaySphere(mouseRay, closestSegment, radius, ref tt, ref closestRay)) { Matrix4x4 invMatrix = (matrix * node.GetLocalMatrixAtTime(closestOffset)).inverse; Vector3 raySegmentVector = closestRay - closestSegment; raySegmentVector = invMatrix.MultiplyVector(raySegmentVector); rotation = Mathf.Atan2(raySegmentVector.x, raySegmentVector.z) * Mathf.Rad2Deg; } } pointA = pointB; } // Clear directly referenced stuff data.ClearReferences(); return closestOffset; } void SelectGroup(TreeGroup group) { if (group == null) Debug.Log("GROUP SELECTION IS NULL!"); if (m_TreeEditorHelper.NodeHasWrongMaterial(group)) { // automatically show the Geometry tab if the selected node has a wrong shader s_ShowCategory = 1; } s_SelectedGroup = group; s_SelectedNode = null; s_SelectedPoint = -1; Tree tree = target as Tree; if (tree == null) return; Renderer treeRenderer = tree.GetComponent<Renderer>(); var hidden = !(s_SelectedGroup is TreeGroupRoot); EditorUtility.SetSelectedRenderState( treeRenderer, hidden ? EditorSelectedRenderState.Hidden : EditorSelectedRenderState.Wireframe | EditorSelectedRenderState.Highlight); } void SelectNode(TreeNode node, TreeData treeData) { SelectGroup(node == null ? treeData.root : treeData.GetGroup(node.groupID)); s_SelectedNode = node; s_SelectedPoint = -1; } void DuplicateSelected(TreeData treeData) { // Store complete undo UndoStoreSelected(EditMode.Duplicate); if (s_SelectedNode != null) { // duplicate node s_SelectedNode = treeData.DuplicateNode(s_SelectedNode); s_SelectedGroup.Lock(); } else { // duplicate group SelectGroup(treeData.DuplicateGroup(s_SelectedGroup)); } m_WantCompleteUpdate = true; UpdateMesh(target as Tree); m_WantCompleteUpdate = false; } void DeleteSelected(TreeData treeData) { // Store complete undo UndoStoreSelected(EditMode.Delete); // if (s_SelectedNode != null) { if (s_SelectedPoint >= 1) { if (s_SelectedNode.spline.nodes.Length > 2) { //Undo.RegisterSceneUndo("Delete"); if (s_SelectedGroup.lockFlags == 0) { s_SelectedGroup.Lock(); } s_SelectedNode.spline.RemoveNode(s_SelectedPoint); s_SelectedPoint = Mathf.Max(s_SelectedPoint - 1, 0); } } else { if ((s_SelectedGroup != null) && (s_SelectedGroup.nodeIDs.Length == 1)) { s_SelectedNode = null; DeleteSelected(treeData); return; } treeData.DeleteNode(s_SelectedNode); s_SelectedGroup.Lock(); SelectGroup(s_SelectedGroup); } } else if (s_SelectedGroup != null) { TreeGroup parentGroup = treeData.GetGroup(s_SelectedGroup.parentGroupID); if (parentGroup == null) { return; } treeData.DeleteGroup(s_SelectedGroup); SelectGroup(parentGroup); } m_WantCompleteUpdate = true; UpdateMesh(target as Tree); m_WantCompleteUpdate = false; } void VerifySelection(TreeData treeData) { TreeGroup groupToSelect = s_SelectedGroup; TreeNode nodeToSelect = s_SelectedNode; if (groupToSelect != null) { groupToSelect = treeData.GetGroup(groupToSelect.uniqueID); } if (nodeToSelect != null) { nodeToSelect = treeData.GetNode(nodeToSelect.uniqueID); } // on first start, we need to verify the selected part actually belongs to the current tree); if (groupToSelect != treeData.root && groupToSelect != null) { // Make sure this group is part of this tree.. if (!treeData.IsAncestor(treeData.root, groupToSelect)) { // not part of this tree.. groupToSelect = null; nodeToSelect = null; } } // Clear selected node if it's been deleted if ((nodeToSelect != null) && (treeData.GetGroup(nodeToSelect.groupID) != groupToSelect)) { nodeToSelect = null; } if (groupToSelect == null) groupToSelect = treeData.root; if (s_SelectedGroup != null && groupToSelect == s_SelectedGroup) return; SelectGroup(groupToSelect); if (nodeToSelect != null) SelectNode(nodeToSelect, treeData); } // // Check for hot key events.. // bool OnCheckHotkeys(TreeData treeData, bool checkFrameSelected) { switch (Event.current.type) { case EventType.ValidateCommand: if (Event.current.commandName == "SoftDelete" || Event.current.commandName == "Delete") { if ((s_SelectedGroup != null) && (s_SelectedGroup != treeData.root)) { Event.current.Use(); } } if (Event.current.commandName == "FrameSelected") { if (checkFrameSelected) { Event.current.Use(); } } if (Event.current.commandName == "UndoRedoPerformed") { Event.current.Use(); } break; case EventType.ExecuteCommand: //Debug.Log("Execute command " + Event.current.commandName); if (Event.current.commandName == "SoftDelete" || Event.current.commandName == "Delete") { if ((s_SelectedGroup != null) && (s_SelectedGroup != treeData.root)) { DeleteSelected(treeData); Event.current.Use(); } } if (Event.current.commandName == "FrameSelected") { if (checkFrameSelected) { FrameSelected(target as Tree); Event.current.Use(); } } if (Event.current.commandName == "UndoRedoPerformed") { float materialHash = GenerateMaterialHash(treeData.optimizedCutoutMaterial); if (s_CutoutMaterialHashBeforeUndo != materialHash) { // Cutout material's hash has changed, so we're undoing property changes on the // generated material only, no need to update the whole tree. s_CutoutMaterialHashBeforeUndo = materialHash; } else { // After undo: restore the material hash of the materials that were used to create // texture atlases currently stored on disk. That will make sure that performing undo // will regenerate atlases when necessary. treeData.materialHash = s_SavedSourceMaterialsHash; m_StartPointRotationDirty = true; UpdateMesh(target as Tree); } Event.current.Use(); // Must exit to update properly return true; } if (Event.current.commandName == "CurveChangeCompleted") { UpdateMesh(target as Tree); Event.current.Use(); return true; } break; } return false; } Bounds CalcBounds(TreeData treeData, Matrix4x4 objMatrix, TreeNode node) { Matrix4x4 nodeMatrix = objMatrix * node.matrix; Bounds bounds; if (treeData.GetGroup(node.groupID).GetType() == typeof(TreeGroupBranch) && node.spline != null && node.spline.nodes.Length > 0) { // Has a spline bounds = new Bounds(nodeMatrix.MultiplyPoint(node.spline.nodes[0].point), Vector3.zero); for (int i = 1; i < node.spline.nodes.Length; i++) { bounds.Encapsulate(nodeMatrix.MultiplyPoint(node.spline.nodes[i].point)); } } else { // no spline bounds = new Bounds(nodeMatrix.MultiplyPoint(Vector3.zero), Vector3.zero); } return bounds; } void FrameSelected(Tree tree) { TreeData treeData = GetTreeData(tree); Matrix4x4 objMatrix = tree.transform.localToWorldMatrix; Bounds bounds = new Bounds(objMatrix.MultiplyPoint(Vector3.zero), Vector3.zero); // Compute bounds for selection if (s_SelectedGroup != null) { if (s_SelectedGroup.GetType() == typeof(TreeGroupRoot)) { MeshFilter meshFilter = tree.GetComponent<MeshFilter>(); if ((meshFilter == null) || (s_SelectedGroup.childGroupIDs.Length == 0)) { float rad = s_SelectedGroup.GetRootSpread(); bounds = new Bounds(objMatrix.MultiplyPoint(Vector3.zero), objMatrix.MultiplyVector(new Vector3(rad, rad, rad))); } else { bounds = new Bounds(objMatrix.MultiplyPoint(meshFilter.sharedMesh.bounds.center), objMatrix.MultiplyVector(meshFilter.sharedMesh.bounds.size)); } } else if (s_SelectedNode != null) { if (s_SelectedGroup.GetType() == typeof(TreeGroupLeaf) && s_SelectedPoint >= 0) { // Focus on selected point Matrix4x4 nodeMatrix = objMatrix * s_SelectedNode.matrix; bounds = new Bounds(nodeMatrix.MultiplyPoint(s_SelectedNode.spline.nodes[s_SelectedPoint].point), Vector3.zero); } else { bounds = CalcBounds(treeData, objMatrix, s_SelectedNode); } } else { // Focus on selected group for (int i = 0; i < s_SelectedGroup.nodeIDs.Length; i++) { Bounds temp = CalcBounds(treeData, objMatrix, treeData.GetNode(s_SelectedGroup.nodeIDs[i])); if (i == 0) { bounds = temp; } else { bounds.Encapsulate(temp); } } } } Vector3 center = bounds.center; float size = bounds.size.magnitude + 1.0f; SceneView currentSceneView = SceneView.lastActiveSceneView; if (currentSceneView) { currentSceneView.LookAt(center, currentSceneView.rotation, size); } } void UndoStoreSelected(EditMode mode) { // // Store undo // TreeData treeData = GetTreeData(target as Tree); if (!treeData) return; // // Object[] objects; objects = new Object[1]; objects[0] = treeData; EditorUtility.SetDirty(treeData); switch (mode) { case EditMode.Freehand: Undo.RegisterCompleteObjectUndo(objects, "Freehand Drawing"); break; case EditMode.RotateNode: Undo.RegisterCompleteObjectUndo(objects, "Rotate"); break; case EditMode.MoveNode: Undo.RegisterCompleteObjectUndo(objects, "Move"); break; case EditMode.Parameter: Undo.RegisterCompleteObjectUndo(objects, "Parameter Change"); break; case EditMode.Everything: Undo.RegisterCompleteObjectUndo(objects, "Parameter Change"); break; case EditMode.Delete: Undo.RegisterCompleteObjectUndo(objects, "Delete"); break; case EditMode.CreateGroup: Undo.RegisterCompleteObjectUndo(objects, "Create Group"); break; case EditMode.Duplicate: Undo.RegisterCompleteObjectUndo(objects, "Duplicate"); break; } } void RepaintGUIView() { GUIView.current.Repaint(); } void OnEnable() { Tree tree = target as Tree; if (tree == null) return; TreeData treeData = GetTreeData(tree); if (treeData == null) return; m_TreeEditorHelper.OnEnable(treeData); m_TreeEditorHelper.SetAnimsCallback(RepaintGUIView); for (int i = 0; i < m_SectionAnimators.Length; i++) m_SectionAnimators[i] = new AnimBool(s_ShowCategory == i, Repaint); Renderer treeRenderer = tree.GetComponent<Renderer>(); var hidden = !(s_SelectedGroup is TreeGroupRoot); EditorUtility.SetSelectedRenderState( treeRenderer, hidden ? EditorSelectedRenderState.Hidden : EditorSelectedRenderState.Wireframe | EditorSelectedRenderState.Highlight); } void OnDisable() { Tools.s_Hidden = false; Tree tree = target as Tree; if (tree == null) return; Renderer treeRenderer = tree.GetComponent<Renderer>(); EditorUtility.SetSelectedRenderState(treeRenderer, EditorSelectedRenderState.Wireframe | EditorSelectedRenderState.Highlight); } void OnSceneGUI() { // make sure it's a tree Tree tree = target as Tree; TreeData treeData = GetTreeData(tree); if (!treeData) return; // make sure selection is ok VerifySelection(treeData); if (s_SelectedGroup == null) { return; } // Check for hotkey event OnCheckHotkeys(treeData, true); Transform treeTransform = tree.transform; Matrix4x4 treeMatrix = tree.transform.localToWorldMatrix; Event evt = Event.current; #region Do Root Handles if (s_SelectedGroup.GetType() == typeof(TreeGroupRoot)) { Tools.s_Hidden = false; Handles.color = s_NormalColor; Handles.DrawWireDisc(treeTransform.position, treeTransform.up, treeData.root.rootSpread); } else { Tools.s_Hidden = true; Handles.color = Handles.secondaryColor; Handles.DrawWireDisc(treeTransform.position, treeTransform.up, treeData.root.rootSpread); } #endregion #region Do Branch Handles if (s_SelectedGroup != null && s_SelectedGroup.GetType() == typeof(TreeGroupBranch)) { EventType oldEventType = evt.type; // we want ignored mouse up events to check for dragging off of scene view if (evt.type == EventType.Ignore && evt.rawType == EventType.MouseUp) oldEventType = evt.rawType; // Draw all splines in a single GL.Begin / GL.End Handles.DrawLine(Vector3.zero, Vector3.zero); HandleUtility.ApplyWireMaterial(); GL.Begin(GL.LINES); for (int nodeIndex = 0; nodeIndex < s_SelectedGroup.nodeIDs.Length; nodeIndex++) { TreeNode branch = treeData.GetNode(s_SelectedGroup.nodeIDs[nodeIndex]); TreeSpline spline = branch.spline; if (spline == null) continue; Handles.color = (branch == s_SelectedNode) ? s_NormalColor : s_GroupColor; Matrix4x4 branchMatrix = treeMatrix * branch.matrix; // Draw Spline Vector3 prevPos = branchMatrix.MultiplyPoint(spline.GetPositionAtTime(0.0f)); GL.Color(Handles.color); for (float t = 0.01f; t <= 1.0f; t += 0.01f) { Vector3 currPos = branchMatrix.MultiplyPoint(spline.GetPositionAtTime(t)); //Handles.DrawLine(prevPos, currPos); GL.Vertex(prevPos); GL.Vertex(currPos); prevPos = currPos; } } GL.End(); // Draw all handles for (int nodeIndex = 0; nodeIndex < s_SelectedGroup.nodeIDs.Length; nodeIndex++) { TreeNode branch = treeData.GetNode(s_SelectedGroup.nodeIDs[nodeIndex]); TreeSpline spline = branch.spline; if (spline == null) continue; Handles.color = (branch == s_SelectedNode) ? s_NormalColor : s_GroupColor; Matrix4x4 branchMatrix = treeMatrix * branch.matrix; // Draw Points for (int pointIndex = 0; pointIndex < spline.nodes.Length; pointIndex++) { SplineNode point = spline.nodes[pointIndex]; Vector3 worldPos = branchMatrix.MultiplyPoint(point.point); float handleSize = HandleUtility.GetHandleSize(worldPos) * 0.08f; Handles.color = Handles.centerColor; int oldKeyboardControl = GUIUtility.keyboardControl; switch (editMode) { case EditMode.MoveNode: if (pointIndex == 0) worldPos = Handles.FreeMoveHandle(worldPos, handleSize, Vector3.zero, Handles.CircleHandleCap); else worldPos = Handles.FreeMoveHandle(worldPos, handleSize, Vector3.zero, Handles.RectangleHandleCap); // check if point was just selected if (oldEventType == EventType.MouseDown && evt.type == EventType.Used && oldKeyboardControl != GUIUtility.keyboardControl) { SelectNode(branch, treeData); s_SelectedPoint = pointIndex; m_StartPointRotation = MathUtils.QuaternionFromMatrix(branchMatrix) * point.rot; } if ((oldEventType == EventType.MouseDown || oldEventType == EventType.MouseUp) && evt.type == EventType.Used) { m_StartPointRotation = MathUtils.QuaternionFromMatrix(branchMatrix) * point.rot; } // check if we're done dragging handle (so we can change ids) if (oldEventType == EventType.MouseUp && evt.type == EventType.Used) { if (treeData.isInPreviewMode) { // We need a complete rebuild.. UpdateMesh(tree); } } if (GUI.changed) { Undo.RegisterCompleteObjectUndo(treeData, "Move"); s_SelectedGroup.Lock(); // Snap root branch to parent (overrides position received from handles, uses mouse raycasts instead) float angle = branch.baseAngle; if (pointIndex == 0) { TreeNode parentNode = treeData.GetNode(s_SelectedNode.parentID); Ray mouseRay = HandleUtility.GUIPointToWorldRay(evt.mousePosition); float hitDist = 0f; if (parentNode != null) { TreeGroup parentGroup = treeData.GetGroup(s_SelectedGroup.parentGroupID); if (parentGroup.GetType() == typeof(TreeGroupBranch)) { // Snap to parent branch s_SelectedNode.offset = FindClosestOffset(treeData, treeMatrix, parentNode, mouseRay, ref angle); worldPos = branchMatrix.MultiplyPoint(Vector3.zero); } else if (parentGroup.GetType() == typeof(TreeGroupRoot)) { // Snap to ground Vector3 mid = treeMatrix.MultiplyPoint(Vector3.zero); Plane p = new Plane(treeMatrix.MultiplyVector(Vector3.up), mid); if (p.Raycast(mouseRay, out hitDist)) { worldPos = mouseRay.origin + mouseRay.direction * hitDist; Vector3 delta = worldPos - mid; delta = treeMatrix.inverse.MultiplyVector(delta); s_SelectedNode.offset = Mathf.Clamp01(delta.magnitude / treeData.root.rootSpread); angle = Mathf.Atan2(delta.z, delta.x) * Mathf.Rad2Deg; worldPos = branchMatrix.MultiplyPoint(Vector3.zero); } else { worldPos = branchMatrix.MultiplyPoint(point.point); } } } } branch.baseAngle = angle; point.point = branchMatrix.inverse.MultiplyPoint(worldPos); spline.UpdateTime(); spline.UpdateRotations(); PreviewMesh(tree); GUI.changed = false; } break; case EditMode.RotateNode: EditorGUI.BeginChangeCheck(); Quaternion newRotation = Handles.FreeRotateHandle(point.rot, worldPos, handleSize); if (EditorGUI.EndChangeCheck()) { SelectNode(branch, treeData); s_SelectedGroup.Lock(); s_SelectedPoint = pointIndex; Undo.RecordObject(this, "Rotate branch"); //Move all points after the rotation pivot accordingly to the rotation for (int i = s_SelectedPoint + 1; i < spline.nodes.Length; i++) { Vector3 pointVector = (spline.nodes[i].point - point.point); pointVector = branchMatrix.MultiplyVector(pointVector); pointVector = newRotation * pointVector; pointVector = branchMatrix.inverse.MultiplyVector(pointVector); Vector3 newPos = point.point + pointVector; s_SelectedNode.spline.nodes[i].point = newPos; } spline.UpdateTime(); spline.UpdateRotations(); PreviewMesh(tree); } else if (s_SelectedPoint == pointIndex && treeData.isInPreviewMode) { s_SelectedPoint = -1; UpdateMesh(tree); } break; case EditMode.Freehand: EditorGUI.BeginChangeCheck(); Vector3 newPosition = Handles.FreeMoveHandle(worldPos, handleSize, Vector3.zero, Handles.CircleHandleCap); if (EditorGUI.EndChangeCheck()) { Undo.RegisterCompleteObjectUndo(treeData, "Free Hand"); SelectNode(branch, treeData); s_SelectedPoint = pointIndex; s_StartPosition = worldPos; int cutCount = Mathf.Max(2, s_SelectedPoint + 1); branch.spline.SetNodeCount(cutCount); Ray mouseRay = HandleUtility.GUIPointToWorldRay(evt.mousePosition); // In draw mode.. move current spline node to mouse position // trace ray on a plane placed at the original position of the selected node and aligned to the camera.. Vector3 camFront = Camera.current.transform.forward; Plane p = new Plane(camFront, s_StartPosition); float hitDist = 0.0f; if (p.Raycast(mouseRay, out hitDist)) { Vector3 hitPos = mouseRay.origin + hitDist * mouseRay.direction; if (s_SelectedPoint == 0) { s_SelectedPoint = 1; } // lock shape s_SelectedGroup.Lock(); s_SelectedNode.spline.nodes[s_SelectedPoint].point = (branchMatrix.inverse).MultiplyPoint(hitPos); Vector3 delta = s_SelectedNode.spline.nodes[s_SelectedPoint].point - s_SelectedNode.spline.nodes[s_SelectedPoint - 1].point; if (delta.magnitude > 1.0f) { // move on to the next node s_SelectedPoint++; if (s_SelectedPoint >= s_SelectedNode.spline.nodes.Length) { s_SelectedNode.spline.AddPoint(branchMatrix.inverse.MultiplyPoint(hitPos), 1.1f); } } s_SelectedNode.spline.UpdateTime(); s_SelectedNode.spline.UpdateRotations(); // Make sure changes are saved PreviewMesh(tree); } } else if (s_SelectedPoint == pointIndex) { //SelectNode(null,treeData); if (treeData.isInPreviewMode) { // We need a complete rebuild.. UpdateMesh(tree); } } break; default: break; } // Handle undo if (s_SelectedPoint == pointIndex && s_SelectedNode == branch && m_StartPointRotationDirty) { spline.UpdateTime(); spline.UpdateRotations(); m_StartPointRotation = MathUtils.QuaternionFromMatrix(branchMatrix) * point.rot; m_GlobalToolRotation = Quaternion.identity; m_StartPointRotationDirty = false; } } } // Draw Position Handles for Selected Point if (s_SelectedPoint > 0 && editMode == EditMode.MoveNode && s_SelectedNode != null) { TreeNode branch = s_SelectedNode; SplineNode point = branch.spline.nodes[s_SelectedPoint]; Matrix4x4 branchMatrix = treeMatrix * branch.matrix; Vector3 worldPos = branchMatrix.MultiplyPoint(point.point); Quaternion toolRotation = Quaternion.identity; if (Tools.pivotRotation == PivotRotation.Local) { if (oldEventType == EventType.MouseUp || oldEventType == EventType.MouseDown) m_StartPointRotation = MathUtils.QuaternionFromMatrix(branchMatrix) * point.rot; toolRotation = m_StartPointRotation; } worldPos = DoPositionHandle(worldPos, toolRotation, false); if (GUI.changed) { Undo.RegisterCompleteObjectUndo(treeData, "Move"); s_SelectedGroup.Lock(); point.point = branchMatrix.inverse.MultiplyPoint(worldPos); branch.spline.UpdateTime(); branch.spline.UpdateRotations(); PreviewMesh(tree); } // check if we're done dragging handle (so we can change ids) if (oldEventType == EventType.MouseUp && evt.type == EventType.Used) { s_SelectedPoint = -1; if (treeData.isInPreviewMode) { // We need a complete rebuild.. UpdateMesh(tree); } } } } #endregion #region Do Leaf Handles if (s_SelectedGroup != null && s_SelectedGroup.GetType() == typeof(TreeGroupLeaf)) { for (int nodeIndex = 0; nodeIndex < s_SelectedGroup.nodeIDs.Length; nodeIndex++) { TreeNode leaf = treeData.GetNode(s_SelectedGroup.nodeIDs[nodeIndex]); Matrix4x4 leafMatrix = treeMatrix * leaf.matrix; Vector3 worldPos = leafMatrix.MultiplyPoint(Vector3.zero); float handleSize = HandleUtility.GetHandleSize(worldPos) * 0.08f; Handles.color = Handles.centerColor; EventType oldEventType = evt.type; int oldKeyboardControl = GUIUtility.keyboardControl; switch (editMode) { case EditMode.MoveNode: Handles.FreeMoveHandle(worldPos, handleSize, Vector3.zero, Handles.CircleHandleCap); // check if point was just selected if (oldEventType == EventType.MouseDown && evt.type == EventType.Used && oldKeyboardControl != GUIUtility.keyboardControl) { SelectNode(leaf, treeData); m_GlobalToolRotation = MathUtils.QuaternionFromMatrix(leafMatrix); m_StartMatrix = leafMatrix; m_StartPointRotation = leaf.rotation; m_LockedWorldPos = new Vector3(m_StartMatrix.m03, m_StartMatrix.m13, m_StartMatrix.m23); } // check if we're done dragging handle (so we can change ids) if (oldEventType == EventType.MouseUp && evt.type == EventType.Used) { s_SelectedPoint = -1; if (treeData.isInPreviewMode) { // We need a complete rebuild.. UpdateMesh(tree); } } if (GUI.changed) { s_SelectedGroup.Lock(); TreeNode parentNode = treeData.GetNode(leaf.parentID); TreeGroup parentGroup = treeData.GetGroup(s_SelectedGroup.parentGroupID); Ray mouseRay = HandleUtility.GUIPointToWorldRay(evt.mousePosition); float hitDist = 0f; float angle = leaf.baseAngle; if (parentGroup.GetType() == typeof(TreeGroupBranch)) { // Snap to branch leaf.offset = FindClosestOffset(treeData, treeMatrix, parentNode, mouseRay, ref angle); leaf.baseAngle = angle; PreviewMesh(tree); } else if (parentGroup.GetType() == typeof(TreeGroupRoot)) { // Snap to ground Vector3 mid = treeMatrix.MultiplyPoint(Vector3.zero); Plane p = new Plane(treeMatrix.MultiplyVector(Vector3.up), mid); if (p.Raycast(mouseRay, out hitDist)) { worldPos = mouseRay.origin + mouseRay.direction * hitDist; Vector3 delta = worldPos - mid; delta = treeMatrix.inverse.MultiplyVector(delta); leaf.offset = Mathf.Clamp01(delta.magnitude / treeData.root.rootSpread); angle = Mathf.Atan2(delta.z, delta.x) * Mathf.Rad2Deg; } leaf.baseAngle = angle; PreviewMesh(tree); } } break; case EditMode.RotateNode: { m_GlobalToolRotation = MathUtils.QuaternionFromMatrix(leafMatrix); m_StartMatrix = leafMatrix; m_LockedWorldPos = new Vector3(leafMatrix.m03, leafMatrix.m13, leafMatrix.m23); EditorGUI.BeginChangeCheck(); Quaternion newRotation = Handles.FreeRotateHandle(leaf.rotation, m_LockedWorldPos, handleSize); if (EditorGUI.EndChangeCheck()) { SelectNode(leaf, treeData); s_SelectedGroup.Lock(); Undo.RecordObject(this, "Rotate leaf"); leaf.rotation = newRotation; PreviewMesh(tree); } else if (s_SelectedNode == leaf && treeData.isInPreviewMode) { UpdateMesh(tree); } } break; default: break; } } } #endregion } private Vector3 DoPositionHandle(Vector3 position, Quaternion rotation, bool hide) { Color temp = Handles.color; Handles.color = Handles.xAxisColor; position = Handles.Slider(position, rotation * Vector3.right); Handles.color = Handles.yAxisColor; position = Handles.Slider(position, rotation * Vector3.up); Handles.color = Handles.zAxisColor; position = Handles.Slider(position, rotation * Vector3.forward); Handles.color = temp; return position; } private Rect GUIPropBegin() { Rect r = EditorGUILayout.BeginHorizontal(); return r; } private void GUIPropEnd() { GUIPropEnd(true); } private void GUIPropEnd(bool addSpace) { if (addSpace) { GUILayout.Space(m_SectionHasCurves ? kCurveSpace + 4 : 0); } EditorGUILayout.EndHorizontal(); } private void GUIHandlePropertyChange(PropertyType prop) { switch (prop) { case PropertyType.Normal: UndoStoreSelected(EditMode.Parameter); break; case PropertyType.FullUpdate: UndoStoreSelected(EditMode.Parameter); m_WantCompleteUpdate = true; break; case PropertyType.FullUndo: UndoStoreSelected(EditMode.Everything); break; case PropertyType.FullUndoUpdate: UndoStoreSelected(EditMode.Everything); m_WantCompleteUpdate = true; break; } } // GUI Helpers.. private float GUISlider(PropertyType prop, string contentID, float value, float minimum, float maximum, bool hasCurve) { GUIPropBegin(); float newValue = EditorGUILayout.Slider(TreeEditorHelper.GetGUIContent(contentID), value, minimum, maximum); if (newValue != value) { GUIHandlePropertyChange(prop); } if (!hasCurve) GUIPropEnd(); return newValue; } private int GUIIntSlider(PropertyType prop, string contentID, int value, int minimum, int maximum, bool hasCurve) { GUIPropBegin(); int newValue = EditorGUILayout.IntSlider(TreeEditorHelper.GetGUIContent(contentID), value, minimum, maximum); if (newValue != value) { GUIHandlePropertyChange(prop); } if (!hasCurve) GUIPropEnd(); return newValue; } private bool GUIToggle(PropertyType prop, string contentID, bool value, bool hasCurve) { GUIPropBegin(); bool newValue = EditorGUILayout.Toggle(TreeEditorHelper.GetGUIContent(contentID), value); if (newValue != value) { GUIHandlePropertyChange(prop); m_WantCompleteUpdate = true; } if (!hasCurve) GUIPropEnd(); return newValue; } private int GUIPopup(PropertyType prop, string contentID, string[] optionIDs, int value, bool hasCurve) { GUIPropBegin(); GUIContent[] options = new GUIContent[optionIDs.Length]; for (int i = 0; i < optionIDs.Length; i++) { options[i] = TreeEditorHelper.GetGUIContent(optionIDs[i]); } int newValue = EditorGUILayout.Popup(TreeEditorHelper.GetGUIContent(contentID), value, options); if (newValue != value) { GUIHandlePropertyChange(prop); m_WantCompleteUpdate = true; } if (!hasCurve) GUIPropEnd(); return newValue; } private Material GUIMaterialField(PropertyType prop, int uniqueNodeID, string contentID, Material value, TreeEditorHelper.NodeType nodeType) { string uniqueID = uniqueNodeID + "_" + contentID; GUIPropBegin(); Material newValue = EditorGUILayout.ObjectField(TreeEditorHelper.GetGUIContent(contentID), value, typeof(Material), false) as Material; GUIPropEnd(); bool shaderFixed = m_TreeEditorHelper.GUIWrongShader(uniqueID, newValue, nodeType); if (newValue != value || shaderFixed) { GUIHandlePropertyChange(prop); m_WantCompleteUpdate = true; } return newValue; } private Object GUIObjectField(PropertyType prop, string contentID, Object value, System.Type type, bool hasCurve) { GUIPropBegin(); Object newValue = EditorGUILayout.ObjectField(TreeEditorHelper.GetGUIContent(contentID), value, type, false); if (newValue != value) { GUIHandlePropertyChange(prop); m_WantCompleteUpdate = true; } if (!hasCurve) GUIPropEnd(); return newValue; } private bool GUICurve(PropertyType prop, AnimationCurve curve, Rect ranges) { bool preChange = GUI.changed; EditorGUILayout.CurveField(curve, Color.green, ranges, GUILayout.Width(kCurveSpace)); GUIPropEnd(false); if (preChange != GUI.changed) { if (GUIUtility.hotControl == 0) m_WantCompleteUpdate = true; GUIHandlePropertyChange(prop); return true; } return false; } private Vector2 GUIMinMaxSlider(PropertyType prop, string contentID, Vector2 value, float minimum, float maximum, bool hasCurve) { GUIPropBegin(); Vector2 newValue = new Vector2(Mathf.Min(value.x, value.y), Mathf.Max(value.x, value.y)); GUIContent content = TreeEditorHelper.GetGUIContent(contentID); bool preChange = GUI.changed; Rect tempRect = GUILayoutUtility.GetRect(content, "Button"); EditorGUI.MinMaxSlider(tempRect, content, ref newValue.x, ref newValue.y, minimum, maximum); if (preChange != GUI.changed) { GUIHandlePropertyChange(prop); } if (!hasCurve) GUIPropEnd(); return newValue; } public void InspectorHierachy(TreeData treeData, Renderer renderer) { if (s_SelectedGroup == null) { Debug.Log("NO GROUP SELECTED!"); return; } EditorGUILayout.BeginHorizontal(); GUILayout.BeginVertical(); bool preChange = GUI.changed; Rect sizeRect = GUIPropBegin(); DrawHierachy(treeData, renderer, sizeRect); if (GUI.changed != preChange) m_WantCompleteUpdate = true; GUIPropEnd(false); GUIPropBegin(); int sel = -1; GUILayout.BeginHorizontal(styles.toolbar); if (GUILayout.Button(styles.iconRefresh, styles.toolbarButton)) { TreeGroupLeaf.s_TextureHullsDirty = true; UpdateMesh(target as Tree); } GUILayout.FlexibleSpace(); // Only enable if this group can have sub groups GUI.enabled = s_SelectedGroup.CanHaveSubGroups(); if (GUILayout.Button(styles.iconAddLeaves, styles.toolbarButton)) sel = 0; if (GUILayout.Button(styles.iconAddBranches, styles.toolbarButton)) sel = 1; GUI.enabled = true; if (s_SelectedGroup == treeData.root) { GUI.enabled = false; } if (GUILayout.Button(styles.iconDuplicate, styles.toolbarButton)) sel = 3; if (GUILayout.Button(styles.iconTrash, styles.toolbarButton)) sel = 2; GUI.enabled = true; GUILayout.EndHorizontal(); switch (sel) { case 0: { UndoStoreSelected(EditMode.CreateGroup); TreeGroup g = treeData.AddGroup(s_SelectedGroup, typeof(TreeGroupLeaf)); SelectGroup(g); m_WantCompleteUpdate = true; Event.current.Use(); } break; case 1: { UndoStoreSelected(EditMode.CreateGroup); TreeGroup g = treeData.AddGroup(s_SelectedGroup, typeof(TreeGroupBranch)); SelectGroup(g); m_WantCompleteUpdate = true; Event.current.Use(); } break; case 2: { DeleteSelected(treeData); Event.current.Use(); } break; case 3: { DuplicateSelected(treeData); Event.current.Use(); } break; } GUIPropEnd(false); GUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); } public void InspectorEditTools(Tree obj) { // early out if we don't have a scene representation if (EditorUtility.IsPersistent(obj)) return; string[] toolbarIconStrings; string[] toolbarContentStrings; if (s_SelectedGroup is TreeGroupBranch) { toolbarIconStrings = toolbarIconStringsBranch; toolbarContentStrings = toolbarContentStringsBranch; } else { toolbarIconStrings = toolbarIconStringsLeaf; toolbarContentStrings = toolbarContentStringsLeaf; // check if user selected a leaf group when in branch free hand mode if (editMode == EditMode.Freehand) editMode = EditMode.None; } EditMode oldEditMode = editMode; editMode = (EditMode)GUItoolbar((int)editMode, BuildToolbarContent(toolbarIconStrings, toolbarContentStrings, (int)editMode)); if (oldEditMode != editMode) { // Edit mode changed.. repaint scene view! SceneView.RepaintAll(); } EditorGUILayout.BeginVertical(EditorStyles.helpBox); if (editMode == EditMode.None) { GUILayout.Label("No Tool Selected"); GUILayout.Label("Please select a tool", EditorStyles.wordWrappedMiniLabel); } else { string uiString = toolbarContentStrings[(int)editMode]; GUILayout.Label(TreeEditorHelper.ExtractLabel(uiString)); GUILayout.Label(TreeEditorHelper.ExtractTooltip(uiString), EditorStyles.wordWrappedMiniLabel); } EditorGUILayout.EndVertical(); EditorGUILayout.Space(); } private static GUIContent[] BuildToolbarContent(string[] iconStrings, string[] contentStrings, int selection) { GUIContent[] contents = new GUIContent[contentStrings.Length]; for (int i = 0; i < contentStrings.Length; i++) { string iconSuffix = selection == i ? " On" : ""; string tooltip = TreeEditorHelper.ExtractLabel(contentStrings[i]); contents[i] = EditorGUIUtility.IconContent(iconStrings[i] + iconSuffix, tooltip); } return contents; } // // Distribution properties inspector (generic) // public void InspectorDistribution(TreeData treeData, TreeGroup group) { if (group == null) return; PrepareSpacing(true); bool enableGUI = true; if (group.lockFlags != 0) { enableGUI = false; } // Seed GUI.enabled = enableGUI; int pre = group.seed; group.seed = GUIIntSlider(PropertyType.Normal, group.GroupSeedString, group.seed, 0, 999999, false); if (group.seed != pre) { treeData.UpdateSeed(group.uniqueID); } // Frequency pre = group.distributionFrequency; group.distributionFrequency = GUIIntSlider(PropertyType.FullUndo, group.FrequencyString, group.distributionFrequency, 1, 100, false); if (group.distributionFrequency != pre) { treeData.UpdateFrequency(group.uniqueID); } // Distribution Mode pre = (int)group.distributionMode; group.distributionMode = (TreeGroup.DistributionMode)GUIPopup(PropertyType.Normal, group.DistributionModeString, inspectorDistributionPopupOptions, (int)group.distributionMode, true); if ((int)group.distributionMode != pre) { treeData.UpdateDistribution(group.uniqueID); } // Distribution Curve AnimationCurve tempCurve = group.distributionCurve; if (GUICurve(PropertyType.Normal, tempCurve, m_CurveRangesA)) { group.distributionCurve = tempCurve; treeData.UpdateDistribution(group.uniqueID); } // Twirl if (group.distributionMode != TreeGroup.DistributionMode.Random) { float pref = group.distributionTwirl; group.distributionTwirl = GUISlider(PropertyType.Normal, group.TwirlString, group.distributionTwirl, -1.0f, 1.0f, false); if (group.distributionTwirl != pref) { treeData.UpdateDistribution(group.uniqueID); } } // Nodes per arrangement if (group.distributionMode == TreeGroup.DistributionMode.Whorled) { pre = group.distributionNodes; group.distributionNodes = GUIIntSlider(PropertyType.Normal, group.WhorledStepString, group.distributionNodes, 1, 21, false); if (group.distributionNodes != pre) { treeData.UpdateDistribution(group.uniqueID); } } // growth scale group.distributionScale = GUISlider(PropertyType.Normal, group.GrowthScaleString, group.distributionScale, 0.0f, 1.0f, true); // growth scale curve tempCurve = group.distributionScaleCurve; if (GUICurve(PropertyType.Normal, tempCurve, m_CurveRangesA)) { group.distributionScaleCurve = tempCurve; } // growth scale group.distributionPitch = GUISlider(PropertyType.Normal, group.GrowthAngleString, group.distributionPitch, 0.0f, 1.0f, true); // growth scale curve tempCurve = group.distributionPitchCurve; if (GUICurve(PropertyType.Normal, tempCurve, m_CurveRangesB)) { group.distributionPitchCurve = tempCurve; } GUI.enabled = true; EditorGUILayout.Space(); } // // Animation properties inspector (generic) // public void InspectorAnimation(TreeData treeData, TreeGroup group) { if (group == null) return; PrepareSpacing(false); group.animationPrimary = GUISlider(PropertyType.Normal, group.MainWindString, group.animationPrimary, 0.0f, 1.0f, false); // not for trunks if (treeData.GetGroup(group.parentGroupID) != treeData.root) group.animationSecondary = GUISlider(PropertyType.Normal, group.MainTurbulenceString, group.animationSecondary, 0.0f, 1.0f, false); // branches must have fronds GUI.enabled = true; if (!(group is TreeGroupBranch && ((group as TreeGroupBranch).geometryMode == (int)TreeGroupBranch.GeometryMode.Branch))) { group.animationEdge = GUISlider(PropertyType.Normal, group.EdgeTurbulenceString, group.animationEdge, 0.0f, 1.0f, false); } // Create default wind button GUIPropBegin(); if (GUILayout.Button(TreeEditorHelper.GetGUIContent("Create Wind Zone|Creates a default wind zone, which is required for animating trees while playing the game."))) { CreateDefaultWindZone(); } GUIPropEnd(); } private int GUItoolbar(int selection, GUIContent[] names) { GUI.enabled = true; bool preChange = GUI.changed; EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); for (int i = 0; i < names.Length; i++) { GUIStyle buttonStyle = "ButtonMid"; if (i == 0) buttonStyle = "ButtonLeft"; if (i == names.Length - 1) buttonStyle = "ButtonRight"; if (names[i] != null) { if (GUILayout.Toggle(selection == i, names[i], buttonStyle)) selection = i; } } GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); GUI.changed = preChange; return selection; } private void GUIunlockbox(TreeData treeData) { GUILayout.BeginVertical(EditorStyles.helpBox); GUIContent labelContent = TreeEditorHelper.GetGUIContent("This group has been edited by hand. Some parameters may not be available. \nIt cannot be parented to another group |"); labelContent.image = styles.warningIcon.image; GUILayout.Label(labelContent, EditorStyles.wordWrappedMiniLabel); GUIStyle helpButtonStyle = "wordwrapminibutton"; GUIContent buttonContent = TreeEditorHelper.GetGUIContent("Convert to procedural group. All hand editing will be lost!|"); if (GUILayout.Button(buttonContent, helpButtonStyle)) { treeData.UnlockGroup(s_SelectedGroup); m_WantCompleteUpdate = true; } GUILayout.EndVertical(); } void PrepareSpacing(bool hasCurves) { m_SectionHasCurves = hasCurves; EditorGUIUtility.labelWidth = hasCurves ? 100 : 120; } private bool GUIMaterialColor(Material material, string propertyID, string contentID) { bool changed = false; GUIPropBegin(); Color value = material.GetColor(propertyID); Color newValue = EditorGUILayout.ColorField(TreeEditorHelper.GetGUIContent(contentID), value); if (newValue != value) { Undo.RegisterCompleteObjectUndo(material, "Material"); material.SetColor(propertyID, newValue); changed = true; } GUIPropEnd(); return changed; } private bool GUIMaterialSlider(Material material, string propertyID, string contentID) { bool changed = false; GUIPropBegin(); float value = material.GetFloat(propertyID); float newValue = EditorGUILayout.Slider(TreeEditorHelper.GetGUIContent(contentID), value, 0, 1); if (newValue != value) { Undo.RegisterCompleteObjectUndo(material, "Material"); material.SetFloat(propertyID, newValue); changed = true; } GUIPropEnd(); return changed; } private bool GUIMaterialFloatField(Material material, string propertyID, string contentID) { bool success; float value = GetMaterialFloat(material, propertyID, out success); if (!success) return false; bool changed = false; GUIPropBegin(); float newValue = EditorGUILayout.FloatField(TreeEditorHelper.GetGUIContent(contentID), value); if (newValue != value) { Undo.RegisterCompleteObjectUndo(material, "Material"); material.SetFloat(propertyID, newValue); changed = true; } GUIPropEnd(); return changed; } private static float GetMaterialFloat(Material material, string propertyID, out bool success) { success = false; if (!material.HasProperty(propertyID)) return 0.0f; success = true; return material.GetFloat(propertyID); } private static float GetMaterialFloat(Material material, string propertyID) { bool success; return GetMaterialFloat(material, propertyID, out success); } private static float GenerateMaterialHash(Material material) { float hash = 0; Color color = material.GetColor("_TranslucencyColor"); hash += color.r + color.g + color.b + color.a; hash += GetMaterialFloat(material, "_Cutoff"); hash += GetMaterialFloat(material, "_TranslucencyViewDependency"); hash += GetMaterialFloat(material, "_ShadowStrength"); hash += GetMaterialFloat(material, "_ShadowOffsetScale"); return hash; } public void InspectorRoot(TreeData treeData, TreeGroupRoot group) { GUIContent[] categoryNames = { TreeEditorHelper.GetGUIContent(L10n.Tr("Distribution|")), TreeEditorHelper.GetGUIContent(L10n.Tr("Geometry|")), TreeEditorHelper.GetGUIContent(L10n.Tr("Material|Controls global material properties of the tree.")), null, null, null}; bool guiEnabled = GUI.enabled; // // Distribution props // BeginSettingsSection(0, categoryNames); PrepareSpacing(false); int pre = group.seed; group.seed = GUIIntSlider(PropertyType.Normal, treeSeedString, group.seed, 0, 9999999, false); if (group.seed != pre) { treeData.UpdateSeed(group.uniqueID); } group.rootSpread = GUISlider(PropertyType.Normal, areaSpreadString, group.rootSpread, 0.0f, 10.0f, false); group.groundOffset = GUISlider(PropertyType.Normal, groundOffsetString, group.groundOffset, 0.0f, 10.0f, false); EndSettingsSection(); // // Geometry props // BeginSettingsSection(1, categoryNames); PrepareSpacing(false); group.adaptiveLODQuality = GUISlider(PropertyType.FullUndo, lodQualityString, group.adaptiveLODQuality, 0.0f, 1.0f, false); group.enableAmbientOcclusion = GUIToggle(PropertyType.FullUndo, ambientOcclusionString, group.enableAmbientOcclusion, false); GUI.enabled = group.enableAmbientOcclusion; group.aoDensity = GUISlider(PropertyType.Normal, aoDensityString, group.aoDensity, 0.0f, 1.0f, false); GUI.enabled = true; EndSettingsSection(); // // Material props // Material leafMaterial = treeData.optimizedCutoutMaterial; if (leafMaterial != null) { BeginSettingsSection(2, categoryNames); PrepareSpacing(false); bool guiChanged = GUI.changed; bool changed = GUIMaterialColor(leafMaterial, "_TranslucencyColor", translucencyColorString); changed |= GUIMaterialSlider(leafMaterial, "_TranslucencyViewDependency", transViewDepString); changed |= GUIMaterialSlider(leafMaterial, "_Cutoff", alphaCutoffString); changed |= GUIMaterialSlider(leafMaterial, "_ShadowStrength", shadowStrengthString); changed |= GUIMaterialFloatField(leafMaterial, "_ShadowOffsetScale", shadowOffsetString); if (changed) s_CutoutMaterialHashBeforeUndo = GenerateMaterialHash(treeData.optimizedCutoutMaterial); group.shadowTextureQuality = GUIPopup(PropertyType.FullUpdate, shadowCasterResString, leafMaterialOptions, group.shadowTextureQuality, false); GUI.changed = guiChanged; EndSettingsSection(); } GUI.enabled = guiEnabled; EditorGUILayout.Space(); } public void InspectorBranch(TreeData treeData, TreeGroupBranch group) { InspectorEditTools(target as Tree); GUIContent[] categoryNames = { TreeEditorHelper.GetGUIContent(L10n.Tr("Distribution|Adjusts the count and placement of branches in the group. Use the curves to fine tune position, rotation and scale. The curves are relative to the parent branch or to the area spread in case of a trunk.")), TreeEditorHelper.GetGUIContent(L10n.Tr("Geometry|Select what type of geometry is generated for this branch group and which materials are applied. LOD Multiplier allows you to adjust the quality of this group relative to tree's LOD Quality.")), TreeEditorHelper.GetGUIContent(L10n.Tr("Shape|Adjusts the shape and growth of the branches. Use the curves to fine tune the shape, all curves are relative to the branch itself.")), TreeEditorHelper.GetGUIContent(L10n.Tr("Fronds|")), TreeEditorHelper.GetGUIContent(L10n.Tr("Wind|Adjusts the parameters used for animating this group of branches. The wind zones are only active in Play Mode.")) }; bool guiEnabled = GUI.enabled; // Locked group warning if (s_SelectedGroup.lockFlags != 0) { GUIunlockbox(treeData); } AnimationCurve tempCurve; // Distribution (Standard) BeginSettingsSection(0, categoryNames); InspectorDistribution(treeData, group); EndSettingsSection(); // Geometry BeginSettingsSection(1, categoryNames); PrepareSpacing(false); group.lodQualityMultiplier = GUISlider(PropertyType.Normal, lodMultiplierString, group.lodQualityMultiplier, 0.0f, 2.0f, false); group.geometryMode = (TreeGroupBranch.GeometryMode)GUIPopup(PropertyType.FullUpdate, geometryModeString, categoryNamesOptions, (int)group.geometryMode, false); if (group.geometryMode != TreeGroupBranch.GeometryMode.Frond) group.materialBranch = GUIMaterialField(PropertyType.FullUpdate, group.uniqueID, branchMaterialString, group.materialBranch, TreeEditorHelper.NodeType.BarkNode); group.materialBreak = GUIMaterialField(PropertyType.FullUpdate, group.uniqueID, breakMaterialString, group.materialBreak, TreeEditorHelper.NodeType.BarkNode); if (group.geometryMode != TreeGroupBranch.GeometryMode.Branch) group.materialFrond = GUIMaterialField(PropertyType.FullUpdate, group.uniqueID, frondMaterialString, group.materialFrond, TreeEditorHelper.NodeType.BarkNode); EndSettingsSection(); BeginSettingsSection(2, categoryNames); PrepareSpacing(true); // // General Shape // GUI.enabled = (group.lockFlags == 0); group.height = GUIMinMaxSlider(PropertyType.Normal, lengthString, group.height, 0.1f, 50.0f, false); GUI.enabled = (group.geometryMode != TreeGroupBranch.GeometryMode.Frond); group.radiusMode = GUIToggle(PropertyType.Normal, relativeLengthString, group.radiusMode, false); GUI.enabled = (group.geometryMode != TreeGroupBranch.GeometryMode.Frond); group.radius = GUISlider(PropertyType.Normal, radiusString, group.radius, 0.1f, 5.0f, true); tempCurve = group.radiusCurve; if (GUICurve(PropertyType.Normal, tempCurve, m_CurveRangesA)) { group.radiusCurve = tempCurve; } GUI.enabled = (group.geometryMode != TreeGroupBranch.GeometryMode.Frond); group.capSmoothing = GUISlider(PropertyType.Normal, capSmoothingString, group.capSmoothing, 0.0f, 1.0f, false); GUI.enabled = true; EditorGUILayout.Space(); // // Growth // GUI.enabled = (group.lockFlags == 0); group.crinklyness = GUISlider(PropertyType.Normal, crinklynessString, group.crinklyness, 0.0f, 1.0f, true); tempCurve = group.crinkCurve; if (GUICurve(PropertyType.Normal, tempCurve, m_CurveRangesA)) { group.crinkCurve = tempCurve; } GUI.enabled = (group.lockFlags == 0); group.seekBlend = GUISlider(PropertyType.Normal, seekSunString, group.seekBlend, 0.0f, 1.0f, true); tempCurve = group.seekCurve; if (GUICurve(PropertyType.Normal, tempCurve, m_CurveRangesB)) { group.seekCurve = tempCurve; } GUI.enabled = true; EditorGUILayout.Space(); // // Surface Noise // // Only enabled if there is branch geometry GUI.enabled = (group.geometryMode != TreeGroupBranch.GeometryMode.Frond); group.noise = GUISlider(PropertyType.Normal, noiseString, group.noise, 0.0f, 1.0f, true); tempCurve = group.noiseCurve; if (GUICurve(PropertyType.Normal, tempCurve, m_CurveRangesA)) { group.noiseCurve = tempCurve; } group.noiseScaleU = GUISlider(PropertyType.Normal, noiseScaleUString, group.noiseScaleU, 0.0f, 1.0f, false); group.noiseScaleV = GUISlider(PropertyType.Normal, noiseScaleVString, group.noiseScaleV, 0.0f, 1.0f, false); EditorGUILayout.Space(); // Only enabled if there is branch geometry GUI.enabled = (group.geometryMode != TreeGroupBranch.GeometryMode.Frond); if (treeData.GetGroup(group.parentGroupID) == treeData.root) { // // Flares // group.flareSize = GUISlider(PropertyType.Normal, flareRadiusString, group.flareSize, 0.0f, 5.0f, false); group.flareHeight = GUISlider(PropertyType.Normal, flareHeightString, group.flareHeight, 0.0f, 1.0f, false); group.flareNoise = GUISlider(PropertyType.Normal, flareNoiseString, group.flareNoise, 0.0f, 1.0f, false); } else { // // Welding // group.weldHeight = GUISlider(PropertyType.Normal, weldLengthString, group.weldHeight, 0.01f, 1.0f, false); group.weldSpreadTop = GUISlider(PropertyType.Normal, spreadTopString, group.weldSpreadTop, 0.0f, 1.0f, false); group.weldSpreadBottom = GUISlider(PropertyType.Normal, spreadBottomString, group.weldSpreadBottom, 0.0f, 1.0f, false); } EditorGUILayout.Space(); // Breaking group.breakingChance = GUISlider(PropertyType.Normal, breakChanceString, group.breakingChance, 0.0f, 1.0f, false); group.breakingSpot = GUIMinMaxSlider(PropertyType.Normal, breakLocationString, group.breakingSpot, 0.0f, 1.0f, false); EndSettingsSection(); // Fronds if (group.geometryMode != (int)(TreeGroupBranch.GeometryMode.Branch)) { BeginSettingsSection(3, categoryNames); PrepareSpacing(true); group.frondCount = GUIIntSlider(PropertyType.Normal, frondCountString, group.frondCount, 1, 16, false); group.frondWidth = GUISlider(PropertyType.Normal, frondWidthString, group.frondWidth, 0.1f, 10.0f, true); tempCurve = group.frondCurve; if (GUICurve(PropertyType.Normal, tempCurve, m_CurveRangesA)) { group.frondCurve = tempCurve; } group.frondRange = GUIMinMaxSlider(PropertyType.Normal, frondRangeString, group.frondRange, 0.0f, 1.0f, false); group.frondRotation = GUISlider(PropertyType.Normal, frondRotationString, group.frondRotation, 0.0f, 1.0f, false); group.frondCrease = GUISlider(PropertyType.Normal, frondCreaseString, group.frondCrease, -1.0f, 1.0f, false); GUI.enabled = true; EndSettingsSection(); } BeginSettingsSection(4, categoryNames); // Animation InspectorAnimation(treeData, group); EndSettingsSection(); GUI.enabled = guiEnabled; EditorGUILayout.Space(); } public void InspectorLeaf(TreeData treeData, TreeGroupLeaf group) { InspectorEditTools(target as Tree); GUIContent[] categoryNames = { TreeEditorHelper.GetGUIContent("Distribution|Adjusts the count and placement of leaves in the group. Use the curves to fine tune position, rotation and scale. The curves are relative to the parent branch."), TreeEditorHelper.GetGUIContent("Geometry|Select what type of geometry is generated for this leaf group and which materials are applied. If you use a custom mesh, its materials will be used."), TreeEditorHelper.GetGUIContent("Shape|Adjusts the shape and growth of the leaves."), null, null, TreeEditorHelper.GetGUIContent("Wind|Adjusts the parameters used for animating this group of leaves. Wind zones are only active in Play Mode. If you select too high values for Main Wind and Main Turbulence the leaves may float away from the branches.") }; bool guiEnabled = GUI.enabled; // Locked group warning if (s_SelectedGroup.lockFlags != 0) { GUIunlockbox(treeData); } BeginSettingsSection(0, categoryNames); // Distribution InspectorDistribution(treeData, group); EndSettingsSection(); BeginSettingsSection(1, categoryNames); PrepareSpacing(false); // Geometry group.geometryMode = GUIPopup(PropertyType.FullUpdate, geometryModeLeafString, geometryModeOptions, group.geometryMode, false); if (group.geometryMode != (int)TreeGroupLeaf.GeometryMode.MESH) group.materialLeaf = GUIMaterialField(PropertyType.FullUpdate, group.uniqueID, materialLeafString, group.materialLeaf, TreeEditorHelper.NodeType.LeafNode); if (group.geometryMode == (int)TreeGroupLeaf.GeometryMode.MESH) group.instanceMesh = GUIObjectField(PropertyType.FullUpdate, meshString, group.instanceMesh, typeof(GameObject), false) as GameObject; EndSettingsSection(); BeginSettingsSection(2, categoryNames); PrepareSpacing(false); // Shape group.size = GUIMinMaxSlider(PropertyType.Normal, sizeString, group.size, 0.1f, 2.0f, false); group.perpendicularAlign = GUISlider(PropertyType.Normal, perpendicularAlignString, group.perpendicularAlign, 0.0f, 1.0f, false); group.horizontalAlign = GUISlider(PropertyType.Normal, horizontalAlignString, group.horizontalAlign, 0.0f, 1.0f, false); EndSettingsSection(); BeginSettingsSection(5, categoryNames); PrepareSpacing(false); // Animation InspectorAnimation(treeData, group); EndSettingsSection(); GUI.enabled = guiEnabled; EditorGUILayout.Space(); } public override bool UseDefaultMargins() { return false; } public override void OnInspectorGUI() { // make sure it's a tree Tree obj = target as Tree; TreeData treeData = GetTreeData(obj); if (!treeData) return; Renderer renderer = obj.GetComponent<Renderer>(); // make sure selection is ok VerifySelection(treeData); if (s_SelectedGroup == null) { return; } // reset complete update flag m_WantCompleteUpdate = false; // We just want events in this window - checking on Event.current.type won't work EventType hotControlType = Event.current.GetTypeForControl(GUIUtility.hotControl); // MouseUp works for most controls, need to check Return and OnLostFocus for controls with text fields if (hotControlType == EventType.MouseUp || (hotControlType == EventType.KeyUp && Event.current.keyCode == KeyCode.Return) || (hotControlType == EventType.ExecuteCommand && Event.current.commandName == "OnLostFocus")) { if (treeData.isInPreviewMode) { // We need a complete rebuild.. m_WantCompleteUpdate = true; } } // Check for hotkey event if (OnCheckHotkeys(treeData, true)) return; // Refresh all tree shaders to validate whether we don't have too many // and in case a node is not using a tree shader - recommend one already used. m_TreeEditorHelper.RefreshAllTreeShaders(); if (m_TreeEditorHelper.GUITooManyShaders()) m_WantCompleteUpdate = true; EditorGUILayout.Space(); EditorGUILayout.BeginVertical(EditorStyles.inspectorFullWidthMargins); InspectorHierachy(treeData, renderer); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(EditorStyles.inspectorDefaultMargins); if (s_SelectedGroup != null) { if (s_SelectedGroup.GetType() == typeof(TreeGroupBranch)) { InspectorBranch(treeData, (TreeGroupBranch)s_SelectedGroup); } else if (s_SelectedGroup.GetType() == typeof(TreeGroupLeaf)) { InspectorLeaf(treeData, (TreeGroupLeaf)s_SelectedGroup); } else if (s_SelectedGroup.GetType() == typeof(TreeGroupRoot)) { InspectorRoot(treeData, (TreeGroupRoot)s_SelectedGroup); } } EditorGUILayout.EndVertical(); if (m_WantedCompleteUpdateInPreviousFrame) m_WantCompleteUpdate = true; m_WantedCompleteUpdateInPreviousFrame = false; // HACKY! if (m_WantCompleteUpdate) { GUI.changed = true; } if (GUI.changed) { if (!m_TreeEditorHelper.AreShadersCorrect()) { m_WantedCompleteUpdateInPreviousFrame = m_WantCompleteUpdate; return; } if (m_WantCompleteUpdate) { // full update UpdateMesh(obj); m_WantCompleteUpdate = false; } else { // preview update PreviewMesh(obj); } } } public class Styles { public GUIContent iconAddLeaves = EditorGUIUtility.TrIconContent("TreeEditor.AddLeaves", "Add Leaf Group"); public GUIContent iconAddBranches = EditorGUIUtility.TrIconContent("TreeEditor.AddBranches", "Add Branch Group"); public GUIContent iconTrash = EditorGUIUtility.TrIconContent("TreeEditor.Trash", "Delete Selected Group"); public GUIContent iconDuplicate = EditorGUIUtility.TrIconContent("TreeEditor.Duplicate", "Duplicate Selected Group"); public GUIContent iconRefresh = EditorGUIUtility.TrIconContent("TreeEditor.Refresh", "Recompute Tree"); public GUIStyle toolbar = "TE Toolbar"; public GUIStyle toolbarButton = "TE toolbarbutton"; public GUIStyle nodeBackground = "TE NodeBackground"; public GUIStyle[] nodeBoxes = { "TE NodeBox", "TE NodeBoxSelected" }; public GUIContent warningIcon = EditorGUIUtility.IconContent("editicon.sml"); public GUIContent[] nodeIcons = { EditorGUIUtility.IconContent("tree_icon_branch_frond"), EditorGUIUtility.IconContent("tree_icon_branch"), EditorGUIUtility.IconContent("tree_icon_frond"), EditorGUIUtility.IconContent("tree_icon_leaf"), EditorGUIUtility.IconContent("tree_icon") }; public GUIContent[] visibilityIcons = { EditorGUIUtility.IconContent("animationvisibilitytoggleon"), EditorGUIUtility.IconContent("animationvisibilitytoggleoff") }; public GUIStyle nodeLabelTop = "TE NodeLabelTop"; public GUIStyle nodeLabelBot = "TE NodeLabelBot"; public GUIStyle pinLabel = "TE PinLabel"; } public static Styles styles; Vector2 hierachyScroll = new Vector2(); Vector2 hierachyNodeSize = new Vector2(40.0f, 48.0f); Vector2 hierachyNodeSpace = new Vector2(16.0f, 16.0f); Vector2 hierachySpread = new Vector2(32.0f, 32.0f); Rect hierachyView = new Rect(0, 0, 0, 0); Rect hierachyRect = new Rect(0, 0, 0, 0); Rect hierachyDisplayRect = new Rect(0, 0, 0, 0); HierachyNode dragNode = null; HierachyNode dropNode = null; bool isDragging = false; Vector2 dragClickPos; internal class HierachyNode { internal Vector3 pos; internal TreeGroup group; internal Rect rect; } void DrawHierachy(TreeData treeData, Renderer renderer, Rect sizeRect) { if (styles == null) styles = new Styles(); hierachySpread = hierachyNodeSize + hierachyNodeSpace; hierachyView = sizeRect; Event cloneEvent = new Event(Event.current); List<HierachyNode> nodes = new List<HierachyNode>(); BuildHierachyNodes(treeData, nodes, treeData.root, 0); LayoutHierachyNodes(nodes, sizeRect); // begin scroll view float oversize = 16.0f; Vector2 offset = Vector2.zero; if (sizeRect.width < hierachyRect.width) { offset.y -= 16.0f; } bool clear = GUI.changed; hierachyDisplayRect = GUILayoutUtility.GetRect(sizeRect.width, hierachyRect.height + oversize); hierachyDisplayRect.width = sizeRect.width; // background GUI.Box(hierachyDisplayRect, GUIContent.none, styles.nodeBackground); hierachyScroll = GUI.BeginScrollView(hierachyDisplayRect, hierachyScroll, hierachyRect, false, false); GUI.changed = clear; // handle dragging HandleDragHierachyNodes(treeData, nodes); // draw nodes DrawHierachyNodes(treeData, nodes, treeData.root, offset / 2, 1.0f, 1.0f); // draw drag nodes if (dragNode != null && isDragging) { Vector2 dragOffset = Event.current.mousePosition - dragClickPos; DrawHierachyNodes(treeData, nodes, dragNode.group, dragOffset + offset / 2, 0.5f, 0.5f); } // end scroll view // EditorGUILayout.EndScrollView(); GUI.EndScrollView(); // draw stats if (renderer) { MeshFilter m = renderer.GetComponent<MeshFilter>(); if (m && m.sharedMesh && renderer) { int vs = m.sharedMesh.vertices.Length; int ts = m.sharedMesh.triangles.Length / 3; int ms = renderer.sharedMaterials.Length; Rect labelrect = new Rect(hierachyDisplayRect.xMax - 80 - 4, hierachyDisplayRect.yMax + offset.y - 40 - 4, 80, 40); string text = TreeEditorHelper.GetGUIContent("Hierarchy Stats").text; text = text.Replace("[v]", vs.ToString()); text = text.Replace("[t]", ts.ToString()); text = text.Replace("[m]", ms.ToString()); text = text.Replace(" / ", "\n"); GUI.Label(labelrect, text, EditorStyles.helpBox); } } // Pass scroll wheel event through.. if ((cloneEvent.type == EventType.ScrollWheel) && (Event.current.type == EventType.Used)) { Event.current = cloneEvent; } } void BuildHierachyNodes(TreeData treeData, List<HierachyNode> nodes, TreeGroup group, int depth) { HierachyNode node = new HierachyNode(); node.group = group; node.pos = new Vector3(0, depth * hierachySpread.y, 0); nodes.Add(node); for (int i = 0; i < group.childGroupIDs.Length; i++) { TreeGroup childGroup = treeData.GetGroup(group.childGroupIDs[i]); BuildHierachyNodes(treeData, nodes, childGroup, depth - 1); } } void LayoutHierachyNodes(List<HierachyNode> nodes, Rect sizeRect) { Bounds bounds = new Bounds(); for (int i = 0; i < nodes.Count; i++) { for (int j = i + 1; j < nodes.Count; j++) { if (nodes[i].pos.y == nodes[j].pos.y) { nodes[i].pos.x -= hierachySpread.x * 0.5f; nodes[j].pos.x = nodes[i].pos.x + hierachySpread.x; } } bounds.Encapsulate(nodes[i].pos); } bounds.Expand(hierachySpread); hierachyRect = new Rect(0, 0, bounds.size.x, bounds.size.y); //hierachyRect.height = Mathf.Max(hierachyRect.height, hierachyView.height); hierachyRect.width = Mathf.Max(hierachyRect.width, hierachyView.width); Vector3 cen = new Vector3((hierachyRect.xMax + hierachyRect.xMin) * 0.5f, (hierachyRect.yMax + hierachyRect.yMin) * 0.5f, 0.0f); cen.y += 8.0f; for (int i = 0; i < nodes.Count; i++) { nodes[i].pos -= bounds.center; nodes[i].pos.x += cen.x; nodes[i].pos.y += cen.y; nodes[i].rect = new Rect(nodes[i].pos.x - hierachyNodeSize.x * 0.5f, nodes[i].pos.y - hierachyNodeSize.y * 0.5f, hierachyNodeSize.x, hierachyNodeSize.y); } } void HandleDragHierachyNodes(TreeData treeData, List<HierachyNode> nodes) { if (dragNode == null) { isDragging = false; dropNode = null; } int handleID = GUIUtility.GetControlID(FocusType.Passive); EventType eventType = Event.current.GetTypeForControl(handleID); // on left mouse button down if (eventType == EventType.MouseDown && Event.current.button == 0) { for (int i = 0; i < nodes.Count; i++) { // continue if not in the node's rect if (!nodes[i].rect.Contains(Event.current.mousePosition)) continue; // don't drag from visibility checkbox rect if (GetHierachyNodeVisRect(nodes[i].rect).Contains(Event.current.mousePosition)) continue; // don't drag root node if (nodes[i].group is TreeGroupRoot) continue; // start dragging dragClickPos = Event.current.mousePosition; dragNode = nodes[i]; GUIUtility.hotControl = handleID; Event.current.Use(); break; } } if (dragNode != null) { // find a drop node dropNode = null; for (int i = 0; i < nodes.Count; i++) { // Are we over this node? if (nodes[i].rect.Contains(Event.current.mousePosition)) { // // Verify drop-target is valid // TreeGroup sourceGroup = dragNode.group; TreeGroup targetGroup = nodes[i].group; if (targetGroup == sourceGroup) { // Dropping on itself.. do nothing } else if (!targetGroup.CanHaveSubGroups()) { // Drop target cannot have a sub group // Debug.Log("Drop target cannot have subGroups"); } else if (treeData.GetGroup(sourceGroup.parentGroupID) == targetGroup) { // No need to do anything // Debug.Log("Drop target already parent of Drag node .. IGNORING"); } else if (treeData.IsAncestor(sourceGroup, targetGroup)) { // Would create cyclic-dependency // Debug.Log("Drop target is a subGroup of Drag node"); } else { // Drop target is ok! dropNode = nodes[i]; break; } } } if (eventType == EventType.MouseMove || eventType == EventType.MouseDrag) { Vector2 delta = dragClickPos - Event.current.mousePosition; if (delta.magnitude > 10.0f) { isDragging = true; } Event.current.Use(); } else if (eventType == EventType.MouseUp) { if (GUIUtility.hotControl == handleID) { // finish dragging && don't reparent the group if the group is locked if (dropNode != null && dragNode.group.lockFlags == 0) { // Store Complete Undo.. UndoStoreSelected(EditMode.Everything); // Relink TreeGroup sourceGroup = dragNode.group; TreeGroup targetGroup = dropNode.group; treeData.SetGroupParent(sourceGroup, targetGroup); // Tell editor to do full mesh update m_WantCompleteUpdate = true; } else { // the nodes have not been dropped on a drop node so e.g. // they landed outside of the hierarchy viewask for a repaint Repaint(); } // clear and exit dragNode = null; dropNode = null; // cleanup drag GUIUtility.hotControl = 0; Event.current.Use(); } } } } Rect GetHierachyNodeVisRect(Rect rect) { return new Rect(rect.x + rect.width - 13.0f - 1.0f, rect.y + 11, 13.0f, 11.0f); } void DrawHierachyNodes(TreeData treeData, List<HierachyNode> nodes, TreeGroup group, Vector2 offset, float alpha, float fade) { // fade if ((dragNode != null) && isDragging) { if (dragNode.group == group) { alpha = 0.5f; fade = 0.75f; } } Vector3 delta = new Vector3(0, hierachyNodeSize.y * 0.5f, 0); Vector3 offset3 = new Vector3(offset.x, offset.y); Handles.color = new Color(0.0f, 0.0f, 0.0f, 0.5f * alpha); if (EditorGUIUtility.isProSkin) Handles.color = new Color(0.4f, 0.4f, 0.4f, 0.5f * alpha); // find node for this group.. HierachyNode node = null; for (int i = 0; i < nodes.Count; i++) { if (group == nodes[i].group) { node = nodes[i]; break; } } if (node == null) { return; } for (int j = 0; j < group.childGroupIDs.Length; j++) { TreeGroup childGroup = treeData.GetGroup(group.childGroupIDs[j]); for (int k = 0; k < nodes.Count; k++) { if (nodes[k].group == childGroup) { Handles.DrawLine(node.pos + offset3 - delta, nodes[k].pos + offset3 + delta); } } } Rect rect = node.rect; rect.x += offset.x; rect.y += offset.y; int nodeBoxIndex = 0; if (node == dropNode) { // hovering over this node which is a valid drop-target nodeBoxIndex = 1; } else if (s_SelectedGroup == node.group) { if (s_SelectedNode != null) { // node selected nodeBoxIndex = 1; } else { // only the group is selected nodeBoxIndex = 1; } } GUI.backgroundColor = new Color(1, 1, 1, alpha); GUI.contentColor = new Color(1, 1, 1, alpha); GUI.Label(rect, GUIContent.none, styles.nodeBoxes[nodeBoxIndex]); // GUI.Label(rect, styles.nodeBoxes[nodeBoxIndex]); Rect pinRectTop = new Rect(rect.x + rect.width / 2f - 4.0f, rect.y - 2.0f, 0f, 0f); Rect pinRectBot = new Rect(rect.x + rect.width / 2f - 4.0f, rect.y + rect.height - 2.0f, 0f, 0f); Rect iconRect = new Rect(rect.x + 1.0f, rect.yMax - 36f, 32.0f , 32.0f); Rect editRect = new Rect(rect.xMax - 18.0f, rect.yMax - 18.0f, 16.0f, 16.0f); Rect labelRect = new Rect(rect.x, rect.y, rect.width - 2.0f, 16.0f); // Select correct icon bool showExtras = true; int iconIndex = 0; GUIContent buttonContent = new GUIContent(); System.Type typ = group.GetType(); if (typ == typeof(TreeGroupBranch)) { buttonContent = TreeEditorHelper.GetGUIContent("|Branch Group"); TreeGroupBranch br = (TreeGroupBranch)group; switch (br.geometryMode) { case TreeGroupBranch.GeometryMode.BranchFrond: iconIndex = 0; break; case TreeGroupBranch.GeometryMode.Branch: iconIndex = 1; break; case TreeGroupBranch.GeometryMode.Frond: iconIndex = 2; break; } } else if (typ == typeof(TreeGroupLeaf)) { buttonContent = TreeEditorHelper.GetGUIContent("|Leaf Group"); iconIndex = 3; } else if (typ == typeof(TreeGroupRoot)) { buttonContent = TreeEditorHelper.GetGUIContent("|Tree Root Node"); iconIndex = 4; showExtras = false; } // anything but the root if (showExtras) { // visibility // Rect rect = HierachyNodeRect(nodes, i); Rect visRect = GetHierachyNodeVisRect(rect); GUIContent visContent = TreeEditorHelper.GetGUIContent("|Show / Hide Group"); visContent.image = styles.visibilityIcons[group.visible ? 0 : 1].image; GUI.contentColor = new Color(1, 1, 1, 0.7f); if (GUI.Button(visRect, visContent, GUIStyle.none)) { group.visible = !group.visible; GUI.changed = true; } GUI.contentColor = Color.white; } // Icon, click to select.. buttonContent.image = styles.nodeIcons[iconIndex].image; GUI.contentColor = new Color(1, 1, 1, group.visible ? 1 : 0.5f); if (GUI.Button(iconRect, buttonContent, GUIStyle.none) || (dragNode == node)) { TreeGroup preSelect = s_SelectedGroup; SelectGroup(group); if (preSelect == s_SelectedGroup) { Tree tree = target as Tree; FrameSelected(tree); } } GUI.contentColor = Color.white; // only show top attachement pin if needed if (group.CanHaveSubGroups()) { GUI.Label(pinRectTop, GUIContent.none, styles.pinLabel); } // anything but the root if (showExtras) { GUIContent nodeContent = TreeEditorHelper.GetGUIContent("|Node Count"); nodeContent.text = group.nodeIDs.Length.ToString(); GUI.Label(labelRect, nodeContent, styles.nodeLabelTop); // one of the node's material has a wrong shader if (m_TreeEditorHelper.NodeHasWrongMaterial(group)) { GUI.DrawTexture(editRect, ConsoleWindow.iconErrorSmall); } // edited by hand else if (group.lockFlags != 0) { GUI.DrawTexture(editRect, styles.warningIcon.image); } GUI.Label(pinRectBot, GUIContent.none, styles.pinLabel); } // Draw sub groups.. for (int j = 0; j < group.childGroupIDs.Length; j++) { TreeGroup childGroup = treeData.GetGroup(group.childGroupIDs[j]); DrawHierachyNodes(treeData, nodes, childGroup, offset, alpha * fade, fade); } GUI.backgroundColor = Color.white; GUI.contentColor = Color.white; } private static void BeginSettingsSection(int nr, GUIContent[] names) { GUILayout.Space(kSectionSpace / 2.0f); GUILayout.Label(names[nr].text, EditorStyles.boldLabel); } private static void EndSettingsSection() { GUI.enabled = true; GUILayout.Space(kSectionSpace / 2.0f); } } }
UnityCsReference/Modules/TreeEditor/TreeEditor.cs/0
{ "file_path": "UnityCsReference/Modules/TreeEditor/TreeEditor.cs", "repo_id": "UnityCsReference", "token_count": 64029 }
461
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using PackageInfo = UnityEditor.PackageManager.PackageInfo; using System.Linq; using UnityEditor; using UnityEngine; namespace Unity.UI.Builder { static class BuilderExternalPackages { public static bool is2DSpriteEditorInstalled { get { var packageInfo = PackageInfo.FindForPackageName("com.unity.2d.sprite"); if (packageInfo != null) return packageInfo.version == "1.0.0"; return false; } } public static void Open2DSpriteEditor(Object value) { SpriteUtilityWindow.ShowSpriteEditorWindow(value); } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/BuilderExternalPackages.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/BuilderExternalPackages.cs", "repo_id": "UnityCsReference", "token_count": 362 }
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.Collections.Generic; using System.Linq; using UnityEditor; using UnityEngine; using UnityEngine.UIElements; namespace Unity.UI.Builder { internal class BuilderViewportDragger : BuilderHierarchyDragger { public BuilderViewportDragger( BuilderPaneWindow paneWindow, VisualElement root, BuilderSelection selection, BuilderViewport viewport = null, BuilderParentTracker parentTracker = null) : base(paneWindow, root, selection, viewport, parentTracker) { } protected override VisualElement ExplorerGetDragPreviewFromTarget(VisualElement target, Vector2 mousePosition) { var picked = viewport.PickElement(mousePosition); return picked; } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Draggers/BuilderViewportDragger.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Draggers/BuilderViewportDragger.cs", "repo_id": "UnityCsReference", "token_count": 336 }
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 System.Collections.Generic; using Unity.Properties; using UnityEditor.UIElements; using UnityEngine; using UnityEngine.Pool; using UnityEngine.UIElements; namespace Unity.UI.Builder { /// <summary> /// Utility class used to create, edit and find bindings. /// </summary> static class BuilderBindingUtility { private const float k_WindowWidth = 560; private const float k_WindowHeight = 460; private const float k_Spacing = 10; public static UxmlObjectAsset FindUxmlBinding(VisualTreeAsset vta, VisualElementAsset element, string property) { var entry = vta.GetUxmlObjectEntry(element.id); if (entry.uxmlObjectAssets == null || entry.uxmlObjectAssets.Count == 0) return null; var description = UxmlSerializedDataRegistry.GetDescription(typeof(VisualElement).FullName); var attributeDescription = description.FindAttributeWithPropertyName("bindings"); foreach (var obj in entry.uxmlObjectAssets) { var fullType = obj.fullTypeName; var rootName = (attributeDescription as UxmlSerializedUxmlObjectAttributeDescription)?.rootName ?? attributeDescription.name; if (obj.isField && fullType == rootName) { var bindingEntry = vta.GetUxmlObjectEntry(obj.id); foreach (var bindingObj in bindingEntry.uxmlObjectAssets) { if (bindingObj.GetAttributeValue("property") == property) return bindingObj; } } else if (obj.GetAttributeValue("property") == property) { return obj; } } return null; } /// <summary> /// Finds the binding that binds the specified property of the selected VisualElement to a data source. /// </summary> /// <param name="property">The property for which we seek a related binding.</param> /// <param name="binding">The binding instance we seek.</param> /// <param name="uxmlBindingAsset">The uxml element related to the binding instance.</param> /// <returns>Returns true if a binding on the specified property is found; otherwise returns false.</returns> public static bool TryGetBinding(string property, out Binding binding, out UxmlObjectAsset uxmlBindingAsset) { var builder = Builder.ActiveWindow; var vta = builder.document.visualTreeAsset; var currentVe = builder.inspector.currentVisualElement; var vea = currentVe.GetVisualElementAsset(); binding = null; uxmlBindingAsset = null; // VisualElementAsset can be null when the inspected element is coming from a template instance. if (vea == null) return false; if (DataBindingUtility.TryGetBinding(builder.inspector.currentVisualElement, new PropertyPath(property), out var bindingInfo)) { binding = bindingInfo.binding; uxmlBindingAsset = FindUxmlBinding(vta, vea, property); } return uxmlBindingAsset != null; } public static object GetBindingDataSourceOrRelativeHierarchicalDataSource(VisualElement element, BindingId id) { if (!element.TryGetBinding(id, out var binding)) return null; if (binding is IDataSourceProvider {dataSource: { }} provider) return provider.dataSource; var context = element.GetHierarchicalDataSourceContext(); var dataSource = context.dataSource; return PropertyContainer.TryGetValue(ref dataSource, context.dataSourcePath, out object relativeDataSource) ? relativeDataSource : dataSource; } private static void OpenBindingWindowToCreateOrEdit(string property, bool openToCreate, BuilderInspector inspector) { var fieldElement = inspector.FindFieldAtPath(property); var windowSize = new Vector2(k_WindowWidth, k_WindowHeight); var worldBound = Rect.zero; if (fieldElement != null) { worldBound = fieldElement.worldBound; // Adjust the position to align with left edge of the field worldBound.x -= k_WindowWidth + k_Spacing; worldBound.y -= (k_WindowHeight - worldBound.height) / 2; } worldBound = GUIUtility.GUIToScreenRect(worldBound); var message = openToCreate ? BuilderConstants.AddBindingTitle : BuilderConstants.EditBindingTitle; // Calls the active Binding window if (BuilderBindingWindow.activeWindow != null) BuilderBindingWindow.activeWindow.Close(); var wnd = BuilderBindingWindow.Open(message, worldBound, windowSize); if (openToCreate) wnd.view.StartCreatingBinding(property, inspector); else wnd.view.StartEditingBinding(property, inspector); } /// <summary> /// Opens the Binding window to create a new binding for the specified property of the selected VisualElement. /// </summary> /// <param name="property">The property to bind.</param> public static void OpenBindingWindowToCreate(string property, BuilderInspector inspector) { OpenBindingWindowToCreateOrEdit(property, true, inspector); } /// <summary> /// Opens the Binding window to edit the binding instance that binds the specified property of the selected VisualElement to a data source. /// </summary> /// <param name="property">The bound property.</param> public static void OpenBindingWindowToEdit(string property, BuilderInspector inspector) { OpenBindingWindowToCreateOrEdit(property, false, inspector); } /// <summary> /// Deletes the binding instance that binds the specified property of the selected VisualElement. /// </summary> /// <param name="fieldElement">The element to unbind.</param> /// <param name="property">The property to unbind.</param> public static void DeleteBinding(VisualElement fieldElement, string property) { if (!TryGetBinding(property, out _, out _)) return; // Remove binding from SerializedData. var builder = Builder.ActiveWindow; builder.inspector.attributeSection.RemoveBindingFromSerializedData(fieldElement, property); builder.OnEnableAfterAllSerialization(); if (property.StartsWith(BuilderConstants.StylePropertyPathPrefix)) { var styleName = BuilderNameUtilities.ConvertCamelToDash(property.Substring(BuilderConstants.StylePropertyPathPrefix.Length)); builder.selection.NotifyOfStylingChange(null, new() {styleName}); } else { builder.selection.NotifyOfHierarchyChange(); } } /// <summary> /// Clear all bindings that can be found in uxml for this element. /// </summary> /// <param name="ve">The visual element to clear bindings from.</param> public static void ClearUxmlBindings(VisualElement ve) { using var pool = ListPool<BindingId>.Get(out var idsToRemove); foreach (var bindingInfo in ve.GetBindingInfos()) { var bindingId = bindingInfo.binding.property; if (bindingId != BindingId.Invalid) { idsToRemove.Add(bindingId); } } foreach (var bindingId in idsToRemove) { ve.ClearBinding(bindingId); } } public static bool IsInlineEditingEnabled(VisualElement field) { var inspector = Builder.ActiveWindow.inspector; return inspector.IsInlineEditingEnabled(field); } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Inspector/Binding/BuilderBindingUtility.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Inspector/Binding/BuilderBindingUtility.cs", "repo_id": "UnityCsReference", "token_count": 3526 }
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 UnityEditor.UIElements; using UnityEngine.UIElements; namespace Unity.UI.Builder { internal class BuilderInspectorPreview : BuilderPaneContent, IBuilderSelectionNotifier { static readonly string s_UssClassName = "unity-builder-selector-preview"; static readonly string s_CheckerboardBackgroundClassName = s_UssClassName + "__checkerboard-background"; static readonly string s_ToggleIconClassName = s_UssClassName + "__toggle-icon"; static readonly string s_DefaultBackgroundClassName = s_UssClassName + "__default-layer"; static readonly string s_TextClassName = s_UssClassName + "__selector-text"; static readonly string s_ContainerClassName = s_UssClassName + "__text-container"; static readonly string s_PreviewTextContent = "Unity\n0123"; Label m_Text; VisualElement m_CheckerboardBackgroundElement; VisualElement m_DefaultBackgroundElement; ToolbarToggle m_BackgroundToggle; BuilderInspector m_Inspector; VisualElement currentVisualElement => m_Inspector.currentVisualElement; public VisualElement defaultBackgroundElement => m_DefaultBackgroundElement; public VisualElement checkerboardBackgroundElement => m_CheckerboardBackgroundElement; public ToolbarToggle backgroundToggle => m_BackgroundToggle; public BuilderInspectorPreview(BuilderInspector inspector) { m_Inspector = inspector; AddToClassList(s_UssClassName); // checkered and default backgrounds m_CheckerboardBackgroundElement = new CheckerboardBackground(); m_CheckerboardBackgroundElement.AddToClassList(s_CheckerboardBackgroundClassName); m_DefaultBackgroundElement = new VisualElement(); m_DefaultBackgroundElement.AddToClassList(s_DefaultBackgroundClassName); m_DefaultBackgroundElement.style.display = DisplayStyle.None; // preview text m_Text = new Label(s_PreviewTextContent); m_Text.AddToClassList(s_TextClassName); m_Text.RemoveFromClassList(Label.ussClassName); m_Text.RemoveFromClassList(TextElement.ussClassName); // transparency toggle m_BackgroundToggle = new ToolbarToggle(); m_BackgroundToggle.tooltip = BuilderConstants.PreviewTransparencyToggleTooltip; m_BackgroundToggle.AddToClassList(s_ToggleIconClassName); m_BackgroundToggle.RegisterValueChangedCallback(ToggleBackground); // preview container var container = new VisualElement(); container.AddToClassList(s_ContainerClassName); container.Add(m_CheckerboardBackgroundElement); container.Add(m_DefaultBackgroundElement); container.Add(m_Text); Add(container); } protected override void OnAttachToPanelDefaultAction() { base.OnAttachToPanelDefaultAction(); RefreshPreview(); } protected override void InitEllipsisMenu() { base.InitEllipsisMenu(); if (pane == null) return; pane.AppendActionToEllipsisMenu( BuilderConstants.PreviewConvertToFloatingWindow, a => m_Inspector.OpenPreviewWindow(), a => DropdownMenuAction.Status.Normal); pane.AppendActionToEllipsisMenu(BuilderConstants.PreviewMinimizeInInspector, a => m_Inspector.TogglePreviewInInspector(), a => !m_Inspector.showingPreview ? DropdownMenuAction.Status.Checked : DropdownMenuAction.Status.Normal); } private void RefreshPreview() { if (currentVisualElement == null) return; SetTextStyles(); } public void ToggleBackground(ChangeEvent<bool> evt) { var value = evt.newValue; m_CheckerboardBackgroundElement.style.display = value ? DisplayStyle.None : DisplayStyle.Flex; m_DefaultBackgroundElement.style.display = value ? DisplayStyle.Flex : DisplayStyle.None; } private void SetTextStyles() { m_Text.style.unityFont = currentVisualElement.resolvedStyle.unityFont; m_Text.style.unityFontDefinition = currentVisualElement.resolvedStyle.unityFontDefinition; m_Text.style.unityFontStyleAndWeight = currentVisualElement.resolvedStyle.unityFontStyleAndWeight; m_Text.style.fontSize = currentVisualElement.resolvedStyle.fontSize; m_Text.style.color = currentVisualElement.resolvedStyle.color; m_Text.style.unityTextAlign = currentVisualElement.resolvedStyle.unityTextAlign; m_Text.style.whiteSpace = currentVisualElement.resolvedStyle.whiteSpace; m_Text.style.textOverflow = currentVisualElement.resolvedStyle.textOverflow; m_Text.style.unityTextOutlineWidth = currentVisualElement.resolvedStyle.unityTextOutlineWidth; m_Text.style.unityTextOutlineColor = currentVisualElement.resolvedStyle.unityTextOutlineColor; m_Text.style.textShadow = currentVisualElement.computedStyle.textShadow; m_Text.style.letterSpacing = currentVisualElement.resolvedStyle.letterSpacing; m_Text.style.wordSpacing = currentVisualElement.resolvedStyle.wordSpacing; m_Text.style.unityParagraphSpacing = currentVisualElement.resolvedStyle.unityParagraphSpacing; } public void HierarchyChanged(VisualElement element, BuilderHierarchyChangeType changeType) { if (changeType.HasFlag(BuilderHierarchyChangeType.FullRefresh)) { RefreshPreview(); } } public void SelectionChanged() { RefreshPreview(); } public void StylingChanged(List<string> styles, BuilderStylingChangeType changeType) { RefreshPreview(); } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Inspector/BuilderInspectorPreview.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Inspector/BuilderInspectorPreview.cs", "repo_id": "UnityCsReference", "token_count": 2589 }
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.Collections.Generic; using UnityEditor; using UnityEngine.UIElements; namespace Unity.UI.Builder { class BuilderAnchorer : BuilderManipulator { static readonly string s_UssClassName = "unity-builder-anchorer"; static readonly string s_ActiveAnchorClassName = "unity-builder-anchorer--active"; Dictionary<string, VisualElement> m_HandleElements; [Serializable] public new class UxmlSerializedData : BuilderManipulator.UxmlSerializedData { public override object CreateInstance() => new BuilderAnchorer(); } public BuilderAnchorer() { var builderTemplate = BuilderPackageUtilities.LoadAssetAtPath<VisualTreeAsset>( BuilderConstants.UIBuilderPackagePath + "/Manipulators/BuilderAnchorer.uxml"); builderTemplate.CloneTree(this); AddToClassList(s_UssClassName); m_HandleElements = new Dictionary<string, VisualElement>(); m_HandleElements.Add("top-anchor", this.Q("top-anchor")); m_HandleElements.Add("left-anchor", this.Q("left-anchor")); m_HandleElements.Add("bottom-anchor", this.Q("bottom-anchor")); m_HandleElements.Add("right-anchor", this.Q("right-anchor")); m_HandleElements["top-anchor"].AddManipulator(new Clickable(OnAnchorClickTop)); m_HandleElements["left-anchor"].AddManipulator(new Clickable(OnAnchorClickLeft)); m_HandleElements["bottom-anchor"].AddManipulator(new Clickable(OnAnchorClickBottom)); m_HandleElements["right-anchor"].AddManipulator(new Clickable(OnAnchorClickRight)); m_AbsoluteOnlyHandleElements.Add(m_HandleElements["top-anchor"]); m_AbsoluteOnlyHandleElements.Add(m_HandleElements["left-anchor"]); m_AbsoluteOnlyHandleElements.Add(m_HandleElements["bottom-anchor"]); m_AbsoluteOnlyHandleElements.Add(m_HandleElements["right-anchor"]); } protected override void SetStylesFromTargetStyles() { base.SetStylesFromTargetStyles(); if (m_Target == null) return; // Set Anchor active states. m_HandleElements["top-anchor"].RemoveFromClassList(s_ActiveAnchorClassName); m_HandleElements["left-anchor"].RemoveFromClassList(s_ActiveAnchorClassName); m_HandleElements["bottom-anchor"].RemoveFromClassList(s_ActiveAnchorClassName); m_HandleElements["right-anchor"].RemoveFromClassList(s_ActiveAnchorClassName); if (!IsNoneOrAuto(TrackedStyles.Top)) m_HandleElements["top-anchor"].AddToClassList(s_ActiveAnchorClassName); if (!IsNoneOrAuto(TrackedStyles.Left)) m_HandleElements["left-anchor"].AddToClassList(s_ActiveAnchorClassName); if (!IsNoneOrAuto(TrackedStyles.Bottom)) m_HandleElements["bottom-anchor"].AddToClassList(s_ActiveAnchorClassName); if (!IsNoneOrAuto(TrackedStyles.Right)) m_HandleElements["right-anchor"].AddToClassList(s_ActiveAnchorClassName); } void SetAnchorHandleState(TrackedStyles style, bool state) { string anchorName = string.Empty; switch (style) { case TrackedStyles.Top: anchorName = "top-anchor"; break; case TrackedStyles.Left: anchorName = "left-anchor"; break; case TrackedStyles.Bottom: anchorName = "bottom-anchor"; break; case TrackedStyles.Right: anchorName = "right-anchor"; break; default: return; } if (state) m_HandleElements[anchorName].AddToClassList(s_ActiveAnchorClassName); else m_HandleElements[anchorName].RemoveFromClassList(s_ActiveAnchorClassName); } void OnAnchorClick(TrackedStyles primaryStyle, TrackedStyles oppositeStyle, TrackedStyles lengthStyle) { var primaryIsUnset = IsNoneOrAuto(primaryStyle); // We can enable primary. var oppositeIsSet = !IsNoneOrAuto(oppositeStyle); // We can safely unset primary. if (!primaryIsUnset && !oppositeIsSet) // Nothing to do. return; var parentLength = GetResolvedStyleFloat(lengthStyle, m_Target.parent); var parentBorderPrimary = GetBorderResolvedStyleFloat(primaryStyle, m_Target.parent); var parentBorderOpposite = GetBorderResolvedStyleFloat(oppositeStyle, m_Target.parent); var primary = GetStyleSheetFloat(primaryStyle); var opposite = GetStyleSheetFloat(oppositeStyle); var length = GetStyleSheetFloat(lengthStyle); var primaryName = GetStyleName(primaryStyle); var lengthName = GetStyleName(lengthStyle); var marginPrimary = GetMarginResolvedStyleFloat(primaryStyle); var marginOpposite = GetMarginResolvedStyleFloat(oppositeStyle); var totalAxisMargin = marginPrimary + marginOpposite; var changeList = new List<string>() { primaryName, lengthName }; if (primaryIsUnset) { var newPrimaryValue = parentLength - opposite - length - totalAxisMargin - parentBorderOpposite - parentBorderPrimary; SetStyleSheetValue(primaryStyle, newPrimaryValue); RemoveStyleSheetValue(lengthName); SetAnchorHandleState(primaryStyle, true); m_Selection.NotifyOfStylingChange(this, changeList); m_Selection.NotifyOfHierarchyChange(this, m_Target, BuilderHierarchyChangeType.InlineStyle | BuilderHierarchyChangeType.FullRefresh); } else if (oppositeIsSet) { var newLengthValue = parentLength - opposite - primary - totalAxisMargin - parentBorderOpposite - parentBorderPrimary; SetStyleSheetValue(lengthStyle, newLengthValue); RemoveStyleSheetValue(primaryName); SetAnchorHandleState(primaryStyle, false); m_Selection.NotifyOfStylingChange(this, changeList); m_Selection.NotifyOfHierarchyChange(this, m_Target, BuilderHierarchyChangeType.InlineStyle | BuilderHierarchyChangeType.FullRefresh); } } public void OnAnchorClickTop() { OnAnchorClick(TrackedStyles.Top, TrackedStyles.Bottom, TrackedStyles.Height); } public void OnAnchorClickRight() { OnAnchorClick(TrackedStyles.Right, TrackedStyles.Left, TrackedStyles.Width); } public void OnAnchorClickBottom() { OnAnchorClick(TrackedStyles.Bottom, TrackedStyles.Top, TrackedStyles.Height); } public void OnAnchorClickLeft() { OnAnchorClick(TrackedStyles.Left, TrackedStyles.Right, TrackedStyles.Width); } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Manipulators/BuilderAnchorer.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Manipulators/BuilderAnchorer.cs", "repo_id": "UnityCsReference", "token_count": 3113 }
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.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.UIElements; using UnityEditor; using UnityEditor.UIElements; using UnityEditor.UIElements.StyleSheets; using Toolbar = UnityEditor.UIElements.Toolbar; namespace Unity.UI.Builder { internal class BuilderToolbar : VisualElement, IBuilderAssetModificationProcessor, IBuilderSelectionNotifier { public const string FitViewportButtonName = "fit-viewport-button"; public const string PreviewToggleName = "preview-button"; public const string BreadcrumbsToolbarName = "breadcrumbs-toolbar"; public const string BreadcrumbsName = "breadcrumbs-view"; BuilderPaneWindow m_PaneWindow; BuilderSelection m_Selection; BuilderViewport m_Viewport; BuilderExplorer m_Explorer; BuilderLibrary m_Library; BuilderInspector m_Inspector; BuilderTooltipPreview m_TooltipPreview; ToolbarMenu m_FileMenu; ToolbarMenu m_ZoomMenu; ToolbarButton m_FitViewportButton; ToolbarMenu m_CanvasThemeMenu; ToolbarMenu m_SettingsMenu; Toolbar m_BreadcrumbsToolbar; ToolbarBreadcrumbs m_Breadcrumbs; ThemeStyleSheetManager m_ThemeManager; ThemeStyleSheet m_LastCustomTheme; string m_LastSavePath = "Assets/"; public BuilderDocument document { get { return m_PaneWindow.document; } } public BuilderToolbar( BuilderPaneWindow paneWindow, BuilderSelection selection, BuilderViewport viewport, BuilderExplorer explorer, BuilderLibrary library, BuilderInspector inspector, BuilderTooltipPreview tooltipPreview) { m_PaneWindow = paneWindow; m_Selection = selection; m_Viewport = viewport; m_Explorer = explorer; m_Library = library; m_Inspector = inspector; m_TooltipPreview = tooltipPreview; var template = BuilderPackageUtilities.LoadAssetAtPath<VisualTreeAsset>( BuilderConstants.UIBuilderPackagePath + "/BuilderToolbar.uxml"); template.CloneTree(this); m_ThemeManager = new ThemeStyleSheetManager(this); m_ThemeManager.selection = m_Selection; m_ThemeManager.themeFilesChanged += UpdateCanvasThemeMenuStatus; // File Menu m_FileMenu = this.Q<ToolbarMenu>("file-menu"); SetUpFileMenu(); // Zoom Menu m_ZoomMenu = this.Q<ToolbarMenu>("zoom-menu"); SetUpZoomMenu(); // Fit viewport m_FitViewportButton = this.Q<ToolbarButton>(FitViewportButtonName); m_FitViewportButton.clicked += () => m_Viewport.FitViewport(); // Preview Button var previewButton = this.Q<ToolbarToggle>(PreviewToggleName); previewButton.RegisterValueChangedCallback(TogglePreviewMode); m_Viewport.SetPreviewMode(false); m_CanvasThemeMenu = this.Q<ToolbarMenu>("canvas-theme-menu"); InitCanvasTheme(); SetViewportSubTitle(); // Track unsaved changes state change. UpdateHasUnsavedChanges(); m_SettingsMenu = this.Q<ToolbarMenu>("settings-menu"); SetupSettingsMenu(); // Breadcrumbs & BreadCrumbs Toolbar m_BreadcrumbsToolbar = this.Q<Toolbar>(BreadcrumbsToolbarName); m_Breadcrumbs = this.Q<ToolbarBreadcrumbs>(BreadcrumbsName); SetToolbarBreadCrumbs(); RegisterCallback<AttachToPanelEvent>(RegisterCallbacks); } public void InitCanvasTheme() { var projectDefaultTssAsset = m_ThemeManager.FindProjectDefaultRuntimeThemeAsset(); // If we find a Default Runtime Theme in the project, use that as the default theme // Otherwise we use the built-in Default Runtime Theme var defaultTssAsset = projectDefaultTssAsset == null ? m_ThemeManager.builtInDefaultRuntimeTheme : projectDefaultTssAsset; InitCanvasTheme(defaultTssAsset); } private void InitCanvasTheme(ThemeStyleSheet defaultTssAsset) { var currentTheme = document.currentCanvasTheme; var currentThemeSheet = document.currentCanvasThemeStyleSheet; // If canvas theme is editor-only without Editor Extensions mode enabled, treat this as a Runtime theme if (!document.fileSettings.editorExtensionMode && IsEditorCanvasTheme(currentTheme)) { currentTheme = BuilderDocument.CanvasTheme.Runtime; } else if (currentTheme == BuilderDocument.CanvasTheme.Custom && currentThemeSheet == null) { // Theme file was deleted, fallback to default theme currentTheme = BuilderDocument.CanvasTheme.Runtime; } else if (currentTheme == BuilderDocument.CanvasTheme.Custom && currentThemeSheet == m_ThemeManager.builtInDefaultRuntimeTheme && defaultTssAsset != m_ThemeManager.builtInDefaultRuntimeTheme) { // If a new Default Runtime Theme was added to the project, use that instead of the built-in one currentTheme = BuilderDocument.CanvasTheme.Runtime; } // If canvas theme is equal to the obsolete Runtime enum, search for the Unity default runtime theme // in the current project. If that can't be found, try one of the custom themes, otherwise // fallback to default Editor theme if (currentTheme == BuilderDocument.CanvasTheme.Runtime) { if (defaultTssAsset != null) { currentTheme = BuilderDocument.CanvasTheme.Custom; currentThemeSheet = defaultTssAsset; } else { // Fall back on first custom theme we find or default editor theme if (m_ThemeManager != null && m_ThemeManager.themeFiles.Count > 0) { var customThemeFile = m_ThemeManager.themeFiles[0]; currentTheme = BuilderDocument.CanvasTheme.Custom; currentThemeSheet = AssetDatabase.LoadAssetAtPath<ThemeStyleSheet>(customThemeFile); } else { currentTheme = BuilderDocument.CanvasTheme.Default; currentThemeSheet = null; } } } ChangeCanvasTheme(currentTheme, currentThemeSheet); UpdateCanvasThemeMenuStatus(); } void RegisterCallbacks(AttachToPanelEvent evt) { RegisterCallback<DetachFromPanelEvent>(UnregisterCallbacks); BuilderAssetModificationProcessor.Register(this); if (m_ThemeManager != null) BuilderAssetPostprocessor.Register(m_ThemeManager); } void UnregisterCallbacks(DetachFromPanelEvent evt) { UnregisterCallback<DetachFromPanelEvent>(UnregisterCallbacks); BuilderAssetModificationProcessor.Unregister(this); if (m_ThemeManager != null) BuilderAssetPostprocessor.Unregister(m_ThemeManager); } public void SetToolbarBreadCrumbs() { m_Breadcrumbs.Clear(); var allHierarchyDocuments = new List<BuilderDocumentOpenUXML>(); var allOpenDocuments = m_PaneWindow.document.openUXMLFiles; foreach (var Doc in allOpenDocuments) if (Doc.openSubDocumentParentIndex > -1 || allOpenDocuments.IndexOf(Doc) == 0) allHierarchyDocuments.Add(Doc); if (allHierarchyDocuments.Count == 1) { m_BreadcrumbsToolbar.style.display = DisplayStyle.None; return; } m_BreadcrumbsToolbar.style.display = DisplayStyle.Flex; foreach (var Doc in allHierarchyDocuments) { string docName = BreadcrumbFileName(Doc); Action onBreadCrumbClick = () => { document.GoToSubdocument(m_Viewport.documentRootElement, m_PaneWindow, Doc); m_Viewport.SetViewFromDocumentSetting(); }; bool clickedOnSameDocument = document.activeOpenUXMLFile == Doc; m_Breadcrumbs.PushItem(docName, clickedOnSameDocument ? null : onBreadCrumbClick); } } string BreadcrumbFileName(BuilderDocumentOpenUXML breadDoc) { var newFileName = breadDoc.uxmlFileName; if (string.IsNullOrEmpty(newFileName)) newFileName = BuilderConstants.ToolbarUnsavedFileDisplayMessage; else if (breadDoc.hasUnsavedChanges) newFileName = newFileName + BuilderConstants.ToolbarUnsavedFileSuffix; return newFileName; } public void OnAssetChange() { } public AssetDeleteResult OnWillDeleteAsset(string assetPath, RemoveAssetOptions option) { if (IsFileActionCompatible(assetPath, "delete")) return AssetDeleteResult.DidNotDelete; else return AssetDeleteResult.FailedDelete; } public AssetMoveResult OnWillMoveAsset(string sourcePath, string destinationPath) { // let Unity move it, we support that with the project:// URL syntax // note that if assets were not serialized with this Builder version, or authored manually with this new // URL syntax, then this will break references. return AssetMoveResult.DidNotMove; } internal static bool IsAssetUsedInDocument(BuilderDocument document, string assetPath) { // Check current document. var isAssetUsedInDocument = assetPath.Equals(document.uxmlPath) || document.ussPaths.Contains(assetPath); if (!isAssetUsedInDocument) { // Check uxml and uss paths in document dependencies. isAssetUsedInDocument = IsAssetUsedInDependencies(document.visualTreeAsset, assetPath); } return isAssetUsedInDocument; } static bool IsAssetUsedInDependencies(VisualTreeAsset visualTreeAsset, string assetPath) { foreach (var styleSheet in visualTreeAsset.GetAllReferencedStyleSheets()) { if (AssetDatabase.GetAssetPath(styleSheet) == assetPath) { return true; } } foreach (var vta in visualTreeAsset.templateDependencies) { var path = visualTreeAsset.GetPathFromTemplateName(vta.name); if (path == assetPath) { return true; } return IsAssetUsedInDependencies(vta, assetPath); } return false; } bool IsFileActionCompatible(string assetPath, string actionName) { if (IsAssetUsedInDocument(document, assetPath)) { var fileName = Path.GetFileName(assetPath); var acceptAction = BuilderDialogsUtility.DisplayDialog(BuilderConstants.ErrorDialogNotice, string.Format(BuilderConstants.ErrorIncompatibleFileActionMessage, actionName, fileName), string.Format(BuilderConstants.DialogDiscardOption, actionName.ToPascalCase()), string.Format(BuilderConstants.DialogAbortActionOption, actionName.ToPascalCase())); if (acceptAction) { // Open a new, empty document NewDocument(false); } return acceptAction; } return true; } string OpenLoadFileDialog(string title, string extension) { var loadPath = EditorUtility.OpenFilePanel( title, Path.GetDirectoryName(m_LastSavePath), extension); return loadPath; } public bool NewDocument(bool checkForUnsavedChanges = true, bool unloadAllSubdocuments = true) { if (checkForUnsavedChanges && !document.CheckForUnsavedChanges()) return false; if (unloadAllSubdocuments) document.GoToRootDocument(m_Viewport.documentRootElement, m_PaneWindow, true); m_Selection.ClearSelection(null); document.NewDocument(m_Viewport.documentRootElement); m_Viewport.ResetView(); m_Inspector?.canvasInspector.Refresh(); m_Selection.NotifyOfHierarchyChange(document); m_Selection.NotifyOfStylingChange(document); m_Library?.ResetCurrentlyLoadedUxmlStyles(); UpdateHasUnsavedChanges(); return true; } internal void SaveDocument(bool isSaveAs) { var viewportWindow = m_PaneWindow as IBuilderViewportWindow; if (viewportWindow == null) return; m_Explorer.elementHierarchyView.RegisterTreeState(); // Set asset. var userConfirmed = document.SaveNewDocument(viewportWindow.documentRootElement, isSaveAs, out var needFullRefresh); if (!userConfirmed) return; // Update any uses out there of the currently edited and saved USS. RetainedMode.FlagStyleSheetChange(); // Save last save path. m_LastSavePath = Path.GetDirectoryName(document.uxmlPath); // Set doc field value. UpdateHasUnsavedChanges(); // Only updating UI to remove "*" from file names. m_Selection.ResetUnsavedChanges(); if (needFullRefresh) m_PaneWindow.OnEnableAfterAllSerialization(); else m_Selection.NotifyOfHierarchyChange(document); } public void OnAfterBuilderDeserialize() { UpdateHasUnsavedChanges(); SetViewportSubTitle(); ChangeCanvasTheme(document.currentCanvasTheme, document.currentCanvasThemeStyleSheet); SetToolbarBreadCrumbs(); } public bool ReloadDocument() { return LoadDocument(document.visualTreeAsset, false); } public bool LoadDocument(VisualTreeAsset visualTreeAsset, string assetPath) { return LoadDocument(visualTreeAsset, true, false, assetPath); } public bool LoadDocument(VisualTreeAsset visualTreeAsset, bool unloadAllSubdocuments = true, bool assetModifiedExternally = false, string assetPath = null) { if (!BuilderAssetUtilities.ValidateAsset(visualTreeAsset, assetPath)) return false; if (!document.CheckForUnsavedChanges(assetModifiedExternally)) return false; if (unloadAllSubdocuments) document.GoToRootDocument(m_Viewport.documentRootElement, m_PaneWindow); LoadDocumentInternal(visualTreeAsset); return true; } void LoadDocumentInternal(VisualTreeAsset visualTreeAsset) { m_Selection.ClearSelection(null); document.LoadDocument(visualTreeAsset, m_Viewport.documentRootElement); m_Viewport.SetViewFromDocumentSetting(); m_Inspector?.canvasInspector.Refresh(); m_Selection.NotifyOfStylingChange(document); m_Selection.NotifyOfHierarchyChange(document); m_Library?.ResetCurrentlyLoadedUxmlStyles(); try { m_LastSavePath = Path.GetDirectoryName(document.uxmlPath); } catch { m_LastSavePath = "Assets"; } OnAfterBuilderDeserialize(); } void SetUpFileMenu() { m_FileMenu.menu.AppendAction("New", a => { NewDocument(); }); m_FileMenu.menu.AppendAction("Open...", a => { var path = OpenLoadFileDialog(BuilderConstants.ToolbarLoadUxmlDialogTitle, BuilderConstants.Uxml); if (string.IsNullOrEmpty(path)) return; if (BuilderAssetUtilities.IsPathInProject(path)) { path = BuilderAssetUtilities.GetPathRelativeToProject(path); } else { Debug.LogError(BuilderConstants.ToolbarCannotLoadUxmlOutsideProjectMessage); return; } var asset = BuilderPackageUtilities.LoadAssetAtPath<VisualTreeAsset>(path); LoadDocument(asset, false, false, path); }); m_FileMenu.menu.AppendSeparator(); m_FileMenu.menu.AppendAction("Save", a => { SaveDocument(false); }); m_FileMenu.menu.AppendAction("Save As...", a => { SaveDocument(true); }); } static string GetTextForZoomScale(float scale) { return $"{(int)(scale*100f)}%"; } void UpdateZoomMenuText() { m_ZoomMenu.text = GetTextForZoomScale(m_Viewport.zoomScale); } void SetUpZoomMenu() { foreach (var zoomScale in m_Viewport.zoomer.zoomMenuScaleValues) { m_ZoomMenu.menu.AppendAction(GetTextForZoomScale(zoomScale), a => { m_Viewport.zoomScale = zoomScale; }, a => Mathf.Approximately(m_Viewport.zoomScale, zoomScale) ? DropdownMenuAction.Status.Checked : DropdownMenuAction.Status.Normal); } m_Viewport.canvas.RegisterCallback<GeometryChangedEvent>(e => UpdateZoomMenuText()); UpdateZoomMenuText(); } internal static string GetEditorThemeText(BuilderDocument.CanvasTheme theme) { switch (theme) { case BuilderDocument.CanvasTheme.Default: return "Active Editor Theme"; case BuilderDocument.CanvasTheme.Dark: return "Dark Editor Theme"; case BuilderDocument.CanvasTheme.Light: return "Light Editor Theme"; default: break; } return null; } void SetUpCanvasThemeMenu() { m_CanvasThemeMenu.menu.ClearItems(); if (document.fileSettings.editorExtensionMode) { m_CanvasThemeMenu.menu.AppendAction(GetEditorThemeText(BuilderDocument.CanvasTheme.Default), a => { ChangeCanvasTheme(BuilderDocument.CanvasTheme.Default, null); UpdateCanvasThemeMenuStatus(); }, a => document.currentCanvasTheme == BuilderDocument.CanvasTheme.Default ? DropdownMenuAction.Status.Checked : DropdownMenuAction.Status.Normal); m_CanvasThemeMenu.menu.AppendAction(GetEditorThemeText(BuilderDocument.CanvasTheme.Dark), a => { ChangeCanvasTheme(BuilderDocument.CanvasTheme.Dark); UpdateCanvasThemeMenuStatus(); }, a => document.currentCanvasTheme == BuilderDocument.CanvasTheme.Dark ? DropdownMenuAction.Status.Checked : DropdownMenuAction.Status.Normal); m_CanvasThemeMenu.menu.AppendAction(GetEditorThemeText(BuilderDocument.CanvasTheme.Light), a => { ChangeCanvasTheme(BuilderDocument.CanvasTheme.Light); UpdateCanvasThemeMenuStatus(); }, a => document.currentCanvasTheme == BuilderDocument.CanvasTheme.Light ? DropdownMenuAction.Status.Checked : DropdownMenuAction.Status.Normal); } if (m_ThemeManager != null && m_ThemeManager.themeFiles.Count > 0) { m_CanvasThemeMenu.menu.AppendSeparator(); m_ThemeManager.themeFiles.Sort((a, b) => Path.GetFileName(a).CompareTo(Path.GetFileName(b))); foreach (var themeFile in m_ThemeManager.themeFiles) { var isBuiltInDefaultRuntimeTheme = themeFile == ThemeRegistry.k_DefaultStyleSheetPath; var themeName = isBuiltInDefaultRuntimeTheme ? BuilderConstants.ToolbarBuiltInDefaultRuntimeThemeName : ObjectNames.NicifyVariableName(Path.GetFileNameWithoutExtension(themeFile)); m_CanvasThemeMenu.menu.AppendAction(themeName, a => { var theme = isBuiltInDefaultRuntimeTheme ? m_ThemeManager.builtInDefaultRuntimeTheme : AssetDatabase.LoadAssetAtPath<ThemeStyleSheet>(themeFile); ChangeCanvasTheme(BuilderDocument.CanvasTheme.Custom, theme); UpdateCanvasThemeMenuStatus(); }, a => document.currentCanvasThemeStyleSheet != null && (AssetDatabase.GetAssetPath(document.currentCanvasThemeStyleSheet) == themeFile || isBuiltInDefaultRuntimeTheme && document.currentCanvasThemeStyleSheet == m_ThemeManager.builtInDefaultRuntimeTheme) ? DropdownMenuAction.Status.Checked : DropdownMenuAction.Status.Normal); } } } bool IsEditorCanvasTheme(BuilderDocument.CanvasTheme theme) { return theme is BuilderDocument.CanvasTheme.Default or BuilderDocument.CanvasTheme.Dark or BuilderDocument.CanvasTheme.Light; } public void ChangeCanvasTheme(BuilderDocument.CanvasTheme theme, ThemeStyleSheet customThemeStyleSheet = null) { m_Viewport.canvas.defaultBackgroundElement.style.display = theme == BuilderDocument.CanvasTheme.Custom ? DisplayStyle.None : DisplayStyle.Flex; m_Viewport.canvas.checkerboardBackgroundElement.style.display = theme == BuilderDocument.CanvasTheme.Custom ? DisplayStyle.Flex : DisplayStyle.None; StyleSheet activeThemeStyleSheet = null; switch (theme) { case BuilderDocument.CanvasTheme.Dark: activeThemeStyleSheet = UIElementsEditorUtility.GetCommonDarkStyleSheet(); break; case BuilderDocument.CanvasTheme.Light: activeThemeStyleSheet = UIElementsEditorUtility.GetCommonLightStyleSheet(); break; case BuilderDocument.CanvasTheme.Default: activeThemeStyleSheet = EditorGUIUtility.isProSkin ? UIElementsEditorUtility.GetCommonDarkStyleSheet() : UIElementsEditorUtility.GetCommonLightStyleSheet(); break; case BuilderDocument.CanvasTheme.Custom: activeThemeStyleSheet = customThemeStyleSheet; break; } ApplyCanvasTheme(m_Viewport.sharedStylesAndDocumentElement, activeThemeStyleSheet, m_LastCustomTheme); ApplyCanvasTheme(m_Viewport.documentRootElement, activeThemeStyleSheet, m_LastCustomTheme); ApplyCanvasBackground(m_Viewport.canvas.defaultBackgroundElement, theme); ApplyCanvasTheme(m_TooltipPreview, activeThemeStyleSheet, m_LastCustomTheme); ApplyCanvasBackground(m_TooltipPreview, theme); document.ChangeDocumentTheme(m_Viewport.documentRootElement, theme, customThemeStyleSheet); m_LastCustomTheme = customThemeStyleSheet; m_Inspector?.selection.NotifyOfStylingChange(null, null, BuilderStylingChangeType.RefreshOnly); } void ApplyCanvasTheme(VisualElement element, StyleSheet newThemeStyleSheet, StyleSheet oldCustomThemeStyleSheet) { if (element == null) return; // Remove any null stylesheet. This may occur if an used theme has been deleted. // This should be handle by ui toolkit var i = 0; if (element.styleSheetList != null) { while (i < element.styleSheetList.Count) { var sheet = element.styleSheetList[i]; if (sheet == null) { element.styleSheetList?.Remove(sheet); if (element.styleSheetList.Count == 0) { element.styleSheetList = null; break; } } else { i++; } } } // We verify whether the styles are loaded beforehand because calling GetCommonXXXStyleSheet() will load them unnecessarily in this case if (UIElementsEditorUtility.IsCommonDarkStyleSheetLoaded()) element.styleSheets.Remove(UIElementsEditorUtility.GetCommonDarkStyleSheet()); if (UIElementsEditorUtility.IsCommonLightStyleSheetLoaded()) element.styleSheets.Remove(UIElementsEditorUtility.GetCommonLightStyleSheet()); if (oldCustomThemeStyleSheet != null) element.styleSheets.Remove(oldCustomThemeStyleSheet); if (newThemeStyleSheet != null) element.styleSheets.Add(newThemeStyleSheet); element.SetProperty(BuilderConstants.ElementLinkedActiveThemeStyleSheetVEPropertyName, newThemeStyleSheet); } void ApplyCanvasBackground(VisualElement element, BuilderDocument.CanvasTheme theme) { if (element == null) return; element.RemoveFromClassList(BuilderConstants.CanvasContainerDarkStyleClassName); element.RemoveFromClassList(BuilderConstants.CanvasContainerLightStyleClassName); element.RemoveFromClassList(BuilderConstants.CanvasContainerRuntimeStyleClassName); switch (theme) { case BuilderDocument.CanvasTheme.Dark: element.AddToClassList(BuilderConstants.CanvasContainerDarkStyleClassName); break; case BuilderDocument.CanvasTheme.Light: element.AddToClassList(BuilderConstants.CanvasContainerLightStyleClassName); break; case BuilderDocument.CanvasTheme.Runtime: element.AddToClassList(BuilderConstants.CanvasContainerRuntimeStyleClassName); break; case BuilderDocument.CanvasTheme.Default: string defaultClass = EditorGUIUtility.isProSkin ? BuilderConstants.CanvasContainerDarkStyleClassName : BuilderConstants.CanvasContainerLightStyleClassName; element.AddToClassList(defaultClass); break; case BuilderDocument.CanvasTheme.Custom: element.AddToClassList(BuilderConstants.CanvasContainerRuntimeStyleClassName); break; } } void UpdateCanvasThemeMenuStatus() { SetUpCanvasThemeMenu(); if (m_CanvasThemeMenu.menu.MenuItems().Count == 0) { m_CanvasThemeMenu.tooltip = BuilderConstants.ToolbarCanvasThemeMenuEmptyTooltip; m_CanvasThemeMenu.text = GetEditorThemeText(BuilderDocument.CanvasTheme.Default); return; } m_CanvasThemeMenu.tooltip = document.fileSettings.editorExtensionMode ? BuilderConstants.ToolbarCanvasThemeMenuEditorTooltip : BuilderConstants.ToolbarCanvasThemeMenuTooltip; foreach (var item in m_CanvasThemeMenu.menu.MenuItems()) { var action = item as DropdownMenuAction; // Skip separators if (action == null) { continue; } action.UpdateActionStatus(null); var theme = document.currentCanvasTheme; if (action.status == DropdownMenuAction.Status.Checked) { if (theme == BuilderDocument.CanvasTheme.Custom) { if (document.currentCanvasThemeStyleSheet == m_ThemeManager.builtInDefaultRuntimeTheme) { m_CanvasThemeMenu.text = BuilderConstants.ToolbarBuiltInDefaultRuntimeThemeName; } else { var assetPath = AssetDatabase.GetAssetPath(document.currentCanvasThemeStyleSheet); var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(assetPath); var themeName = ObjectNames.NicifyVariableName(fileNameWithoutExtension); m_CanvasThemeMenu.text = themeName; } } else { m_CanvasThemeMenu.text = GetEditorThemeText(theme); } } } } void TogglePreviewMode(ChangeEvent<bool> evt) { m_Viewport.SetPreviewMode(evt.newValue); if (evt.newValue) m_Explorer?.ClearHighlightOverlay(); else m_Explorer?.ResetHighlightOverlays(); } void SetViewportSubTitle() { m_Viewport.subTitle = string.Empty; } void UpdateHasUnsavedChanges() { m_PaneWindow.SetHasUnsavedChanges(document.hasUnsavedChanges); SetCanvasTitle(); } void SetCanvasTitle() { var newFileName = document.uxmlFileName; bool hasUSSChanges = ((m_Selection.selectionType == BuilderSelectionType.StyleSheet) || (m_Selection.selectionType == BuilderSelectionType.StyleSelector) || (m_Selection.selectionType == BuilderSelectionType.ParentStyleSelector)); if (string.IsNullOrEmpty(newFileName)) newFileName = BuilderConstants.ToolbarUnsavedFileDisplayMessage; else if (document.hasUnsavedChanges && !hasUSSChanges) newFileName = newFileName + BuilderConstants.ToolbarUnsavedFileSuffix; m_Viewport.canvas.titleLabel.text = newFileName; m_Viewport.canvas.titleLabel.tooltip = document.uxmlPath; } void SetupSettingsMenu() { Builder builder = m_PaneWindow as Builder; if (builder == null) return; m_SettingsMenu.menu.AppendAction( "Show UXML \u2215 USS Previews", a => builder.codePreviewVisible = !builder.codePreviewVisible, a => builder.codePreviewVisible ? DropdownMenuAction.Status.Checked : DropdownMenuAction.Status.Normal); m_SettingsMenu.menu.AppendAction( "Reset Notifications", _ => BuilderProjectSettings.ResetNotifications(), _ => BuilderProjectSettings.HasBlockedNotifications() ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled); if (Unsupported.IsDeveloperMode()) { m_SettingsMenu.menu.AppendAction( "Always Use UxmlTraits Attribute fields", a => { BuilderUxmlAttributesView.alwaysUseUxmlTraits = !BuilderUxmlAttributesView.alwaysUseUxmlTraits; builder.inspector.RefreshUI(); }, a => BuilderUxmlAttributesView.alwaysUseUxmlTraits ? DropdownMenuAction.Status.Checked : DropdownMenuAction.Status.Normal); } m_SettingsMenu.menu.AppendAction("Settings" , a => ShowSettingsWindow() , a => DropdownMenuAction.Status.Normal); } void ShowSettingsWindow() { var projectSettingsWindow = EditorWindow.GetWindow<ProjectSettingsWindow>(); projectSettingsWindow.Show(); projectSettingsWindow.SelectProviderByName(UIToolkitSettingsProvider.name); } public void SelectionChanged() { } public void HierarchyChanged(VisualElement element, BuilderHierarchyChangeType changeType) { SetToolbarBreadCrumbs(); UpdateHasUnsavedChanges(); } public void StylingChanged(List<string> styles, BuilderStylingChangeType changeType) { SetToolbarBreadCrumbs(); UpdateHasUnsavedChanges(); } } class ThemeStyleSheetManager : IBuilderAssetPostprocessor { SearchFilter m_SearchFilter; BuilderToolbar m_ToolBar; List<string> m_ThemeFiles; internal ThemeStyleSheet builtInDefaultRuntimeTheme { get; } public List<string> themeFiles { get { if (m_ThemeFiles == null) { m_ThemeFiles = new List<string>(); RefreshThemeFiles(); } return m_ThemeFiles; } } BuilderDocument document => m_ToolBar.document; public BuilderSelection selection { get; set; } public event Action themeFilesChanged; public ThemeStyleSheetManager(BuilderToolbar toolbar) { m_ToolBar = toolbar; m_SearchFilter = new SearchFilter { searchArea = SearchFilter.SearchArea.AllAssets, classNames = new[] { nameof(ThemeStyleSheet) } }; builtInDefaultRuntimeTheme = EditorGUIUtility.Load(ThemeRegistry.k_DefaultStyleSheetPath) as ThemeStyleSheet; } internal ThemeStyleSheet FindProjectDefaultRuntimeThemeAsset() { if (themeFiles.Count <= 0) { return null; } foreach (var themeFilePath in themeFiles) { if (BuilderAssetUtilities.IsProjectDefaultRuntimeAsset(themeFilePath)) { return AssetDatabase.LoadAssetAtPath<ThemeStyleSheet>(themeFilePath); } } return null; } bool AddThemeFile(string theme) { if (themeFiles.Contains(theme)) return false; themeFiles.Add(theme); return true; } bool RemoveThemeFile(string theme) { if (!themeFiles.Contains(theme)) return false; themeFiles.Remove(theme); return true; } void NotifyThemesChanged() { themeFilesChanged?.Invoke(); } public void RefreshThemeFiles() { m_ThemeFiles?.Clear(); var assets = AssetDatabase.FindAllAssets(m_SearchFilter); foreach (var asset in assets) { var assetPath = AssetDatabase.GetAssetPath(asset.instanceID); AddThemeFile(assetPath); } // If we don't have a Default Runtime Theme in the project, we add the built-in one if (FindProjectDefaultRuntimeThemeAsset() == null) { AddThemeFile(ThemeRegistry.k_DefaultStyleSheetPath); } NotifyThemesChanged(); } public void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { bool listChanged = false; foreach (var movedAssetPath in movedFromAssetPaths) { if (!movedAssetPath.EndsWith(BuilderConstants.TssExtension)) continue; listChanged |= RemoveThemeFile(movedAssetPath); } foreach (var assetPath in importedAssets) { if (!assetPath.EndsWith(BuilderConstants.TssExtension)) continue; // If the current theme has changed then update the UI if (document.currentCanvasThemeStyleSheet && assetPath == AssetDatabase.GetAssetPath(document.currentCanvasThemeStyleSheet)) { selection.NotifyOfStylingChange(null, null, BuilderStylingChangeType.RefreshOnly); } listChanged |= AddThemeFile(assetPath); } var projectDefaultRuntimeAsset = FindProjectDefaultRuntimeThemeAsset(); foreach (var assetPath in deletedAssets) { if (!assetPath.EndsWith(BuilderConstants.TssExtension)) continue; // Check if the current theme has been removed then revert to the default one if (document.currentCanvasTheme == BuilderDocument.CanvasTheme.Custom && document.currentCanvasThemeStyleSheet == null) { if (document.fileSettings.editorExtensionMode) { m_ToolBar.ChangeCanvasTheme(BuilderDocument.CanvasTheme.Default, null); } else { m_ToolBar.ChangeCanvasTheme(BuilderDocument.CanvasTheme.Custom, projectDefaultRuntimeAsset != null ? projectDefaultRuntimeAsset : builtInDefaultRuntimeTheme); } } listChanged |= RemoveThemeFile(assetPath); } if (projectDefaultRuntimeAsset == null && !themeFiles.Contains(ThemeRegistry.k_DefaultStyleSheetPath)) { // Project Default Runtime Theme was deleted, so we add the built-in one listChanged |= AddThemeFile(ThemeRegistry.k_DefaultStyleSheetPath); } else if (projectDefaultRuntimeAsset != null && themeFiles.Contains(ThemeRegistry.k_DefaultStyleSheetPath)) { // Project Default Runtime Theme was added, so we remove the built-in one listChanged |= RemoveThemeFile(ThemeRegistry.k_DefaultStyleSheetPath); } if (listChanged) { NotifyThemesChanged(); } } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Toolbar/BuilderToolbar.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Toolbar/BuilderToolbar.cs", "repo_id": "UnityCsReference", "token_count": 18821 }
467
// 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 System; using UnityEngine; using UnityEngine.UIElements.StyleSheets; namespace Unity.UI.Builder { internal class BuilderStyleUtilities { // Private Utilities static void GetInlineStyleSheetAndRule(VisualTreeAsset vta, VisualElement element, out StyleSheet styleSheet, out StyleRule styleRule) { var vea = element.GetVisualElementAsset(); styleSheet = vta.GetOrCreateInlineStyleSheet(); styleRule = vta.GetOrCreateInlineStyleRule(vea); } static void GetInlineStyleSheetAndRule(VisualTreeAsset vta, VisualElementAsset vea, out StyleSheet styleSheet, out StyleRule styleRule) { styleSheet = vta.GetOrCreateInlineStyleSheet(); styleRule = vta.GetOrCreateInlineStyleRule(vea); } static StyleProperty GetOrCreateStylePropertyByStyleName(StyleSheet styleSheet, StyleRule styleRule, string styleName) { var styleProperty = styleSheet.FindLastProperty(styleRule, styleName); if (styleProperty == null) styleProperty = styleSheet.AddProperty(styleRule, styleName); return styleProperty; } // Inline StyleSheet Value Setters public static void SetInlineStyleValue(VisualTreeAsset vta, VisualElement element, string styleName, float value) { GetInlineStyleSheetAndRule(vta, element, out StyleSheet styleSheet, out StyleRule styleRule); SetStyleSheetRuleValueAsDimension(styleSheet, styleRule, styleName, value); element?.UpdateInlineRule(styleSheet, styleRule); } public static void SetInlineStyleValue(VisualTreeAsset vta, VisualElementAsset vea, VisualElement element, string styleName, float value) { GetInlineStyleSheetAndRule(vta, vea, out StyleSheet styleSheet, out StyleRule styleRule); SetStyleSheetRuleValue(styleSheet, styleRule, styleName, value); element?.UpdateInlineRule(styleSheet, styleRule); } public static void SetInlineStyleValue(VisualTreeAsset vta, VisualElement element, string styleName, Enum value) { GetInlineStyleSheetAndRule(vta, element, out StyleSheet styleSheet, out StyleRule styleRule); SetStyleSheetRuleValue(styleSheet, styleRule, styleName, value); element?.UpdateInlineRule(styleSheet, styleRule); } public static void SetInlineStyleValue(VisualTreeAsset vta, VisualElementAsset vea, VisualElement element, string styleName, Color value) { GetInlineStyleSheetAndRule(vta, vea, out StyleSheet styleSheet, out StyleRule styleRule); SetStyleSheetRuleValue(styleSheet, styleRule, styleName, value); element?.UpdateInlineRule(styleSheet, styleRule); } // StyleSheet Value Setters static void SetStyleSheetRuleValue(StyleSheet styleSheet, StyleRule styleRule, string styleName, float value) { var styleProperty = GetOrCreateStylePropertyByStyleName(styleSheet, styleRule, styleName); var isNewValue = styleProperty.values.Length == 0; if (isNewValue) styleSheet.AddValue(styleProperty, value); else // TODO: Assume only one value. styleSheet.SetValue(styleProperty.values[0], value); } static void SetStyleSheetRuleValueAsDimension(StyleSheet styleSheet, StyleRule styleRule, string styleName, float value) { var styleProperty = GetOrCreateStylePropertyByStyleName(styleSheet, styleRule, styleName); var isNewValue = styleProperty.values.Length == 0; // If the current style property is saved as a float instead of a dimension, // it means it's a user file where they left out the unit. We need to resave // it here as a dimension to create final proper uss. if (!isNewValue && styleProperty.values[0].valueType != StyleValueType.Dimension) { styleProperty.values = Array.Empty<StyleValueHandle>(); isNewValue = true; } var dimension = new Dimension(); dimension.unit = Dimension.Unit.Pixel; dimension.value = value; if (isNewValue) styleSheet.AddValue(styleProperty, dimension); else // TODO: Assume only one value. styleSheet.SetValue(styleProperty.values[0], dimension); } static void SetStyleSheetRuleValue(StyleSheet styleSheet, StyleRule styleRule, string styleName, Enum value) { var styleProperty = GetOrCreateStylePropertyByStyleName(styleSheet, styleRule, styleName); var isNewValue = styleProperty.values.Length == 0; if (!isNewValue && styleProperty.IsVariable()) { styleProperty.values = Array.Empty<StyleValueHandle>(); isNewValue = true; } if (isNewValue) styleSheet.AddValue(styleProperty, value); else // TODO: Assume only one value. styleSheet.SetValue(styleProperty.values[0], value); } static void SetStyleSheetRuleValue(StyleSheet styleSheet, StyleRule styleRule, string styleName, Color value) { var styleProperty = GetOrCreateStylePropertyByStyleName(styleSheet, styleRule, styleName); var isNewValue = styleProperty.values.Length == 0; if (!isNewValue && styleProperty.IsVariable()) { styleProperty.values = Array.Empty<StyleValueHandle>(); isNewValue = true; } if (isNewValue) styleSheet.AddValue(styleProperty, value); else // TODO: Assume only one value. styleSheet.SetValue(styleProperty.values[0], value); } public static string GenerateElementTargetedSelector(VisualElement documentElement) { string elementTargetedSelector; var classList = documentElement?.classList; // if element has name, use that to target it if (!string.IsNullOrEmpty(documentElement?.name)) { elementTargetedSelector = $"#{documentElement.name}"; } // if element has no name, use its class to target it else if (classList != null && classList.Count > 0) { elementTargetedSelector = $".{classList[^1]}"; } // if element has no class, use its type to target it else { elementTargetedSelector = documentElement?.typeName; } // add its parents name or class or type to the selector if (documentElement?.parent != null && !BuilderSharedStyles.IsDocumentElement(documentElement.parent)) { elementTargetedSelector = GenerateElementTargetedSelector(documentElement.parent) + " > " + elementTargetedSelector; } return elementTargetedSelector; } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Utilities/BuilderStyleUtilities.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Utilities/BuilderStyleUtilities.cs", "repo_id": "UnityCsReference", "token_count": 3070 }
468
// 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 UnityEngine; namespace Unity.UI.Builder { internal class BuilderPanner : PointerManipulator { private readonly BuilderViewport m_Viewport; private bool m_Panning; private int m_ActivatingButton; public BuilderPanner(BuilderViewport viewport) { m_Viewport = viewport; m_Viewport.Q("viewport").AddManipulator(this); activators.Add(new ManipulatorActivationFilter { button = MouseButton.MiddleMouse }); activators.Add(new ManipulatorActivationFilter { button = MouseButton.LeftMouse, modifiers = EventModifiers.Alt | EventModifiers.Control }); } protected override void RegisterCallbacksOnTarget() { target.RegisterCallback<PointerDownEvent>(OnPointerDown); target.RegisterCallback<PointerMoveEvent>(OnPointerMove); target.RegisterCallback<PointerUpEvent>(OnPointerUp); } protected override void UnregisterCallbacksFromTarget() { target.UnregisterCallback<PointerDownEvent>(OnPointerDown); target.UnregisterCallback<PointerMoveEvent>(OnPointerMove); target.UnregisterCallback<PointerUpEvent>(OnPointerUp); } void OnPointerDown(PointerDownEvent evt) { if (CanStartManipulation(evt)) { m_Panning = true; m_ActivatingButton = evt.button; target.CaptureMouse(); evt.StopImmediatePropagation(); } } void OnPointerUp(PointerUpEvent evt) { if (m_ActivatingButton != evt.button || !CanStopManipulation(evt)) return; m_Panning = false; target.ReleaseMouse(); evt.StopPropagation(); } void OnPointerMove(PointerMoveEvent evt) { if (!m_Panning) return; Vector2 deltaPosition = evt.deltaPosition; m_Viewport.contentOffset += deltaPosition; evt.StopPropagation(); } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Viewport/BuilderPanner.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Viewport/BuilderPanner.cs", "repo_id": "UnityCsReference", "token_count": 1023 }
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.Collections.Generic; using System.Linq; using UnityEditor.UIElements; using UnityEngine; using UnityEngine.UIElements; namespace Unity.UI.Builder { internal class FoldoutColorField : FoldoutField { static readonly string k_FieldClassName = BuilderConstants.FoldoutFieldPropertyName + "__color-field"; static readonly string k_MixedValueLineClassName = BuilderConstants.FoldoutFieldPropertyName + "__mixed-value-line"; [Serializable] public new class UxmlSerializedData : FoldoutField.UxmlSerializedData { public override object CreateInstance() => new FoldoutColorField(); } ColorField m_ColorField; VisualElement m_MixedValueLine; public List<Color> fieldValues = new List<Color>(); public bool isMixed { get { if (fieldValues.Count == 0) return true; var allSame = fieldValues.All(o => o == fieldValues[0]); return !allSame; } } public ColorField headerInputField { get { return m_ColorField; } } public FoldoutColorField() { m_ColorField = new ColorField(); m_ColorField.name = "field"; m_ColorField.AddToClassList(k_FieldClassName); m_ColorField.RegisterValueChangedCallback((e) => m_MixedValueLine.style.display = DisplayStyle.None); header.hierarchy.Add(m_ColorField); m_MixedValueLine = new VisualElement(); m_MixedValueLine.name = "mixed-value-line"; m_MixedValueLine.AddToClassList(k_MixedValueLineClassName); m_ColorField.Q(ColorField.internalColorFieldName).hierarchy.Add(m_MixedValueLine); } public override void UpdateFromChildFields() { var styleFields = this.contentContainer.Query<ColorField>().ToList(); for (int i = 0; i < styleFields.Count; ++i) { var styleField = styleFields[i]; UpdateFromChildField(bindingPathArray[i], styleField.value); } } public void UpdateFromChildField(string bindingPath, Color newValue) { while (fieldValues.Count != bindingPathArray.Length) fieldValues.Add(new Color()); var fieldIndex = Array.IndexOf(bindingPathArray, bindingPath); fieldValues[fieldIndex] = newValue; var value = GetCommonValueFromChildFields(); m_ColorField.SetValueWithoutNotify(value); if (isMixed) m_MixedValueLine.style.display = DisplayStyle.Flex; else m_MixedValueLine.style.display = DisplayStyle.None; } public Color GetCommonValueFromChildFields() { if (!isMixed) return fieldValues[0]; else return Color.white; } internal override void SetHeaderInputEnabled(bool enabled) { m_ColorField.SetEnabled(enabled); } } }
UnityCsReference/Modules/UIBuilder/Editor/Utilities/FoldoutField/FoldoutColorField.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/FoldoutField/FoldoutColorField.cs", "repo_id": "UnityCsReference", "token_count": 1529 }
470
// 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.UIElements; namespace Unity.UI.Builder { static class SelectorUtility { public static bool TryCreateSelector(string complexSelectorStr, out StyleComplexSelector selector) { // Remove extra whitespace. var selectorSplit = complexSelectorStr.Split(' '); complexSelectorStr = string.Join(" ", selectorSplit); // Create rule. var rule = new StyleRule { line = -1, properties = new StyleProperty[0] }; // Create selector. selector = new StyleComplexSelector { rule = rule }; var initResult = StyleComplexSelectorExtensions.InitializeSelector(selector, complexSelectorStr); return initResult; } public static bool CompareSelectors(StyleComplexSelector lhs, StyleComplexSelector rhs) { if (lhs.isSimple != rhs.isSimple || lhs.specificity != rhs.specificity || lhs.selectors.Length != rhs.selectors.Length) return false; for(var i = 0; i < lhs.selectors.Length; ++i) { var lSelector = lhs.selectors[i]; var rSelector = rhs.selectors[i]; if (lSelector.parts.Length != rSelector.parts.Length) return false; if (lSelector.previousRelationship != rSelector.previousRelationship) return false; for (var j = 0; j < lSelector.parts.Length; ++j) { if (!EqualityComparer<StyleSelectorPart>.Default.Equals(lSelector.parts[j], rSelector.parts[j])) return false; } } return true; } } }
UnityCsReference/Modules/UIBuilder/Editor/Utilities/Selector/SelectorUtility.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/Selector/SelectorUtility.cs", "repo_id": "UnityCsReference", "token_count": 1038 }
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 UnityEditor; using UnityEngine.UIElements; using UnityEngine.UIElements.StyleSheets; namespace Unity.UI.Builder { class PositionSection : VisualElement { [Serializable] public new class UxmlSerializedData : VisualElement.UxmlSerializedData { public override object CreateInstance() => new PositionSection(); } static readonly string k_FieldClassName = "unity-position-section"; static readonly string k_UxmlPath = BuilderConstants.UtilitiesPath + "/StyleField/PositionSection.uxml"; static readonly string k_UssPathNoExt = BuilderConstants.UtilitiesPath + "/StyleField/PositionSection"; internal static readonly string k_PositionAnchorsFieldName = "anchors"; PositionStyleField m_PositionTopField; PositionStyleField m_PositionBottomField; PositionStyleField m_PositionLeftField; PositionStyleField m_PositionRightField; PositionAnchors m_Anchors; public PositionSection() { AddToClassList(BuilderConstants.InspectorContainerClassName); AddToClassList(k_FieldClassName); styleSheets.Add(BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(k_UssPathNoExt + (EditorGUIUtility.isProSkin ? "Dark" : "Light") + ".uss")); styleSheets.Add(BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(k_UssPathNoExt + ".uss")); var template = BuilderPackageUtilities.LoadAssetAtPath<VisualTreeAsset>(k_UxmlPath); template.CloneTree(this); m_Anchors = this.Q<PositionAnchors>(k_PositionAnchorsFieldName); m_PositionTopField = this.Q<PositionStyleField>(StylePropertyId.Top.UssName()); m_PositionTopField.point = m_Anchors.topPoint; m_PositionBottomField = this.Q<PositionStyleField>(StylePropertyId.Bottom.UssName()); m_PositionBottomField.point = m_Anchors.bottomPoint; m_PositionLeftField = this.Q<PositionStyleField>(StylePropertyId.Left.UssName()); m_PositionLeftField.point = m_Anchors.leftPoint; m_PositionRightField = this.Q<PositionStyleField>(StylePropertyId.Right.UssName()); m_PositionRightField.point = m_Anchors.rightPoint; m_Anchors.topPoint.RegisterValueChangedCallback(e => OnPointClicked(e, m_PositionTopField)); m_Anchors.bottomPoint.RegisterValueChangedCallback(e => OnPointClicked(e, m_PositionBottomField)); m_Anchors.leftPoint.RegisterValueChangedCallback(e => OnPointClicked(e, m_PositionLeftField)); m_Anchors.rightPoint.RegisterValueChangedCallback(e => OnPointClicked(e, m_PositionRightField)); } void OnPointClicked(ChangeEvent<bool> evt, PositionStyleField styleField) { styleField.value = evt.newValue ? "0px" : StyleFieldConstants.KeywordAuto; } } }
UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/PositionSection.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/PositionSection.cs", "repo_id": "UnityCsReference", "token_count": 1180 }
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.Linq; using System.Text.RegularExpressions; using UnityEngine.UIElements; using UnityEditor; using UnityEngine; namespace Unity.UI.Builder { class VariableField : VisualElement, INotifyValueChanged<string> { static readonly string s_UssClassName = "unity-builder-variable-field"; static readonly string s_PrefixClassName = s_UssClassName + "--prefix"; static readonly string s_PlaceholderLabelClassName = s_UssClassName + "__placeholder-label"; TextField m_Field; Label m_PlaceholderLabel; string m_Value; public TextField textField => m_Field; public bool isReadOnly { get { return m_Field.isReadOnly; } set { m_Field.isReadOnly = value; } } public string value { get { return m_Value; } set { SetValue(value, true); } } public void SetValueWithoutNotify(string value) { SetValue(value, false); } void SetValue(string value, bool notify) { string cleanValue = StyleSheetUtilities.GetCleanVariableName(value); if (m_Value == cleanValue) return; var oldValue = m_Value; m_Value = cleanValue; if (panel != null && notify) { using (ChangeEvent<string> evt = ChangeEvent<string>.GetPooled(oldValue, cleanValue)) { evt.elementTarget = this; SendEvent(evt); } } m_Field.SetValueWithoutNotify(m_Value); UpdatePlaceholderLabelVisibility(); } public string placeholderText { get { return m_PlaceholderLabel.text; } set { if (placeholderText == value) return; m_PlaceholderLabel.text = value; UpdatePlaceholderLabelVisibility(); } } public VariableField() { m_Field = new TextField(); AddToClassList(s_UssClassName); m_PlaceholderLabel = new Label(); m_PlaceholderLabel.pickingMode = PickingMode.Ignore; m_PlaceholderLabel.AddToClassList(s_PlaceholderLabelClassName); m_PlaceholderLabel.pickingMode = PickingMode.Ignore; Add(m_Field); Add(m_PlaceholderLabel); m_Field.Q(TextField.textInputUssName).RegisterCallback<BlurEvent>(e => { value = m_Field?.value?.Trim(); }, TrickleDown.TrickleDown); m_Field.RegisterValueChangedCallback<string>(e => { UpdatePlaceholderLabelVisibility(); e.StopImmediatePropagation(); }); m_PlaceholderLabel.RegisterValueChangedCallback<string>(e => { e.StopImmediatePropagation(); }); } void UpdatePlaceholderLabelVisibility() { m_PlaceholderLabel.visible = string.IsNullOrEmpty(m_Field.value); } } }
UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/VariableField.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/VariableField.cs", "repo_id": "UnityCsReference", "token_count": 1676 }
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; namespace Unity.UI.Builder { [Flags] enum TransitionChangeType { None = 0, Property = 1 << 0, Duration = 1 << 1, TimingFunction = 1 << 2, Delay = 1 << 3, All = Property | Duration | TimingFunction | Delay } static class TransitionChangeTypeExtensions { public static bool HasAnyFlag(this TransitionChangeType value) { return (value & TransitionChangeType.All) != TransitionChangeType.None; } public static bool IsSet(this TransitionChangeType value, TransitionChangeType flag) { return (value & flag) == flag; } } }
UnityCsReference/Modules/UIBuilder/Editor/Utilities/Transitions/TransitionChangeType.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/Transitions/TransitionChangeType.cs", "repo_id": "UnityCsReference", "token_count": 329 }
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 System.Collections.Generic; using System.Text; using UnityEngine.Assertions; using UnityEngine.UIElements; using UnityEngine; using System.IO; using System.Linq; using UnityEditor.UIElements.StyleSheets; using UnityEngine.Pool; using Object = UnityEngine.Object; namespace Unity.UI.Builder { internal static class VisualTreeAssetToUXML { static readonly string k_ColumnFullName = typeof(Column).FullName; static void Indent(StringBuilder stringBuilder, int depth) { for (int i = 0; i < depth; ++i) stringBuilder.Append(" "); } static void AppendElementTypeName(VisualTreeAsset vta, UxmlAsset root, StringBuilder stringBuilder) { if (root is UxmlObjectAsset uxmlObjectAsset) { if (uxmlObjectAsset.isField) { stringBuilder.Append(uxmlObjectAsset.fullTypeName); return; } } var xmlNamespace = root.xmlNamespace; if (xmlNamespace != UxmlNamespaceDefinition.Empty) { var namespaceDefinition = vta.FindUxmlNamespaceDefinitionFromPrefix(root, xmlNamespace.prefix); if (namespaceDefinition != xmlNamespace) { xmlNamespace = vta.FindUxmlNamespaceDefinitionForTypeName(root, root.fullTypeName); } } if (string.IsNullOrEmpty(xmlNamespace.prefix)) { if (string.IsNullOrEmpty(xmlNamespace.resolvedNamespace)) { stringBuilder.Append(root.fullTypeName); } else { var name = root.fullTypeName.Substring(xmlNamespace.resolvedNamespace.Length + 1); stringBuilder.Append(name); } } else { stringBuilder.Append($"{xmlNamespace.prefix}:"); var name = root.fullTypeName.Substring(xmlNamespace.resolvedNamespace.Length + 1); stringBuilder.Append(name); } } static void AppendElementAttribute(string name, string value, StringBuilder stringBuilder) { if (string.IsNullOrEmpty(value)) return; if (name == "picking-mode" && value == "Position") return; // Clean up value and make it ready for XML. value = URIHelpers.EncodeUri(value); stringBuilder.Append(" "); stringBuilder.Append(name); stringBuilder.Append("=\""); stringBuilder.Append(value); stringBuilder.Append("\""); } static void AppendElementNonStyleAttributes(VisualElementAsset vea, StringBuilder stringBuilder, bool writingToFile) { AppendElementAttributes(vea, stringBuilder, writingToFile, "class", "style"); } static void AppendHeaderAttributes(VisualTreeAsset vta, StringBuilder stringBuilder, bool writingToFile) { AppendElementAttributes(vta.GetRootUxmlElement(), stringBuilder, writingToFile); } static void AppendNamespaceDefinition(UxmlNamespaceDefinition definition, StringBuilder stringBuilder) { AppendElementAttribute(string.IsNullOrEmpty(definition.prefix) ? "xmlns" : $"xmlns:{definition.prefix}", definition.resolvedNamespace, stringBuilder); } static void AppendElementAttributes(UxmlAsset uxmlAsset, StringBuilder stringBuilder, bool writingToFile, params string[] ignoredAttributes) { var namespaceDefinitions = uxmlAsset.namespaceDefinitions; if (namespaceDefinitions is {Count: > 0}) { for (var i = 0; i < namespaceDefinitions.Count; ++i) { AppendNamespaceDefinition(namespaceDefinitions[i], stringBuilder); } } var attributes = uxmlAsset.GetProperties(); if (attributes is {Count: > 0}) { for (var i = 0; i < attributes.Count; i += 2) { var name = attributes[i]; var value = attributes[i + 1]; // Avoid writing the selection attribute to UXML. if (writingToFile && name == BuilderConstants.SelectedVisualElementAssetAttributeName) continue; if (ignoredAttributes.Contains(name)) continue; AppendElementAttribute(name, value, stringBuilder); } } } static void AppendTemplateRegistrations( VisualTreeAsset vta, string vtaPath, StringBuilder stringBuilder, HashSet<string> templatesFilter = null) { var templateAliases = new List<string>(); if (vta.templateAssets != null && vta.templateAssets.Count > 0) { foreach (var templateAsset in vta.templateAssets) { if (!templateAliases.Contains(templateAsset.templateAlias)) templateAliases.Add(templateAsset.templateAlias); } } if (vta.uxmlObjectEntries != null && vta.uxmlObjectEntries.Count > 0) { foreach (var entry in vta.uxmlObjectEntries) { if (entry.uxmlObjectAssets == null) continue; foreach (var uxmlObjectAsset in entry.uxmlObjectAssets) { if (uxmlObjectAsset.fullTypeName != k_ColumnFullName) continue; var templateAlias = uxmlObjectAsset.GetAttributeValue(Column.k_HeaderTemplateAttributeName); if (!string.IsNullOrEmpty(templateAlias) && !templateAliases.Contains(templateAlias)) templateAliases.Add(templateAlias); templateAlias = uxmlObjectAsset.GetAttributeValue(Column.k_CellTemplateAttributeName); if (!string.IsNullOrEmpty(templateAlias) && !templateAliases.Contains(templateAlias)) templateAliases.Add(templateAlias); } } } var engineNamespaceDefinition = vta.FindUxmlNamespaceDefinitionForTypeName(vta.GetRootUxmlElement(), typeof(VisualElement).FullName); foreach (var templateAlias in templateAliases) { // Skip templates if not in filter. if (templatesFilter != null && !templatesFilter.Contains(templateAlias)) continue; Indent(stringBuilder, 1); stringBuilder.Append(BuilderConstants.UxmlOpenTagSymbol); if (engineNamespaceDefinition != UxmlNamespaceDefinition.Empty) { stringBuilder.Append(string.IsNullOrEmpty(engineNamespaceDefinition.prefix) ? BuilderConstants.UxmlTemplateClassTag : $"{engineNamespaceDefinition.prefix}:{BuilderConstants.UxmlTemplateClassTag}"); } else stringBuilder.Append($"{BuilderConstants.UxmlEngineNamespace}.{BuilderConstants.UxmlTemplateClassTag}"); AppendElementAttribute(BuilderConstants.UxmlNameAttr, templateAlias, stringBuilder); var fieldInfo = VisualTreeAssetExtensions.UsingsListFieldInfo; if (fieldInfo != null) { var usings = fieldInfo.GetValue(vta) as List<VisualTreeAsset.UsingEntry>; if (usings != null && usings.Count > 0) { var lookingFor = new VisualTreeAsset.UsingEntry(templateAlias, string.Empty); int index = usings.BinarySearch(lookingFor, VisualTreeAsset.UsingEntry.comparer); if (index >= 0) { var usingEntry = usings[index]; var path = GetProcessedPathForSrcAttribute(usingEntry.asset, vtaPath, usingEntry.path); AppendElementAttribute("src", path, stringBuilder); } } } else { Debug.LogError("UI Builder: VisualTreeAsset.m_Usings field has not been found! Update the reflection code!"); } stringBuilder.Append(BuilderConstants.UxmlEndTagSymbol); stringBuilder.Append(BuilderConstants.newlineCharFromEditorSettings); } } static void GatherUsedTemplates( VisualTreeAsset vta, VisualElementAsset root, Dictionary<int, List<VisualElementAsset>> idToChildren, HashSet<string> templates) { if (root is TemplateAsset) templates.Add((root as TemplateAsset).templateAlias); // Iterate through child elements. List<VisualElementAsset> children; if (idToChildren != null && idToChildren.TryGetValue(root.id, out children) && children.Count > 0) { foreach (VisualElementAsset childVea in children) GatherUsedTemplates(vta, childVea, idToChildren, templates); } } public static string GetProcessedPathForSrcAttribute(Object asset, string vtaPath, string assetPath) { if (asset) return URIHelpers.MakeAssetUri(asset); if (string.IsNullOrEmpty(assetPath)) return assetPath; var result = string.Empty; if (!string.IsNullOrEmpty(vtaPath)) { var vtaDir = Path.GetDirectoryName(vtaPath); vtaDir = vtaDir.Replace('\\', '/'); vtaDir += "/"; var assetPathDir = Path.GetDirectoryName(assetPath); assetPathDir = assetPathDir.Replace('\\', '/'); assetPathDir += "/"; if (assetPathDir.StartsWith(vtaDir)) result = assetPath.Substring(vtaDir.Length); // +1 for the / } if (string.IsNullOrEmpty(result)) result = "/" + assetPath; return result; } static void ProcessStyleSheetPath( string vtaPath, StyleSheet styleSheet, string styleSheetPath, StringBuilder stringBuilder, int depth, ref bool newLineAdded, ref bool hasChildTags) { if (!newLineAdded) { stringBuilder.Append(BuilderConstants.UxmlCloseTagSymbol); stringBuilder.Append(BuilderConstants.newlineCharFromEditorSettings); newLineAdded = true; } Indent(stringBuilder, depth + 1); stringBuilder.Append("<Style"); { styleSheetPath = GetProcessedPathForSrcAttribute(styleSheet, vtaPath, styleSheetPath); AppendElementAttribute("src", styleSheetPath, stringBuilder); } stringBuilder.Append(BuilderConstants.UxmlEndTagSymbol); stringBuilder.Append(BuilderConstants.newlineCharFromEditorSettings); hasChildTags = true; } static void GenerateUXMLRecursive( VisualTreeAsset vta, string vtaPath, UxmlAsset root, Dictionary<int, List<VisualElementAsset>> idToChildren, StringBuilder stringBuilder, int depth, bool writingToFile) { Indent(stringBuilder, depth); stringBuilder.Append(BuilderConstants.UxmlOpenTagSymbol); AppendElementTypeName(vta, root, stringBuilder); // If we have no children, avoid adding the full end tag and just end the open tag. bool hasChildTags = false; if (root is VisualElementAsset vea) { // Add all non-style attributes. AppendElementNonStyleAttributes(vea, stringBuilder, writingToFile); // Add style classes to class attribute. if (vea.classes != null && vea.classes.Length > 0) { stringBuilder.Append(" class=\""); for (int i = 0; i < vea.classes.Length; i++) { if (i > 0) stringBuilder.Append(" "); stringBuilder.Append(vea.classes[i]); } stringBuilder.Append("\""); } // Add inline StyleSheet attribute. if (vea.ruleIndex != -1) { if (vta.inlineSheet == null) Debug.LogWarning("VisualElementAsset has a RuleIndex but no inlineStyleSheet"); else { StyleRule r = vta.inlineSheet.rules[vea.ruleIndex]; if (r.properties != null && r.properties.Length > 0) { var ruleBuilder = new StringBuilder(); var exportOptions = new UssExportOptions(); exportOptions.propertyIndent = string.Empty; StyleSheetToUss.ToUssString(vta.inlineSheet, exportOptions, r, ruleBuilder); var ruleStr = ruleBuilder.ToString(); // Need to remove newlines here before we give it to // AppendElementAttribute() so we don't add "&#10;" everywhere. ruleStr = ruleStr.Replace("\n", " "); ruleStr = ruleStr.Replace("\r", ""); ruleStr = ruleStr.Trim(); AppendElementAttribute("style", ruleStr, stringBuilder); } } } // Add special children. var styleSheets = vea.GetStyleSheets(); var styleSheetPaths = vea.GetStyleSheetPaths(); if (styleSheetPaths != null && styleSheetPaths.Count > 0) { Assert.IsNotNull(styleSheets); Assert.AreEqual(styleSheetPaths.Count, styleSheets.Count); bool newLineAdded = false; for (var i = 0; i < styleSheetPaths.Count; ++i) { var styleSheet = styleSheets[i]; var styleSheetPath = styleSheetPaths[i]; ProcessStyleSheetPath( vtaPath, styleSheet, styleSheetPath, stringBuilder, depth, ref newLineAdded, ref hasChildTags); } } } else { AppendElementAttributes(root, stringBuilder, writingToFile); } var templateAsset = root as TemplateAsset; if (templateAsset != null && templateAsset.attributeOverrides.Count > 0) { if (!hasChildTags) { stringBuilder.Append(BuilderConstants.UxmlCloseTagSymbol); stringBuilder.Append(BuilderConstants.newlineCharFromEditorSettings); } var overridesMap = new Dictionary<string, List<TemplateAsset.AttributeOverride>>(); foreach (var attributeOverride in templateAsset.attributeOverrides) { if (!overridesMap.ContainsKey(attributeOverride.m_ElementName)) overridesMap.Add(attributeOverride.m_ElementName, new List<TemplateAsset.AttributeOverride>()); overridesMap[attributeOverride.m_ElementName].Add(attributeOverride); } foreach (var attributeOverridePair in overridesMap) { var elementName = attributeOverridePair.Key; var overrides = attributeOverridePair.Value; Indent(stringBuilder, depth + 1); stringBuilder.Append(BuilderConstants.UxmlOpenTagSymbol + "AttributeOverrides"); AppendElementAttribute("element-name", elementName, stringBuilder); foreach (var attributeOverride in overrides) AppendElementAttribute(attributeOverride.m_AttributeName, attributeOverride.m_Value, stringBuilder); stringBuilder.Append(BuilderConstants.UxmlEndTagSymbol); stringBuilder.Append(BuilderConstants.newlineCharFromEditorSettings); } hasChildTags = true; } // Iterate through child elements. List<VisualElementAsset> children; if (idToChildren != null && idToChildren.TryGetValue(root.id, out children) && children.Count > 0) { if (!hasChildTags) { stringBuilder.Append(BuilderConstants.UxmlCloseTagSymbol); stringBuilder.Append(BuilderConstants.newlineCharFromEditorSettings); } children.Sort(VisualTreeAssetUtilities.CompareForOrder); foreach (var childVea in children) GenerateUXMLRecursive( vta, vtaPath, childVea, idToChildren, stringBuilder, depth + 1, writingToFile); hasChildTags = true; } // Iterate through Uxml Objects var entry = vta.GetUxmlObjectEntry(root.id); if (entry.uxmlObjectAssets != null && entry.uxmlObjectAssets.Count > 0) { if (!hasChildTags) { stringBuilder.Append(BuilderConstants.UxmlCloseTagSymbol); stringBuilder.Append(BuilderConstants.newlineCharFromEditorSettings); } foreach (var childAsset in entry.uxmlObjectAssets) { GenerateUXMLRecursive( vta, vtaPath, childAsset, idToChildren, stringBuilder, depth + 1, writingToFile); } hasChildTags = true; } if (hasChildTags) { Indent(stringBuilder, depth); stringBuilder.Append(BuilderConstants.UxmlOpenTagSymbol + "/"); AppendElementTypeName(vta, root, stringBuilder); stringBuilder.Append(BuilderConstants.UxmlCloseTagSymbol); stringBuilder.Append(BuilderConstants.newlineCharFromEditorSettings); } else { stringBuilder.Append(BuilderConstants.UxmlEndTagSymbol); stringBuilder.Append(BuilderConstants.newlineCharFromEditorSettings); } } public static string GenerateUXML(VisualTreeAsset vta, string vtaPath, List<VisualElementAsset> veas) { var stringBuilder = new StringBuilder(); var rootElement = vta.GetRootUxmlElement(); var engineNamespaceDefinition = vta.FindUxmlNamespaceDefinitionForTypeName(rootElement, typeof(VisualElement).FullName); if (engineNamespaceDefinition != UxmlNamespaceDefinition.Empty) { stringBuilder.Append(string.IsNullOrEmpty(engineNamespaceDefinition.prefix) ? "<UXML" : $"<{engineNamespaceDefinition.prefix}:UXML"); } else stringBuilder.Append("<UXML"); AppendHeaderAttributes(vta, stringBuilder, false); using var setHandle = HashSetPool<UxmlNamespaceDefinition>.Get(out var definitionsSet); { for (var i = 0; i < rootElement.namespaceDefinitions.Count; ++i) { definitionsSet.Add(rootElement.namespaceDefinitions[i]); } foreach (var vea in veas) { using var listHandle = ListPool<UxmlNamespaceDefinition>.Get(out var definitions); vta.GatherUxmlNamespaceDefinitions(vea, definitions); for (var i = 0; i < definitions.Count; ++i) { var definition = definitions[i]; if (definitionsSet.Add(definition)) { AppendNamespaceDefinition(definition, stringBuilder); } } } } stringBuilder.Append(BuilderConstants.UxmlCloseTagSymbol); stringBuilder.Append(BuilderConstants.newlineCharFromEditorSettings); var idToChildren = VisualTreeAssetUtilities.GenerateIdToChildren(vta); var usedTemplates = new HashSet<string>(); foreach (var vea in veas) { // Templates GatherUsedTemplates(vta, vea, idToChildren, usedTemplates); } AppendTemplateRegistrations(vta, vtaPath, stringBuilder, usedTemplates); foreach (var vea in veas) { GenerateUXMLRecursive(vta, vtaPath, vea, idToChildren, stringBuilder, 1, true); } if (engineNamespaceDefinition != UxmlNamespaceDefinition.Empty) { stringBuilder.Append(string.IsNullOrEmpty(engineNamespaceDefinition.prefix) ? "</UXML>" : $"</{engineNamespaceDefinition.prefix}:UXML>"); } else stringBuilder.Append("</UXML>"); stringBuilder.Append(BuilderConstants.newlineCharFromEditorSettings); return stringBuilder.ToString(); } static void GenerateUXMLFromRootElements( VisualTreeAsset vta, Dictionary<int, List<VisualElementAsset>> idToChildren, StringBuilder stringBuilder, string vtaPath, bool writingToFile) { List<VisualElementAsset> rootAssets; // Tree root has parentId == 0 idToChildren.TryGetValue(0, out rootAssets); if (rootAssets == null || rootAssets.Count == 0) return; var uxmlRootAsset = rootAssets[0]; bool tempHasChildTags = false; var styleSheets = uxmlRootAsset.GetStyleSheets(); var styleSheetPaths = uxmlRootAsset.GetStyleSheetPaths(); if (styleSheetPaths != null && styleSheetPaths.Count > 0) { Assert.IsNotNull(styleSheets); Assert.AreEqual(styleSheetPaths.Count, styleSheets.Count); bool newLineAdded = true; for (var i = 0; i < styleSheetPaths.Count; ++i) { var styleSheet = styleSheets[i]; var styleSheetPath = styleSheetPaths[i]; ProcessStyleSheetPath( vtaPath, styleSheet, styleSheetPath, stringBuilder, 0, ref newLineAdded, ref tempHasChildTags); } } // Get the first-level elements. These will be instantiated and added to target. idToChildren.TryGetValue(uxmlRootAsset.id, out rootAssets); if (rootAssets == null || rootAssets.Count == 0) return; rootAssets.Sort(VisualTreeAssetUtilities.CompareForOrder); foreach (VisualElementAsset rootElement in rootAssets) { Assert.IsNotNull(rootElement); // Don't try to include the special selection tracking element. if (writingToFile && rootElement.fullTypeName == BuilderConstants.SelectedVisualTreeAssetSpecialElementTypeName) continue; GenerateUXMLRecursive(vta, vtaPath, rootElement, idToChildren, stringBuilder, 1, writingToFile); } } public static string GenerateUXML(VisualTreeAsset vta, string vtaPath, bool writingToFile = false) { var stringBuilder = new StringBuilder(); if (vta.visualElementAssets is not {Count: > 0} && vta.templateAssets is not {Count: > 0}) { stringBuilder.Append($"{BuilderConstants.UxmlOpenTagSymbol}{BuilderConstants.UxmlDefaultEngineNamespacePrefix}:{BuilderConstants.UxmlEngineNamespace}{BuilderConstants.UxmlCloseTagSymbol}"); stringBuilder.Append(BuilderConstants.newlineCharFromEditorSettings); stringBuilder.Append($"{BuilderConstants.UxmlOpenTagSymbol}/{BuilderConstants.UxmlDefaultEngineNamespacePrefix}:{BuilderConstants.UxmlEngineNamespace}{BuilderConstants.UxmlCloseTagSymbol}"); stringBuilder.Append(BuilderConstants.newlineCharFromEditorSettings); return stringBuilder.ToString(); } var idToChildren = VisualTreeAssetUtilities.GenerateIdToChildren(vta); stringBuilder.Append(BuilderConstants.UxmlOpenTagSymbol); AppendElementTypeName(vta, vta.GetRootUxmlElement(), stringBuilder); AppendHeaderAttributes(vta, stringBuilder, writingToFile); stringBuilder.Append(BuilderConstants.UxmlCloseTagSymbol); stringBuilder.Append(BuilderConstants.newlineCharFromEditorSettings); // Templates AppendTemplateRegistrations(vta, vtaPath, stringBuilder); GenerateUXMLFromRootElements(vta, idToChildren, stringBuilder, vtaPath, writingToFile); stringBuilder.Append(BuilderConstants.UxmlOpenTagSymbol); stringBuilder.Append("/"); AppendElementTypeName(vta, vta.GetRootUxmlElement(), stringBuilder); stringBuilder.Append(BuilderConstants.UxmlCloseTagSymbol); stringBuilder.Append(BuilderConstants.newlineCharFromEditorSettings); return stringBuilder.ToString(); } } }
UnityCsReference/Modules/UIBuilder/Editor/Utilities/VisualTreeAssetExtensions/VisualTreeAssetToUXML.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/VisualTreeAssetExtensions/VisualTreeAssetToUXML.cs", "repo_id": "UnityCsReference", "token_count": 13162 }
475
// 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; namespace UnityEngine.UIElements { /// <summary> /// Context object containing the necessary information to resolve a binding. /// </summary> public readonly struct BindingContext { private readonly VisualElement m_TargetElement; private readonly BindingId m_BindingId; private readonly PropertyPath m_DataSourcePath; private readonly object m_DataSource; /// <summary> /// The target element of the binding. /// </summary> public VisualElement targetElement => m_TargetElement; /// <summary> /// The binding ID of the element to bind. /// </summary> public BindingId bindingId => m_BindingId; /// <summary> /// The resolved path to the value in the source, including relative data source paths found in the hierarchy /// between the target and to the resolved source owner. /// </summary> public PropertyPath dataSourcePath => m_DataSourcePath; /// <summary> /// The data source that was resolved for a given binding. /// </summary> /// <remarks> /// If a <see cref="Binding"/> implements the <see cref="IDataSourceProvider"/> interface and provides its own data source, it will automatically be used as the /// resolved data source; otherwise the data source will be resolved to the first valid data source on the target /// element or its ancestors. This value can be <see langword="null"/>. /// </remarks> public object dataSource => m_DataSource; internal BindingContext( VisualElement targetElement, in BindingId bindingId, in PropertyPath resolvedDataSourcePath, object resolvedDataSource) { m_TargetElement = targetElement; m_BindingId = bindingId; m_DataSourcePath = resolvedDataSourcePath; m_DataSource = resolvedDataSource; } } }
UnityCsReference/Modules/UIElements/Core/Bindings/BindingContext.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Bindings/BindingContext.cs", "repo_id": "UnityCsReference", "token_count": 780 }
476
// Unity C# 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.Internal { class AutoCompletePathVisitor : ITypeVisitor, IPropertyVisitor, IPropertyBagVisitor, IListPropertyVisitor { class VisitContext { public List<PropertyPathInfo> propertyPathInfos { get; set; } public HashSet<Type> types { get; } = new(); public PropertyPath current { get; set; } public int currentDepth { get; set; } } VisitContext m_VisitContext = new(); public List<PropertyPathInfo> propertyPathList { set => m_VisitContext.propertyPathInfos = value; } public int maxDepth { get; set; } bool HasReachedEnd(Type containerType) => m_VisitContext.currentDepth >= maxDepth || m_VisitContext.types.Contains(containerType); public void Reset() { m_VisitContext.current = new PropertyPath(); m_VisitContext.propertyPathInfos = null; m_VisitContext.types.Clear(); m_VisitContext.currentDepth = 0; } /// <inheritdoc/> void ITypeVisitor.Visit<TContainer>() { if (HasReachedEnd(typeof(TContainer))) return; using var scope = new InspectedTypeScope<TContainer>(m_VisitContext); var bag = PropertyBag.GetPropertyBag<TContainer>(); if (bag == null) return; foreach (var property in bag.GetProperties()) { using var propertyScope = new VisitedPropertyScope(m_VisitContext, property); VisitPropertyType(property.DeclaredValueType()); } } /// <inheritdoc/> void IPropertyBagVisitor.Visit<TContainer>(IPropertyBag<TContainer> properties, ref TContainer container) { if (HasReachedEnd(typeof(TContainer))) return; using var scope = new InspectedTypeScope<TContainer>(m_VisitContext); switch (properties) { case IIndexedProperties<TContainer> indexedProperties: if (indexedProperties.TryGetProperty(ref container, 0, out var indexProperty)) { using var propertyScope = new VisitedPropertyScope(m_VisitContext, 0, indexProperty.DeclaredValueType()); indexProperty.Accept(this, ref container); } else { // Fallback to type visitation in this branch. VisitPropertyType(typeof(TContainer)); } break; case IKeyedProperties<TContainer, object>: // Dictionaries are unsupported. break; default: { foreach (var property in properties.GetProperties(ref container)) { using var propertyScope = new VisitedPropertyScope(m_VisitContext, property); property.Accept(this, ref container); } break; } } } /// <inheritdoc/> void IPropertyVisitor.Visit<TContainer, TValue>(Property<TContainer, TValue> property, ref TContainer container) { if (!TypeTraits.IsContainer(typeof(TValue))) return; var value = property.GetValue(ref container); var isValueNull = TypeTraits<TValue>.CanBeNull && EqualityComparer<TValue>.Default.Equals(value, default); if (!isValueNull && PropertyBag.TryGetPropertyBagForValue(ref value, out var valuePropertyBag)) { switch (valuePropertyBag) { case IListPropertyAccept<TValue> accept: accept.Accept(this, property, ref container, ref value); break; default: PropertyContainer.TryAccept(this, ref value); break; } } else { // Fallback to type visitation in this branch. VisitPropertyType(property.DeclaredValueType()); } } void IListPropertyVisitor.Visit<TContainer, TList, TElement>(Property<TContainer, TList> property, ref TContainer container, ref TList list) { PropertyContainer.TryAccept(this, ref list); } void VisitPropertyType(Type type) { if (HasReachedEnd(type)) return; if (type.IsArray) { if (type.GetArrayRank() != 1) return; var elementType = type.GetElementType(); var untypedBag = PropertyBag.GetPropertyBag(elementType); using var propertyScope = new VisitedPropertyScope(m_VisitContext, 0, elementType); untypedBag?.Accept(this); } else if (type.IsGenericType) { if (type.GetGenericTypeDefinition().IsAssignableFrom(typeof(List<>)) || type.GetGenericTypeDefinition().IsAssignableFrom(typeof(IList<>))) { var elementType = type.GenericTypeArguments[0]; var untypedBag = PropertyBag.GetPropertyBag(elementType); using var propertyScope = new VisitedPropertyScope(m_VisitContext, 0, elementType); untypedBag?.Accept(this); } } else { var bag = PropertyBag.GetPropertyBag(type); bag?.Accept(this); } } struct InspectedTypeScope<TContainer> : IDisposable { VisitContext m_VisitContext; public InspectedTypeScope(VisitContext context) { m_VisitContext = context; m_VisitContext.types.Add(typeof(TContainer)); } public void Dispose() { m_VisitContext.types.Remove(typeof(TContainer)); } } struct VisitedPropertyScope : IDisposable { VisitContext m_VisitContext; public VisitedPropertyScope(VisitContext context, IProperty property) { m_VisitContext = context; m_VisitContext.current = PropertyPath.AppendProperty(m_VisitContext.current, property); var propertyPathInfo = new PropertyPathInfo(m_VisitContext.current, property.DeclaredValueType()); m_VisitContext.propertyPathInfos?.Add(propertyPathInfo); m_VisitContext.currentDepth++; } public VisitedPropertyScope(VisitContext context, int index, Type type) { m_VisitContext = context; m_VisitContext.current = PropertyPath.AppendIndex(m_VisitContext.current, index); var propertyPathInfo = new PropertyPathInfo(m_VisitContext.current, type); m_VisitContext.propertyPathInfos?.Add(propertyPathInfo); m_VisitContext.currentDepth++; } public void Dispose() { m_VisitContext.current = PropertyPath.Pop(m_VisitContext.current); m_VisitContext.currentDepth--; } } } }
UnityCsReference/Modules/UIElements/Core/Bindings/Utils/AutoCompletePathVisitor.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Bindings/Utils/AutoCompletePathVisitor.cs", "repo_id": "UnityCsReference", "token_count": 3820 }
477
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections; using System.Collections.Generic; using UnityEngine.UIElements.Internal; namespace UnityEngine.UIElements { /// <summary> /// Multi-column tree view controller. View controllers of this type are meant to take care of data virtualized by any <see cref="MultiColumnTreeView"/> inheritor. /// </summary> public abstract class MultiColumnTreeViewController : BaseTreeViewController { MultiColumnController m_ColumnController; /// <summary> /// The column controller, taking care of operations on the header. /// </summary> public MultiColumnController columnController => m_ColumnController; internal MultiColumnCollectionHeader header => m_ColumnController?.header; /// <summary> /// The constructor for MultiColumnTreeViewController. /// </summary> /// <param name="columns">The columns data used to initialize the header.</param> /// <param name="sortDescriptions">The sort data used to initialize the header.</param> /// <param name="sortedColumns">The sorted columns for the view.</param> protected MultiColumnTreeViewController(Columns columns, SortColumnDescriptions sortDescriptions, List<SortColumnDescription> sortedColumns) { m_ColumnController = new MultiColumnController(columns, sortDescriptions, sortedColumns); } internal override void PreRefresh() { base.PreRefresh(); m_ColumnController.SortIfNeeded(); } internal override void InvokeMakeItem(ReusableCollectionItem reusableItem) { if (reusableItem is ReusableMultiColumnTreeViewItem treeItem) { treeItem.Init(MakeItem(), m_ColumnController.header.columns); PostInitRegistration(treeItem); } else { base.InvokeMakeItem(reusableItem); } } internal override void InvokeBindItem(ReusableCollectionItem reusableItem, int index) { var sortedIndex = m_ColumnController.GetSortedIndex(index); base.InvokeBindItem(reusableItem, sortedIndex); } internal override void InvokeUnbindItem(ReusableCollectionItem reusableItem, int index) { var sortedIndex = m_ColumnController.GetSortedIndex(index); base.InvokeUnbindItem(reusableItem, sortedIndex); } /// <inheritdoc /> protected override VisualElement MakeItem() { return m_ColumnController.MakeItem(); } /// <inheritdoc /> protected override void BindItem(VisualElement element, int index) { m_ColumnController.BindItem(element, index, GetItemForIndex(index)); } /// <inheritdoc /> protected override void UnbindItem(VisualElement element, int index) { m_ColumnController.UnbindItem(element, index); } /// <inheritdoc /> protected override void DestroyItem(VisualElement element) { m_ColumnController.DestroyItem(element); } /// <inheritdoc /> protected override void PrepareView() { m_ColumnController.PrepareView(view); } /// <summary> /// Unregisters events and removes the header from the hierarchy. /// </summary> public override void Dispose() { m_ColumnController.Dispose(); m_ColumnController = null; base.Dispose(); } } }
UnityCsReference/Modules/UIElements/Core/Collections/Controllers/MultiColumnTreeViewController.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Collections/Controllers/MultiColumnTreeViewController.cs", "repo_id": "UnityCsReference", "token_count": 1493 }
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 System.Collections.Generic; using UnityEngine.Internal; using UnityEngine.Scripting.APIUpdating; namespace UnityEngine.UIElements { /// <summary> /// This is the base class for the composite fields. /// </summary> [MovedFrom(true, UpgradeConstants.EditorNamespace, UpgradeConstants.EditorAssembly)] public abstract class BaseCompositeField<TValueType, TField, TFieldValue> : BaseField<TValueType> where TField : TextValueField<TFieldValue>, new() { internal struct FieldDescription { public delegate void WriteDelegate(ref TValueType val, TFieldValue fieldValue); internal readonly string name; internal readonly string ussName; internal readonly Func<TValueType, TFieldValue> read; internal readonly WriteDelegate write; public FieldDescription(string name, string ussName, Func<TValueType, TFieldValue> read, WriteDelegate write) { this.name = name; this.ussName = ussName; this.read = read; this.write = write; } } [ExcludeFromDocs, Serializable] public new abstract class UxmlSerializedData : BaseField<TValueType>.UxmlSerializedData { } private VisualElement GetSpacer() { var spacer = new VisualElement(); spacer.AddToClassList(spacerUssClassName); spacer.visible = false; spacer.focusable = false; return spacer; } List<TField> m_Fields; internal List<TField> fields => m_Fields; internal abstract FieldDescription[] DescribeFields(); bool m_ShouldUpdateDisplay; bool m_ForceUpdateDisplay; /// <summary> /// USS class name of elements of this type. /// </summary> public new static readonly string ussClassName = "unity-composite-field"; /// <summary> /// USS class name of labels in elements of this type. /// </summary> public new static readonly string labelUssClassName = ussClassName + "__label"; /// <summary> /// USS class name of input elements in elements of this type. /// </summary> public new static readonly string inputUssClassName = ussClassName + "__input"; /// <summary> /// USS class name of spacers in elements of this type. /// </summary> public static readonly string spacerUssClassName = ussClassName + "__field-spacer"; /// <summary> /// USS class name of elements of this type when the fields are displayed on multiple lines. /// </summary> public static readonly string multilineVariantUssClassName = ussClassName + "--multi-line"; /// <summary> /// USS class name of field groups in elements of this type. /// </summary> public static readonly string fieldGroupUssClassName = ussClassName + "__field-group"; /// <summary> /// USS class name of fields in elements of this type. /// </summary> public static readonly string fieldUssClassName = ussClassName + "__field"; /// <summary> /// USS class name of the first field in elements of this type. /// </summary> public static readonly string firstFieldVariantUssClassName = fieldUssClassName + "--first"; /// <summary> /// USS class name of elements of this type when the fields are displayed on two lines. /// </summary> public static readonly string twoLinesVariantUssClassName = ussClassName + "--two-lines"; protected BaseCompositeField(string label, int fieldsByLine) : base(label, null) { delegatesFocus = false; visualInput.focusable = false; AddToClassList(ussClassName); labelElement.AddToClassList(labelUssClassName); visualInput.AddToClassList(inputUssClassName); m_ShouldUpdateDisplay = true; m_Fields = new List<TField>(); FieldDescription[] fieldDescriptions = DescribeFields(); int numberOfLines = 1; if (fieldsByLine > 1) { numberOfLines = fieldDescriptions.Length / fieldsByLine; } var isMultiLine = false; if (numberOfLines > 1) { isMultiLine = true; AddToClassList(multilineVariantUssClassName); } for (int i = 0; i < numberOfLines; i++) { VisualElement newLineGroup = null; if (isMultiLine) { newLineGroup = new VisualElement(); newLineGroup.AddToClassList(fieldGroupUssClassName); } bool firstField = true; for (int j = i * fieldsByLine; j < ((i * fieldsByLine) + fieldsByLine); j++) { var desc = fieldDescriptions[j]; var field = new TField() { name = desc.ussName }; field.delegatesFocus = true; field.AddToClassList(fieldUssClassName); if (firstField) { field.AddToClassList(firstFieldVariantUssClassName); firstField = false; } field.label = desc.name; field.onValidateValue += newValue => { TValueType cur = value; desc.write(ref cur, newValue); var validatedValue = ValidatedValue(cur); return desc.read(validatedValue); }; field.RegisterValueChangedCallback(e => { TValueType cur = value; desc.write(ref cur, e.newValue); // Here, just check and make sure the text is updated in the basic field and is the same as the value... // For example, backspace done on a selected value will empty the field (text == "") but the value will be 0. // Or : a text of "2+3" is valid until enter is pressed, so not equal to a value of "5". var valueString = e.newValue.ToString(); var textString = ((TField)e.currentTarget).text; // If text is different or value changed because of an explicit value set if (valueString != textString || field.CanTryParse(textString)) { m_ShouldUpdateDisplay = false; } value = cur; m_ShouldUpdateDisplay = true; }); m_Fields.Add(field); if (isMultiLine) { newLineGroup.Add(field); } else { visualInput.hierarchy.Add(field); } } if (fieldsByLine < 3) { int fieldsToAdd = 3 - fieldsByLine; for (int countToAdd = 0; countToAdd < fieldsToAdd; countToAdd++) { if (isMultiLine) { newLineGroup.Add(GetSpacer()); } else { visualInput.hierarchy.Add(GetSpacer()); } } } if (isMultiLine) { visualInput.hierarchy.Add(newLineGroup); } } UpdateDisplay(); } private void UpdateDisplay() { if (m_Fields.Count != 0) { var i = 0; FieldDescription[] fieldDescriptions = DescribeFields(); foreach (var fd in fieldDescriptions) { m_Fields[i].SetValueWithoutNotify(fd.read(rawValue)); i++; } } } public override void SetValueWithoutNotify(TValueType newValue) { var displayNeedsUpdate = m_ForceUpdateDisplay || (m_ShouldUpdateDisplay && !EqualityComparer<TValueType>.Default.Equals(rawValue, newValue)); // Make sure to call the base class to set the value... base.SetValueWithoutNotify(newValue); // Before Updating the display, just check if the value changed... if (displayNeedsUpdate) { UpdateDisplay(); } m_ForceUpdateDisplay = false; } internal override void OnViewDataReady() { // Should the composite field be reloaded, ensure that the value saved in memory is actually displayed when a data key is used. m_ForceUpdateDisplay = true; base.OnViewDataReady(); } protected override void UpdateMixedValueContent() { foreach (var field in m_Fields) { field.showMixedValue = showMixedValue; } } } }
UnityCsReference/Modules/UIElements/Core/Controls/BaseCompositeField.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Controls/BaseCompositeField.cs", "repo_id": "UnityCsReference", "token_count": 4870 }
479
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Globalization; using UnityEngine.Scripting.APIUpdating; namespace UnityEngine.UIElements { /// <summary> /// Makes a text field for entering a float. For more information, refer to [[wiki:UIE-uxml-element-FloatField|UXML element FloatField]]. /// </summary> [MovedFrom(true, UpgradeConstants.EditorNamespace, UpgradeConstants.EditorAssembly)] public class FloatField : TextValueField<float> { // This property to alleviate the fact we have to cast all the time FloatInput floatInput => (FloatInput)textInputBase; [UnityEngine.Internal.ExcludeFromDocs, Serializable] public new class UxmlSerializedData : TextValueField<float>.UxmlSerializedData { public override object CreateInstance() => new FloatField(); } /// <summary> /// Instantiates a <see cref="FloatField"/> 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<FloatField, UxmlTraits> {} /// <summary> /// Defines <see cref="UxmlTraits"/> for the <see cref="FloatField"/>. /// </summary> [Obsolete("UxmlTraits is deprecated and will be removed. Use UxmlElementAttribute instead.", false)] public new class UxmlTraits : TextValueFieldTraits<float, UxmlFloatAttributeDescription> {} /// <summary> /// Converts the given float to a string. /// </summary> /// <param name="v">The float to be converted to string.</param> /// <returns>The float as string.</returns> protected override string ValueToString(float v) { return v.ToString(formatString, CultureInfo.InvariantCulture.NumberFormat); } /// <summary> /// Converts a string to a float. /// </summary> /// <param name="str">The string to convert.</param> /// <returns>The float parsed from the string.</returns> protected override float StringToValue(string str) { var success = UINumericFieldsUtils.TryConvertStringToFloat(str, textInputBase.originalText, out var v); return success ? v : rawValue; } /// <summary> /// USS class name of elements of this type. /// </summary> public new static readonly string ussClassName = "unity-float-field"; /// <summary> /// USS class name of labels in elements of this type. /// </summary> public new static readonly string labelUssClassName = ussClassName + "__label"; /// <summary> /// USS class name of input elements in elements of this type. /// </summary> public new static readonly string inputUssClassName = ussClassName + "__input"; /// <summary> /// Constructor. /// </summary> public FloatField() : this((string)null) {} /// <summary> /// Constructor. /// </summary> /// <param name="maxLength">Maximum number of characters the field can take.</param> public FloatField(int maxLength) : this(null, maxLength) {} /// <summary> /// Constructor. /// </summary> /// <param name="maxLength">Maximum number of characters the field can take.</param> public FloatField(string label, int maxLength = kMaxValueFieldLength) : base(label, maxLength, new FloatInput()) { AddToClassList(ussClassName); labelElement.AddToClassList(labelUssClassName); visualInput.AddToClassList(inputUssClassName); AddLabelDragger<float>(); } internal override bool CanTryParse(string textString) => float.TryParse(textString, out _); /// <summary> /// Applies the values of a 3D delta and a speed from an input device. /// </summary> /// <param name="delta">A vector used to compute the value change.</param> /// <param name="speed">A multiplier for the value change.</param> /// <param name="startValue">The start value.</param> public override void ApplyInputDeviceDelta(Vector3 delta, DeltaSpeed speed, float startValue) { floatInput.ApplyInputDeviceDelta(delta, speed, startValue); } class FloatInput : TextValueInput { FloatField parentFloatField => (FloatField)parent; internal FloatInput() { formatString = UINumericFieldsUtils.k_FloatFieldFormatString; } protected override string allowedCharacters => UINumericFieldsUtils.k_AllowedCharactersForFloat; public override void ApplyInputDeviceDelta(Vector3 delta, DeltaSpeed speed, float startValue) { double sensitivity = NumericFieldDraggerUtility.CalculateFloatDragSensitivity(startValue); float acceleration = NumericFieldDraggerUtility.Acceleration(speed == DeltaSpeed.Fast, speed == DeltaSpeed.Slow); double v = StringToValue(text); v += NumericFieldDraggerUtility.NiceDelta(delta, acceleration) * sensitivity; v = Mathf.RoundBasedOnMinimumDifference(v, sensitivity); if (parentFloatField.isDelayed) { text = ValueToString(Mathf.ClampToFloat(v)); } else { parentFloatField.value = Mathf.ClampToFloat(v); } } protected override string ValueToString(float v) { return v.ToString(formatString); } protected override float StringToValue(string str) { UINumericFieldsUtils.TryConvertStringToFloat(str, originalText, out var v); return v; } } } }
UnityCsReference/Modules/UIElements/Core/Controls/FloatField.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Controls/FloatField.cs", "repo_id": "UnityCsReference", "token_count": 2489 }
480
// 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 { /// <summary> /// Provides an Element displaying text. For more information, refer to [[wiki:UIE-uxml-element-label|UXML element Label]]. /// </summary> public class Label : TextElement { [UnityEngine.Internal.ExcludeFromDocs, Serializable] public new class UxmlSerializedData : TextElement.UxmlSerializedData { public override object CreateInstance() => new Label(); } /// <summary> /// Instantiates a <see cref="Label"/> 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<Label, UxmlTraits> {} /// <summary> /// Defines <see cref="UxmlTraits"/> for the <see cref="Label"/>. /// </summary> [Obsolete("UxmlTraits is deprecated and will be removed. Use UxmlElementAttribute instead.", false)] public new class UxmlTraits : TextElement.UxmlTraits {} /// <summary> /// USS class name of elements of this type. /// </summary> public new static readonly string ussClassName = "unity-label"; /// <summary> /// Constructs a label. /// </summary> public Label() : this(String.Empty) {} /// <summary> /// Constructs a label. /// </summary> /// <param name="text">The text to be displayed.</param> public Label(string text) { AddToClassList(ussClassName); this.text = text; } } }
UnityCsReference/Modules/UIElements/Core/Controls/Label.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Controls/Label.cs", "repo_id": "UnityCsReference", "token_count": 702 }
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; using System.Collections.Generic; using UnityEngine.Internal; namespace UnityEngine.UIElements { /// <summary> /// This represents a collection or SortColumnDescriptions in multi SortColumnDescription views. /// </summary> [UxmlObject] public class SortColumnDescriptions : ICollection<SortColumnDescription> { [ExcludeFromDocs, Serializable] public class UxmlSerializedData : UIElements.UxmlSerializedData { #pragma warning disable 649 [SerializeReference, UxmlObjectReference] List<SortColumnDescription.UxmlSerializedData> sortColumnDescriptions; [SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags sortColumnDescriptions_UxmlAttributeFlags; #pragma warning restore 649 public override object CreateInstance() => new SortColumnDescriptions(); public override void Deserialize(object obj) { if (ShouldWriteAttributeValue(sortColumnDescriptions_UxmlAttributeFlags) && sortColumnDescriptions != null) { var e = (SortColumnDescriptions)obj; foreach (var scdData in sortColumnDescriptions) { var scd = (SortColumnDescription)scdData.CreateInstance(); scdData.Deserialize(scd); e.Add(scd); } } } } /// <summary> /// Instantiates a <see cref="SortColumnDescriptions"/> using the data read from a UXML file. /// </summary> [Obsolete("UxmlObjectFactory<T> is deprecated and will be removed. Use UxmlElementAttribute instead.", false)] internal class UxmlObjectFactory<T> : UxmlObjectFactory<T, UxmlObjectTraits<T>> where T : SortColumnDescriptions, new() {} /// <summary> /// Instantiates a <see cref="SortColumnDescriptions"/> using the data read from a UXML file. /// </summary> [Obsolete("UxmlObjectFactory is deprecated and will be removed. Use UxmlElementAttribute instead.", false)] internal class UxmlObjectFactory : UxmlObjectFactory<SortColumnDescriptions> {} /// <summary> /// Defines <see cref="UxmlObjectTraits{T}"/> for the <see cref="SortColumnDescriptions"/>. /// </summary> [Obsolete("UxmlObjectTraits<T> is deprecated and will be removed. Use UxmlElementAttribute instead.", false)] internal class UxmlObjectTraits<T> : UnityEngine.UIElements.UxmlObjectTraits<T> where T : SortColumnDescriptions { readonly UxmlObjectListAttributeDescription<SortColumnDescription> m_SortColumnDescriptions = new UxmlObjectListAttributeDescription<SortColumnDescription>(); public override void Init(ref T obj, IUxmlAttributes bag, CreationContext cc) { base.Init(ref obj, bag, cc); var sortColumnDescriptions = m_SortColumnDescriptions.GetValueFromBag(bag, cc); if (sortColumnDescriptions != null) { foreach (var d in sortColumnDescriptions) { obj.Add(d); } } } } [SerializeField] private readonly IList<SortColumnDescription> m_Descriptions = new List<SortColumnDescription>(); private IList<SortColumnDescription> sortColumnDescriptions => m_Descriptions; /// <summary> /// Event sent when the descriptions changed. /// </summary> internal event Action changed; /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>The enumerator.</returns> public IEnumerator<SortColumnDescription> GetEnumerator() { return m_Descriptions.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns>The enumerator.</returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Adds a sort description at the end of the collection. /// </summary> /// <param name="item">The sort description to add.</param> public void Add(SortColumnDescription item) { Insert(m_Descriptions.Count, item); } /// <summary> /// Removes all sort descriptions from the collection. /// </summary> public void Clear() { while (m_Descriptions.Count > 0) { Remove(m_Descriptions[0]); } } /// <summary> /// Determines whether the current collection contains a specific value. /// </summary> /// <param name="item">The object to locate in the current collection.</param> /// <returns>Whether the item is in the collection or not.</returns> public bool Contains(SortColumnDescription item) { return m_Descriptions.Contains(item); } /// <summary> /// Copies the elements of the current collection to a Array, starting at the specified index. /// </summary> /// <param name="array">The array to copy to.</param> /// <param name="arrayIndex">The starting index.</param> public void CopyTo(SortColumnDescription[] array, int arrayIndex) { m_Descriptions.CopyTo(array, arrayIndex); } /// <summary> /// Removes the first occurence of a sort description from the collection. /// </summary> /// <param name="desc">The sort description to remove.</param> /// <returns>Whether it was removed or not.</returns> public bool Remove(SortColumnDescription desc) { if (desc == null) throw new ArgumentException("Cannot remove null description"); if (m_Descriptions.Remove(desc)) { desc.column = null; desc.changed -= OnDescriptionChanged; changed?.Invoke(); return true; } return false; } void OnDescriptionChanged(SortColumnDescription desc) { changed?.Invoke(); } /// <summary> /// Gets the number of sort descriptions in the collection. /// </summary> public int Count => m_Descriptions.Count; /// <summary> /// Gets a value indicating whether the collection is readonly. /// </summary> public bool IsReadOnly => m_Descriptions.IsReadOnly; /// <summary> /// Returns the index of the specified <see cref="SortColumnDescription"/> if it is contained in the collection; returns -1 otherwise. /// </summary> /// <param name="desc">The description to locate in the <see cref="SortColumnDescriptions"/>.</param> /// <returns>The index of the <see cref="SortColumnDescriptions"/> if found in the collection; otherwise, -1.</returns> public int IndexOf(SortColumnDescription desc) { return m_Descriptions.IndexOf(desc); } /// <summary> /// Inserts a sort description into the current instance at the specified index. /// </summary> /// <param name="index">Index to insert to.</param> /// <param name="desc">The sort description to insert.</param> public void Insert(int index, SortColumnDescription desc) { if (desc == null) throw new ArgumentException("Cannot insert null description"); if (Contains(desc)) throw new ArgumentException("Already contains this description"); m_Descriptions.Insert(index, desc); desc.changed += OnDescriptionChanged; changed?.Invoke(); } /// <summary> /// Removes the sort description at the specified index. /// </summary> /// <param name="index">The index of the sort description to remove.</param> public void RemoveAt(int index) { Remove(m_Descriptions[index]); } /// <summary> /// Returns the SortColumnDescription at the specified index. /// </summary> /// <param name="index">The index of the SortColumnDescription to locate.</param> /// <returns>The SortColumnDescription at the specified index.</returns> public SortColumnDescription this[int index] { get { return m_Descriptions[index]; } } } }
UnityCsReference/Modules/UIElements/Core/Controls/MultiColumn/SortColumnDescriptions.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Controls/MultiColumn/SortColumnDescriptions.cs", "repo_id": "UnityCsReference", "token_count": 3700 }
482
// Unity C# 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 control that allows single or multiple selection out of a logical group of <see cref="Button"/> elements. /// </summary> /// <remarks> /// The ToggleButtonGroup has a label and a group of interactable <see cref="Button"/> elements. /// /// To create buttons, add <see cref="Button"/> elements directly to the ToggleButtonGroup. This will automatically /// style and configure the button to work properly. /// </remarks> public class ToggleButtonGroup : BaseField<ToggleButtonGroupState> { private static readonly string k_MaxToggleButtonGroupMessage = $"The number of buttons added to ToggleButtonGroup exceeds the maximum allowed ({ToggleButtonGroupState.maxLength}). The newly added button will not be treated as part of this control."; internal static readonly BindingId isMultipleSelectionProperty = nameof(isMultipleSelection); internal static readonly BindingId allowEmptySelectionProperty = nameof(allowEmptySelection); [UnityEngine.Internal.ExcludeFromDocs, Serializable] public new class UxmlSerializedData : BaseField<ToggleButtonGroupState>.UxmlSerializedData { #pragma warning disable 649 [SerializeField] bool isMultipleSelection; [SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags isMultipleSelection_UxmlAttributeFlags; [SerializeField] bool allowEmptySelection; [SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags allowEmptySelection_UxmlAttributeFlags; #pragma warning restore 649 public override object CreateInstance() => new ToggleButtonGroup(); public override void Deserialize(object obj) { base.Deserialize(obj); var e = (ToggleButtonGroup)obj; if (ShouldWriteAttributeValue(isMultipleSelection_UxmlAttributeFlags)) e.isMultipleSelection = isMultipleSelection; if (ShouldWriteAttributeValue(allowEmptySelection_UxmlAttributeFlags)) e.allowEmptySelection = allowEmptySelection; } } /// <summary> /// Instantiates a <see cref="ToggleButtonGroup"/>. /// </summary> /// <remarks> /// This class is added to every <see cref="VisualElement"/> that is created from UXML. /// </remarks> [Obsolete("UxmlFactory is deprecated and will be removed. Use UxmlElementAttribute instead.", false)] public new class UxmlFactory : UxmlFactory<ToggleButtonGroup, UxmlTraits> {} /// <summary> /// Defines <see cref="UxmlTraits"/> for the <see cref="ToggleButtonGroup"/>. /// </summary> /// <remarks> /// This class defines the properties of a ToggleButtonGroup element that you can use in a UXML asset. /// </remarks> [Obsolete("UxmlTraits is deprecated and will be removed. Use UxmlElementAttribute instead.", false)] public new class UxmlTraits : BaseField<ToggleButtonGroupState>.UxmlTraits { private UxmlBoolAttributeDescription m_IsMultipleSelection = new() { name = "is-multiple-selection" }; private UxmlBoolAttributeDescription m_AllowEmptySelection = new() { name = "allow-empty-selection" }; public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) { base.Init(ve, bag, cc); var toggleButtonGroup = (ToggleButtonGroup)ve; toggleButtonGroup.isMultipleSelection = m_IsMultipleSelection.GetValueFromBag(bag, cc); toggleButtonGroup.allowEmptySelection = m_AllowEmptySelection.GetValueFromBag(bag, cc); } } /// <summary> /// USS class name of elements for this type. /// </summary> public new static readonly string ussClassName = "unity-toggle-button-group"; // TO-DO : Fix this - it's only being used as a name /// <summary> /// USS class name of container element of this type. /// </summary> public static readonly string containerUssClassName = ussClassName + "__container"; /// <summary> /// USS class name of container element of this type. /// </summary> public static readonly string buttonGroupClassName = "unity-button-group"; /// <summary> /// USS class name for any Buttons in the group. /// </summary> public static readonly string buttonClassName = buttonGroupClassName + "__button"; /// <summary> /// USS class name for the leftmost Button in the group. /// </summary> public static readonly string buttonLeftClassName = buttonClassName + "--left"; /// <summary> /// USS class name for any Buttons in the middle of the group. /// </summary> public static readonly string buttonMidClassName = buttonClassName + "--mid"; /// <summary> /// USS class name for the rightmost Button in the group. /// </summary> public static readonly string buttonRightClassName = buttonClassName + "--right"; /// <summary> /// USS class name for the Button if only one is available in the group. /// </summary> public static readonly string buttonStandaloneClassName = buttonClassName + "--standalone"; /// <summary> /// USS class name for empty state label. /// </summary> public static readonly string emptyStateLabelClassName = buttonGroupClassName + "__empty-label"; // Main container that will hold the group of buttons. This is what we set as the visualInput element. VisualElement m_ButtonGroupContainer; // Hold a list of available buttons on the group. List<Button> m_Buttons = new(); // Used for the empty state. VisualElement m_EmptyLabel; const string k_EmptyStateLabel = "Group has no buttons."; private bool m_IsMultipleSelection; private bool m_AllowEmptySelection; /// <summary> /// Whether all buttons can be selected. /// </summary> [CreateProperty] public bool isMultipleSelection { get => m_IsMultipleSelection; set { if (m_IsMultipleSelection == value) return; var toggleButtonGroupState = this.value; var selected = toggleButtonGroupState.GetActiveOptions(stackalloc int[toggleButtonGroupState.length]); if (selected.Length > 1 && m_Buttons.Count > 0) { // Clear additional selected buttons and assign the first available to be selected toggleButtonGroupState.ResetAllOptions(); toggleButtonGroupState[selected[0]] = true; SetValueWithoutNotify(toggleButtonGroupState); } m_IsMultipleSelection = value; NotifyPropertyChanged(isMultipleSelectionProperty); } } /// <summary> /// Allows having all buttons to be unchecked when set to true. /// </summary> /// <remarks> /// When the property value is false, the control will automatically set the first available button to checked. /// </remarks> [CreateProperty] public bool allowEmptySelection { get => m_AllowEmptySelection; set { if (m_AllowEmptySelection == value) return; // Select the first button if empty selection is not allowed if (!value) { var toggleButtonGroupState = this.value; var selected = toggleButtonGroupState.GetActiveOptions(stackalloc int[toggleButtonGroupState.length]); if (selected.Length == 0 && m_Buttons.Count > 0) { toggleButtonGroupState[0] = true; SetValueWithoutNotify(toggleButtonGroupState); } } m_AllowEmptySelection = value; NotifyPropertyChanged(allowEmptySelectionProperty); } } /// <summary> /// Constructs a ToggleButtonGroup. /// </summary> public ToggleButtonGroup() : this(null) {} /// <summary> /// Constructs a ToggleButtonGroup. /// </summary> /// <param name="label">The text used as a label.</param> public ToggleButtonGroup(string label) : this(label, new ToggleButtonGroupState(0, ToggleButtonGroupState.maxLength)) { } /// <summary> /// Constructs a ToggleButtonGroup. /// </summary> /// <param name="toggleButtonGroupState">The ToggleButtonGroupState to be used by this control.</param> public ToggleButtonGroup(ToggleButtonGroupState toggleButtonGroupState) : this(null, toggleButtonGroupState) { } /// <summary> /// Constructs a ToggleButtonGroup. /// </summary> /// <param name="label">The text used as a label.</param> /// <param name="toggleButtonGroupState">The ToggleButtonGroupState to be used by this control.</param> public ToggleButtonGroup(string label, ToggleButtonGroupState toggleButtonGroupState) : base(label) { AddToClassList(ussClassName); visualInput = new VisualElement { name = containerUssClassName, classList = { buttonGroupClassName } }; m_ButtonGroupContainer = visualInput; // Note: We are changing the workflow through these series of callback. The desired workflow is when a user // adds a new button, we would take the button and apply the necessary style and give it the designed // functionality for a ToggleButtonGroup's button. Because we are not overwriting the contentContainer // of this control, we need to make sure that elementAdded is hooked for ToggleButtonGroup and its // internal contentContainer separately, otherwise it would not receive the expected workflow when a // control is added into this. m_ButtonGroupContainer.elementAdded += OnButtonGroupContainerElementAdded; m_ButtonGroupContainer.elementRemoved += OnButtonGroupContainerElementRemoved; SetValueWithoutNotify(toggleButtonGroupState); } public override VisualElement contentContainer => m_ButtonGroupContainer ?? this; protected override void UpdateMixedValueContent() { if (showMixedValue) { foreach (var button in m_Buttons) { button.pseudoStates &= ~(PseudoStates.Checked); button.IncrementVersion(VersionChangeType.Styles); } } else { SetValueWithoutNotify(value); } } /// <summary> /// Sets a new value without triggering any change event. /// </summary> /// <param name="newValue">The new value.</param> public override void SetValueWithoutNotify(ToggleButtonGroupState newValue) { if (newValue.length == 0) { newValue = new ToggleButtonGroupState(0, 0); m_EmptyLabel ??= new Label(k_EmptyStateLabel) { name = emptyStateLabelClassName, classList = { emptyStateLabelClassName } }; visualInput.Insert(0, m_EmptyLabel); } else { m_EmptyLabel?.RemoveFromHierarchy(); } base.SetValueWithoutNotify(newValue); UpdateButtonStates(newValue); } void OnButtonGroupContainerElementAdded(VisualElement ve) { if (ve is not Button button) { // We want the empty label there. Early out. if (ve == m_EmptyLabel) return; // Since we only allow buttons, we move anything that is not a button outside of our contentContainer. hierarchy.Add(ve); return; } // The plus one being the button being added. if (m_Buttons.Count + 1 > ToggleButtonGroupState.maxLength) { Debug.LogWarning(k_MaxToggleButtonGroupMessage); return; } // Assign the required class and functionality to the button being added. button.AddToClassList(buttonClassName); button.clickable.clickedWithEventInfo += OnOptionChange; // Since we aren't passing index back and forth, this is the best way for now to get the latest ordered list // of buttons. m_Buttons = m_ButtonGroupContainer.Query<Button>().ToList(); UpdateButtonsStyling(); var needsSetValue = false; var toggleButtonGroupState = value; // If there are more buttons than the ToggleButtonGroupState length, we need to increase it so that it doesn't throw. if (m_Buttons.Count >= value.length && m_Buttons.Count <= ToggleButtonGroupState.maxLength) { toggleButtonGroupState.length = m_Buttons.Count; needsSetValue = true; } // If we don't allow empty selection, we set the first button to be checked. if (value.data == 0 && !allowEmptySelection) { toggleButtonGroupState[0] = true; needsSetValue = true; } if (needsSetValue) { value = toggleButtonGroupState; } } void OnButtonGroupContainerElementRemoved(VisualElement ve) { if (ve is not Button button) return; var toggleButtonGroupState = value; var checkedButtonIndex = m_Buttons.IndexOf(button); var selected = toggleButtonGroupState.GetActiveOptions(stackalloc int[toggleButtonGroupState.length]); var isRemovedButtonChecked = selected.IndexOf(checkedButtonIndex) != -1; button.clickable.clickedWithEventInfo -= OnOptionChange; if (isRemovedButtonChecked) m_Buttons[checkedButtonIndex].pseudoStates &= ~(PseudoStates.Checked); m_Buttons.Remove(button); UpdateButtonsStyling(); toggleButtonGroupState.length = m_Buttons.Count; if (m_Buttons.Count == 0) { toggleButtonGroupState.ResetAllOptions(); SetValueWithoutNotify(toggleButtonGroupState); } else if (isRemovedButtonChecked) { toggleButtonGroupState[checkedButtonIndex] = false; if (!allowEmptySelection && selected.Length == 1) toggleButtonGroupState[0] = true; value = toggleButtonGroupState; } } void UpdateButtonStates(ToggleButtonGroupState options) { var span = options.GetActiveOptions(stackalloc int[value.length]); for (var i = 0; i < m_Buttons.Count; i++) { if (span.IndexOf(i) == -1) { m_Buttons[i].pseudoStates &= ~(PseudoStates.Checked); m_Buttons[i].IncrementVersion(VersionChangeType.Styles); continue; } m_Buttons[i].pseudoStates |= PseudoStates.Checked; m_Buttons[i].IncrementVersion(VersionChangeType.Styles); } } void OnOptionChange(EventBase evt) { var button = evt.target as Button; var index = m_Buttons.IndexOf(button); var toggleButtonGroupState = value; var selected = toggleButtonGroupState.GetActiveOptions(stackalloc int[toggleButtonGroupState.length]); // With showMixedValue, we want to make sure we are starting with an empty state to match the logic inside // the updateMixedValueContent method. Additionally, this makes base.value trigger a valid value change. if (showMixedValue) { var emptiedState = value; emptiedState.ResetAllOptions(); if (value != emptiedState) { SetValueWithoutNotify(emptiedState); } } if (isMultipleSelection) { // Always have one selected even for a multiple selection ToggleButtonGroup - return if we're trying // to deselect the last active one if (!allowEmptySelection && selected.Length == 1 && toggleButtonGroupState[index]) return; if (toggleButtonGroupState[index]) toggleButtonGroupState[index] = false; else toggleButtonGroupState[index] = true; } else { if (allowEmptySelection && selected.Length == 1 && toggleButtonGroupState[selected[0]]) { toggleButtonGroupState[selected[0]] = false; if (index != selected[0]) toggleButtonGroupState[index] = true; } else { toggleButtonGroupState.ResetAllOptions(); toggleButtonGroupState[index] = true; } } value = toggleButtonGroupState; } void UpdateButtonsStyling() { var buttonCount = m_Buttons.Count; for (var i = 0; i < buttonCount; i++) { var button = m_Buttons[i]; var isStandaloneButton = buttonCount == 1; var isLeftButton = i == 0 && !isStandaloneButton; var isRightButton = i == buttonCount - 1 && !isStandaloneButton; var isMiddleButton = !isLeftButton && !isRightButton && !isStandaloneButton; button.EnableInClassList(buttonStandaloneClassName, isStandaloneButton); button.EnableInClassList(buttonLeftClassName, isLeftButton); button.EnableInClassList(buttonRightClassName, isRightButton); button.EnableInClassList(buttonMidClassName, isMiddleButton); } } } }
UnityCsReference/Modules/UIElements/Core/Controls/ToggleButtonGroup/ToggleButtonGroup.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Controls/ToggleButtonGroup/ToggleButtonGroup.cs", "repo_id": "UnityCsReference", "token_count": 8169 }
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 static UnityEngine.InputForUI.PointerEvent; namespace UnityEngine.UIElements { internal partial class DefaultEventSystem { private bool isAppFocused => Application.isFocused; internal static Func<bool> IsEditorRemoteConnected = () => false; private bool ShouldIgnoreEventsOnAppNotFocused() { switch (SystemInfo.operatingSystemFamily) { case OperatingSystemFamily.Windows: case OperatingSystemFamily.Linux: case OperatingSystemFamily.MacOSX: if (IsEditorRemoteConnected()) return false; return true; default: return false; } } private BaseRuntimePanel m_FocusedPanel; private BaseRuntimePanel m_PreviousFocusedPanel; private Focusable m_PreviousFocusedElement; public BaseRuntimePanel focusedPanel { get => m_FocusedPanel; set { if (m_FocusedPanel != value) { m_FocusedPanel?.Blur(); m_FocusedPanel = value; m_FocusedPanel?.Focus(); } } } public void Reset() { m_LegacyInputProcessor?.Reset(); m_InputForUIProcessor?.Reset(); m_FocusedPanel = null; } public enum UpdateMode { Always, IgnoreIfAppNotFocused } public void Update(UpdateMode updateMode = UpdateMode.Always) { if (!isAppFocused && ShouldIgnoreEventsOnAppNotFocused() && updateMode == UpdateMode.IgnoreIfAppNotFocused) return; if (m_IsInputForUIActive) { inputForUIProcessor.ProcessInputForUIEvents(); } else { legacyInputProcessor.ProcessLegacyInputEvents(); } } private LegacyInputProcessor m_LegacyInputProcessor; // Internal for Unit Tests internal LegacyInputProcessor legacyInputProcessor => m_LegacyInputProcessor ??= new LegacyInputProcessor(this); private InputForUIProcessor m_InputForUIProcessor; private InputForUIProcessor inputForUIProcessor => m_InputForUIProcessor ??= new InputForUIProcessor(this); private bool m_IsInputReady = false; internal bool isInputReady { get => m_IsInputReady; set { if (m_IsInputReady == value) return; m_IsInputReady = value; if (m_IsInputReady) { InitInputProcessor(); } else { RemoveInputProcessor(); } } } private bool m_UseInputForUI = true; internal bool useInputForUI { get => m_UseInputForUI; set { if (m_UseInputForUI == value) return; if (m_IsInputReady) { RemoveInputProcessor(); m_UseInputForUI = value; InitInputProcessor(); } else { m_UseInputForUI = value; } } } private bool m_IsInputForUIActive = false; internal struct FocusBasedEventSequenceContext : IDisposable { private DefaultEventSystem es; public FocusBasedEventSequenceContext(DefaultEventSystem es) { this.es = es; es.m_PreviousFocusedPanel = es.focusedPanel; es.m_PreviousFocusedElement = es.focusedPanel?.focusController.GetLeafFocusedElement(); } public void Dispose() { es.m_PreviousFocusedPanel = null; es.m_PreviousFocusedElement = null; } } internal FocusBasedEventSequenceContext FocusBasedEventSequence() { return new FocusBasedEventSequenceContext(this); } void RemoveInputProcessor() { if (m_IsInputForUIActive) { UnityEngine.InputForUI.EventProvider.Unsubscribe(inputForUIProcessor.OnEvent); UnityEngine.InputForUI.EventProvider.SetEnabled(false); m_IsInputForUIActive = false; } } void InitInputProcessor() { if (m_UseInputForUI) { m_IsInputForUIActive = true; UnityEngine.InputForUI.EventProvider.SetEnabled(true); UnityEngine.InputForUI.EventProvider.Subscribe(inputForUIProcessor.OnEvent); } } // Change focused panel to reflect an element being focused by code. However // - Do not modify the target of any ongoing focus-based event sequence // - Do not unfocus the current focused panel if its element loses focus internal void OnFocusEvent(RuntimePanel panel, FocusEvent evt) { focusedPanel = panel; } // Internal for Unit Tests internal void SendFocusBasedEvent<TArg>(Func<TArg, EventBase> evtFactory, TArg arg) { // Send all focus-based events to the same previously focused panel if there's one // This allows Navigation events to use the same target as related KeyDown (and eventually Gamepad) events if (m_PreviousFocusedPanel != null) { using (EventBase evt = evtFactory(arg)) { evt.elementTarget = (VisualElement) m_PreviousFocusedElement ?? m_PreviousFocusedPanel.visualTree; m_PreviousFocusedPanel.visualTree.SendEvent(evt); UpdateFocusedPanel(m_PreviousFocusedPanel); return; } } // Send Keyboard events to all panels if none is focused. // This is so that navigation with Tab can be started without clicking on an element. // Try all the panels, from closest to deepest var panels = UIElementsRuntimeUtility.GetSortedPlayerPanels(); for (var i = panels.Count - 1; i >= 0; i--) { var panel = panels[i]; if (panel is BaseRuntimePanel runtimePanel) { using (EventBase evt = evtFactory(arg)) { // Since there was no focused element, send event to the visualTree to avoid reacting to a // focus change in between events. evt.elementTarget = runtimePanel.visualTree; runtimePanel.visualTree.SendEvent(evt); if (runtimePanel.focusController.focusedElement != null) { focusedPanel = runtimePanel; break; } if (evt.isPropagationStopped) { return; } } } } } void SendPositionBasedEvent<TArg>(Vector3 mousePosition, Vector3 delta, int pointerId, int? targetDisplay, Func<Vector3, Vector3, TArg, EventBase> evtFactory, TArg arg, bool deselectIfNoTarget = false) { // Allow focus to be lost before processing the event if (focusedPanel != null) { UpdateFocusedPanel(focusedPanel); } var capturingPanel = PointerDeviceState.GetPlayerPanelWithSoftPointerCapture(pointerId); // Allow element with pointer capture to update panel soft capture var capturing = RuntimePanel.s_EventDispatcher.pointerState.GetCapturingElement(pointerId); if (capturing is VisualElement capturingVE) { capturingPanel = capturingVE.panel; } BaseRuntimePanel targetPanel = null; Vector2 targetPanelPosition = Vector2.zero; Vector2 targetPanelDelta = Vector2.zero; if (capturingPanel is BaseRuntimePanel capturingRuntimePanel) { // Panel with soft capture has priority, that is it will receive pointer events until pointer up targetPanel = capturingRuntimePanel; targetPanel.ScreenToPanel(mousePosition, delta, out targetPanelPosition, out targetPanelDelta); } else { // Find a candidate panel for the event // Try all the panels, from closest to deepest var panels = UIElementsRuntimeUtility.GetSortedPlayerPanels(); for (var i = panels.Count - 1; i >= 0; i--) { if (panels[i] is BaseRuntimePanel runtimePanel && (targetDisplay == null || runtimePanel.targetDisplay == targetDisplay)) { if (runtimePanel.ScreenToPanel(mousePosition, delta, out targetPanelPosition, out targetPanelDelta) && runtimePanel.Pick(targetPanelPosition) != null) { targetPanel = runtimePanel; break; } } } } BaseRuntimePanel lastActivePanel = PointerDeviceState.GetPanel(pointerId, ContextType.Player) as BaseRuntimePanel; if (lastActivePanel != targetPanel) { // Allow last panel the pointer was in to dispatch [Mouse|Pointer][Out|Leave] events if needed. lastActivePanel?.PointerLeavesPanel(pointerId, lastActivePanel.ScreenToPanel(mousePosition)); targetPanel?.PointerEntersPanel(pointerId, targetPanelPosition); } if (targetPanel != null) { using (EventBase evt = evtFactory(targetPanelPosition, targetPanelDelta, arg)) { targetPanel.visualTree.SendEvent(evt); if (evt.processedByFocusController) { UpdateFocusedPanel(targetPanel); } if (evt.eventTypeId == PointerDownEvent.TypeId()) PointerDeviceState.SetPlayerPanelWithSoftPointerCapture(pointerId, targetPanel); else if (evt.eventTypeId == PointerUpEvent.TypeId() && ((PointerUpEvent)evt).pressedButtons == 0) PointerDeviceState.SetPlayerPanelWithSoftPointerCapture(pointerId, null); } } else { if (deselectIfNoTarget) { focusedPanel = null; } } } private void UpdateFocusedPanel(BaseRuntimePanel runtimePanel) { if (runtimePanel.focusController.focusedElement != null) { focusedPanel = runtimePanel; } else if (focusedPanel == runtimePanel) { focusedPanel = null; } } private static EventBase MakeTouchEvent(Touch touch, EventModifiers modifiers, int targetDisplay) { switch (touch.phase) { case TouchPhase.Began: return PointerDownEvent.GetPooled(touch, modifiers, targetDisplay); case TouchPhase.Moved: return PointerMoveEvent.GetPooled(touch, modifiers, targetDisplay); case TouchPhase.Ended: return PointerUpEvent.GetPooled(touch, modifiers, targetDisplay); case TouchPhase.Canceled: return PointerCancelEvent.GetPooled(touch, modifiers, targetDisplay); default: return null; } } private static EventBase MakePenEvent(PenData pen, EventModifiers modifiers, int targetDisplay) { switch (pen.contactType) { case PenEventType.PenDown: return PointerDownEvent.GetPooled(pen, modifiers, targetDisplay); case PenEventType.PenUp: return PointerUpEvent.GetPooled(pen, modifiers, targetDisplay); case PenEventType.NoContact: return PointerMoveEvent.GetPooled(pen, modifiers, targetDisplay); default: return null; } } // For testing purposes internal bool verbose = false; internal bool logToGameScreen = false; private void Log(object o) { Debug.Log(o); if (logToGameScreen) LogToGameScreen("" + o); } private void LogWarning(object o) { Debug.LogWarning(o); if (logToGameScreen) LogToGameScreen("Warning! " + o); } private Label m_LogLabel; private List<string> m_LogLines = new List<string>(); private void LogToGameScreen(string s) { if (m_LogLabel == null) { m_LogLabel = new Label {style = {position = Position.Absolute, bottom = 0, color = Color.white}}; Object.FindFirstObjectByType<UIDocument>().rootVisualElement.Add(m_LogLabel); } m_LogLines.Add(s + "\n"); if (m_LogLines.Count > 10) m_LogLines.RemoveAt(0); m_LogLabel.text = string.Concat(m_LogLines); } } }
UnityCsReference/Modules/UIElements/Core/DefaultEventSystem.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/DefaultEventSystem.cs", "repo_id": "UnityCsReference", "token_count": 7111 }
484
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEngine.UIElements.Experimental { /// <summary> /// A collection of easing curves to be used with ValueAnimations. /// </summary> /// <remarks> /// Easing curves control the rate of change of a value over time. /// </remarks> public static class Easing { private const float HalfPi = Mathf.PI / 2; /// <undoc/> public static float Step(float t) { return t < 0.5f ? 0 : 1; } /// <undoc/> public static float Linear(float t) { return t; } /// <undoc/> public static float InSine(float t) { return Mathf.Sin(HalfPi * (t - 1)) + 1; } /// <undoc/> public static float OutSine(float t) { return Mathf.Sin(t * HalfPi); } /// <undoc/> public static float InOutSine(float t) { return (Mathf.Sin(Mathf.PI * (t - 0.5f)) + 1) * 0.5f; } /// <undoc/> public static float InQuad(float t) { return t * t; } /// <undoc/> public static float OutQuad(float t) { return t * (2 - t); } /// <undoc/> public static float InOutQuad(float t) { t *= 2; if (t < 1.0f) return (t * t * 0.5f); return -0.5f * ((t - 1) * (t - 3) - 1); } /// <undoc/> public static float InCubic(float t) { return InPower(t, 3); } /// <undoc/> public static float OutCubic(float t) { return OutPower(t, 3); } /// <undoc/> public static float InOutCubic(float t) { return InOutPower(t, 3); } /// <undoc/> public static float InPower(float t, int power) { return Mathf.Pow(t, power); } /// <undoc/> public static float OutPower(float t, int power) { var sign = power % 2 == 0 ? -1 : 1; return (float)(sign * (Mathf.Pow(t - 1, power) + sign)); } /// <undoc/> public static float InOutPower(float t, int power) { t *= 2; if (t < 1) return InPower(t, power) * 0.5f; var sign = power % 2 == 0 ? -1 : 1; return sign * 0.5f * (Mathf.Pow(t - 2, power) + sign * 2); } /// <undoc/> public static float InBounce(float t) { return 1 - OutBounce((1 - t)); } /// <undoc/> public static float OutBounce(float t) { if (t < (1 / 2.75f)) { return (7.5625f * t * t); } if (t < (2 / 2.75f)) { float postFix = t -= (1.5f / 2.75f); return (7.5625f * (postFix) * t + .75f); } else if (t < (2.5f / 2.75f)) { float postFix = t -= (2.25f / 2.75f); return (7.5625f * (postFix) * t + .9375f); } else { float postFix = t -= (2.625f / 2.75f); return (7.5625f * (postFix) * t + .984375f); } } /// <undoc/> public static float InOutBounce(float t) { if (t < 0.5f) { return InBounce(t * 2) * 0.5f; } else { return OutBounce((t - 0.5f) * 2) * 0.5f + 0.5f; } } /// <undoc/> public static float InElastic(float t) { if (t == 0) return 0; if ((t) == 1) return 1; float p = .3f; float s = p / 4; float power = Mathf.Pow(2, 10 * (t -= 1)); return -(power * Mathf.Sin((t - s) * (2 * Mathf.PI) / p)); } /// <undoc/> public static float OutElastic(float t) { if (t == 0) return 0; if (t == 1) return 1; float p = .3f; float s = p / 4; return Mathf.Pow(2, -10 * t) * Mathf.Sin((t - s) * (2 * Mathf.PI) / p) + 1; } /// <undoc/> public static float InOutElastic(float t) { if (t < 0.5f) { return InElastic(t * 2) * 0.5f; } else { return OutElastic((t - 0.5f) * 2) * 0.5f + 0.5f; } } /// <undoc/> public static float InBack(float t) { float s = 1.70158f; return (t) * t * ((s + 1) * t - s); } /// <undoc/> public static float OutBack(float t) { return 1 - (InBack(1 - t)); } /// <undoc/> public static float InOutBack(float t) { if (t < 0.5f) { return InBack(t * 2) * 0.5f; } else { return OutBack((t - 0.5f) * 2) * 0.5f + 0.5f; } } /// <undoc/> public static float InBack(float t, float s) { return (t) * t * ((s + 1) * t - s); } /// <undoc/> public static float OutBack(float t, float s) { return 1 - (InBack(1 - t, s)); } /// <undoc/> public static float InOutBack(float t, float s) { if (t < 0.5f) { return InBack(t * 2, s) * 0.5f; } else { return OutBack((t - 0.5f) * 2, s) * 0.5f + 0.5f; } } /// <undoc/> public static float InCirc(float t) { return -(Mathf.Sqrt(1 - (t * t)) - 1); } /// <undoc/> public static float OutCirc(float t) { t = t - 1; return Mathf.Sqrt(1 - (t * t)); } /// <undoc/> public static float InOutCirc(float t) { t = t * 2; if (t < 1) { return -0.5f * (Mathf.Sqrt(1 - (t * t)) - 1); } else { t = t - 2; return 0.5f * (Mathf.Sqrt(1 - (t * t)) + 1); } } } }
UnityCsReference/Modules/UIElements/Core/EasingCurves.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/EasingCurves.cs", "repo_id": "UnityCsReference", "token_count": 3903 }
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 System.Runtime.CompilerServices; using UnityEngine.UIElements.Experimental; namespace UnityEngine.UIElements { /// <summary> /// Interface for class capable of handling events. /// </summary> public interface IEventHandler { /// <summary> /// Sends an event to the event handler. /// </summary> /// <param name="e">The event to send.</param> void SendEvent(EventBase e); /// <summary> /// Handles an event according to its propagation phase and current target, by executing the element's /// default action or callbacks associated with the event. /// </summary> /// <param name="evt">The event to handle.</param> /// <remarks> /// The <see cref="EventDispatcher"/> may invoke this method multiple times for the same event: once for each /// propagation phase and each target along the event's propagation path if it has matching callbacks or /// overrides default actions for the event. /// /// Do not use this method to intercept all events whose propagation path include this element. There is no /// guarantee that it will or will not be invoked for a propagation phase or target along the propagation path /// if that target has no callbacks for the event and has no default action override that can receive the event. /// /// Use <see cref="CallbackEventHandler.RegisterCallback&lt;TEventType&gt;(EventCallback&lt;TEventType&gt;, TrickleDown)"/>, /// or <see cref="CallbackEventHandler.HandleEventBubbleUp"/> for more predictable results. /// </remarks> /// <seealso cref="CallbackEventHandler.RegisterCallback&lt;TEventType&gt;(EventCallback&lt;TEventType&gt;, TrickleDown)"/> /// <seealso cref="CallbackEventHandler.HandleEventBubbleUp"/> void HandleEvent(EventBase evt); /// <summary> /// Returns true if event handlers, for the event propagation TrickleDown phase, are attached to this object. /// </summary> /// <returns>True if the object already has event handlers for the TrickleDown phase.</returns> bool HasTrickleDownHandlers(); /// <summary> /// Returns true if event handlers for the event propagation BubbleUp phase, have been attached on this object. /// </summary> /// <returns>True if object has event handlers for the BubbleUp phase.</returns> bool HasBubbleUpHandlers(); } /// <summary> /// Interface for classes capable of having callbacks to handle events. /// </summary> public abstract class CallbackEventHandler : IEventHandler { // IMGUIContainers are special snowflakes that need custom treatment regarding events. // This enables early outs in some dispatching strategies. internal bool isIMGUIContainer = false; internal EventCallbackRegistry m_CallbackRegistry; /// <summary> /// Adds an event handler to the instance. If the event handler has already been registered for the same phase (either TrickleDown or BubbleUp) then this method has no effect. /// </summary> /// <param name="callback">The event handler to add.</param> /// <param name="useTrickleDown">By default, this callback is called during the BubbleUp phase. Pass TrickleDown.TrickleDown to call this callback during the TrickleDown phase.</param> public void RegisterCallback<TEventType>(EventCallback<TEventType> callback, TrickleDown useTrickleDown = TrickleDown.NoTrickleDown) where TEventType : EventBase<TEventType>, new() { if (callback == null) throw new ArgumentException("callback parameter is null"); (m_CallbackRegistry ??= new EventCallbackRegistry()).RegisterCallback(callback, useTrickleDown, default); GlobalCallbackRegistry.RegisterListeners<TEventType>(this, callback, useTrickleDown); AddEventCategories<TEventType>(useTrickleDown); } /// <summary> /// Adds an event handler to the instance. If the event handler has already been registered for the same phase (either TrickleDown or BubbleUp) then this method has no effect. /// The event handler is automatically unregistered after it has been invoked exactly once. /// </summary> /// <param name="callback">The event handler to add.</param> /// <param name="useTrickleDown">By default, this callback is called during the BubbleUp phase. Pass TrickleDown.TrickleDown to call this callback during the TrickleDown phase.</param> public void RegisterCallbackOnce<TEventType>(EventCallback<TEventType> callback, TrickleDown useTrickleDown = TrickleDown.NoTrickleDown) where TEventType : EventBase<TEventType>, new() { if (callback == null) throw new ArgumentException("callback parameter is null"); (m_CallbackRegistry ??= new EventCallbackRegistry()).RegisterCallback(callback, useTrickleDown, InvokePolicy.Once); GlobalCallbackRegistry.RegisterListeners<TEventType>(this, callback, useTrickleDown); AddEventCategories<TEventType>(useTrickleDown); } private void AddEventCategories<TEventType>(TrickleDown useTrickleDown) where TEventType : EventBase<TEventType>, new() { if (this is VisualElement ve) { ve.AddEventCallbackCategories(1 << (int)EventBase<TEventType>.EventCategory, useTrickleDown); } } /// <summary> /// Adds an event handler to the instance. If the event handler has already been registered for the same phase (either TrickleDown or BubbleUp) then this method has no effect. /// </summary> /// <param name="callback">The event handler to add.</param> /// <param name="userArgs">Data to pass to the callback.</param> /// <param name="useTrickleDown">By default, this callback is called during the BubbleUp phase. Pass TrickleDown.TrickleDown to call this callback during the TrickleDown phase.</param> public void RegisterCallback<TEventType, TUserArgsType>(EventCallback<TEventType, TUserArgsType> callback, TUserArgsType userArgs, TrickleDown useTrickleDown = TrickleDown.NoTrickleDown) where TEventType : EventBase<TEventType>, new() { if (callback == null) throw new ArgumentException("callback parameter is null"); (m_CallbackRegistry ??= new EventCallbackRegistry()).RegisterCallback(callback, userArgs, useTrickleDown, default); GlobalCallbackRegistry.RegisterListeners<TEventType>(this, callback, useTrickleDown); AddEventCategories<TEventType>(useTrickleDown); } /// <summary> /// Adds an event handler to the instance. If the event handler has already been registered for the same phase (either TrickleDown or BubbleUp) then this method has no effect. /// The event handler is automatically unregistered after it has been invoked exactly once. /// </summary> /// <param name="callback">The event handler to add.</param> /// <param name="userArgs">Data to pass to the callback.</param> /// <param name="useTrickleDown">By default, this callback is called during the BubbleUp phase. Pass TrickleDown.TrickleDown to call this callback during the TrickleDown phase.</param> public void RegisterCallbackOnce<TEventType, TUserArgsType>(EventCallback<TEventType, TUserArgsType> callback, TUserArgsType userArgs, TrickleDown useTrickleDown = TrickleDown.NoTrickleDown) where TEventType : EventBase<TEventType>, new() { if (callback == null) throw new ArgumentException("callback parameter is null"); (m_CallbackRegistry ??= new EventCallbackRegistry()).RegisterCallback(callback, userArgs, useTrickleDown, InvokePolicy.Once); GlobalCallbackRegistry.RegisterListeners<TEventType>(this, callback, useTrickleDown); AddEventCategories<TEventType>(useTrickleDown); } internal void RegisterCallback<TEventType>(EventCallback<TEventType> callback, InvokePolicy invokePolicy, TrickleDown useTrickleDown = TrickleDown.NoTrickleDown) where TEventType : EventBase<TEventType>, new() { (m_CallbackRegistry ??= new EventCallbackRegistry()).RegisterCallback(callback, useTrickleDown, invokePolicy); GlobalCallbackRegistry.RegisterListeners<TEventType>(this, callback, useTrickleDown); AddEventCategories<TEventType>(useTrickleDown); } /// <summary> /// Remove callback from the instance. /// </summary> /// <param name="callback">The callback to remove. If this callback was never registered, nothing happens.</param> /// <param name="useTrickleDown">Set this parameter to true to remove the callback from the TrickleDown phase. Set this parameter to false to remove the callback from the BubbleUp phase.</param> public void UnregisterCallback<TEventType>(EventCallback<TEventType> callback, TrickleDown useTrickleDown = TrickleDown.NoTrickleDown) where TEventType : EventBase<TEventType>, new() { if (callback == null) throw new ArgumentException("callback parameter is null"); m_CallbackRegistry?.UnregisterCallback(callback, useTrickleDown); GlobalCallbackRegistry.UnregisterListeners<TEventType>(this, callback); } /// <summary> /// Remove callback from the instance. /// </summary> /// <param name="callback">The callback to remove. If this callback was never registered, nothing happens.</param> /// <param name="useTrickleDown">Set this parameter to true to remove the callback from the TrickleDown phase. Set this parameter to false to remove the callback from the BubbleUp phase.</param> public void UnregisterCallback<TEventType, TUserArgsType>(EventCallback<TEventType, TUserArgsType> callback, TrickleDown useTrickleDown = TrickleDown.NoTrickleDown) where TEventType : EventBase<TEventType>, new() { if (callback == null) throw new ArgumentException("callback parameter is null"); m_CallbackRegistry?.UnregisterCallback(callback, useTrickleDown); GlobalCallbackRegistry.UnregisterListeners<TEventType>(this, callback); } /// <summary> /// Sends an event to the event handler. /// </summary> /// <param name="e">The event to send.</param> public abstract void SendEvent(EventBase e); internal abstract void SendEvent(EventBase e, DispatchMode dispatchMode); internal abstract void HandleEvent(EventBase e); void IEventHandler.HandleEvent(EventBase evt) { // This is only useful because HandleEvent is public and can be called from user code. if (evt == null) return; HandleEvent(evt); } /// <summary> /// Returns true if event handlers, for the event propagation TrickleDown phase, are attached to this object. /// </summary> /// <returns>True if object has event handlers for the TrickleDown phase.</returns> public bool HasTrickleDownHandlers() { return m_CallbackRegistry != null && m_CallbackRegistry.HasTrickleDownHandlers(); } /// <summary> /// Return true if event handlers for the event propagation BubbleUp phase have been attached on this object. /// </summary> /// <returns>True if object has event handlers for the BubbleUp phase.</returns> public bool HasBubbleUpHandlers() { return m_CallbackRegistry != null && m_CallbackRegistry.HasBubbleHandlers(); } /// <summary> /// Executes logic after the callbacks registered on each element in the BubbleUp phase have executed, /// unless the event propagation is stopped by one of the callbacks. /// <see cref="EventBase{T}.PreventDefault"/>. /// </summary> /// <remarks> /// This method is designed to be overriden by subclasses. Use it to implement event handling without /// registering callbacks, which guarantees precedences of callbacks registered by users of the subclass. /// /// Use <see cref="EventInterestAttribute"/> on this method to specify a range of event types that this /// method needs to receive. Events that don't fall into the specified types might not be sent to this method. /// </remarks> /// <param name="evt">The event instance.</param> [EventInterest(EventInterestOptions.Inherit)] [Obsolete("Use HandleEventBubbleUp. Before proceeding, make sure you understand the latest changes to " + "UIToolkit event propagation rules by visiting Unity's manual page " + "https://docs.unity3d.com/Manual/UIE-Events-Dispatching.html")] protected virtual void ExecuteDefaultActionAtTarget(EventBase evt) {} /// <summary> /// Executes logic on this element during the BubbleUp phase, immediately before this element's /// BubbleUp callbacks. /// Calling StopPropagation will prevent further invocations of this method along the propagation path. /// </summary> /// <remarks> /// This method is designed to be overriden by subclasses. Use it to implement event handling without /// registering callbacks, which guarantees precedences of callbacks registered by users of the subclass. /// /// Use <see cref="EventInterestAttribute"/> on this method to specify a range of event types that this /// method needs to receive. Events that don't fall into the specified types might not be sent to this method. /// </remarks> /// <param name="evt">The event instance.</param> [EventInterest(EventInterestOptions.Inherit)] protected virtual void HandleEventBubbleUp(EventBase evt) {} [EventInterest(EventInterestOptions.Inherit)] internal virtual void HandleEventBubbleUpDisabled(EventBase evt) {} [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void HandleEventBubbleUpInternal(EventBase evt) => HandleEventBubbleUp(evt); internal const string HandleEventBubbleUpName = nameof(HandleEventBubbleUp); /// <summary> /// Executes logic on this element during the TrickleDown phase, immediately after this element's /// TrickleDown callbacks. /// Calling StopPropagation will prevent further invocations of this method along the propagation path. /// </summary> /// <remarks> /// This method is designed to be overriden by subclasses. Use it to implement event handling without /// registering callbacks, which guarantees precedences of callbacks registered by users of the subclass. /// /// Use <see cref="EventInterestAttribute"/> on this method to specify a range of event types that this /// method needs to receive. Events that don't fall into the specified types might not be sent to this method. /// </remarks> /// <param name="evt">The event instance.</param> [EventInterest(EventInterestOptions.Inherit)] protected virtual void HandleEventTrickleDown(EventBase evt) {} [EventInterest(EventInterestOptions.Inherit)] internal virtual void HandleEventTrickleDownDisabled(EventBase evt) {} [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void HandleEventTrickleDownInternal(EventBase evt) => HandleEventTrickleDown(evt); internal const string HandleEventTrickleDownName = nameof(HandleEventTrickleDown); /// <summary> /// Executes logic after the callbacks registered on the event target have executed, /// unless the event has been marked to prevent its default behaviour. /// <see cref="EventBase{T}.PreventDefault"/>. /// </summary> /// <remarks> /// This method is designed to be overriden by subclasses. Use it to implement event handling without /// registering callbacks which guarantees precedences of callbacks registered by users of the subclass. /// Unlike <see cref="HandleEventBubbleUp"/>, this method is called after both the callbacks registered /// on the element and callbacks registered on its ancestors with <see cref="TrickleDown.NoTrickleDown"/>. /// /// Use <see cref="EventInterestAttribute"/> on this method to specify a range of event types that this /// method needs to receive. Events that don't fall into the specified types might not be sent to this method. /// </remarks> /// <param name="evt">The event instance.</param> [EventInterest(EventInterestOptions.Inherit)] [Obsolete("Use HandleEventBubbleUp. Before proceeding, make sure you understand the latest changes to " + "UIToolkit event propagation rules by visiting Unity's manual page " + "https://docs.unity3d.com/Manual/UIE-Events-Dispatching.html")] protected virtual void ExecuteDefaultAction(EventBase evt) {} [EventInterest(EventInterestOptions.Inherit)] [Obsolete("Use HandleEventBubbleUpDisabled.")] internal virtual void ExecuteDefaultActionDisabledAtTarget(EventBase evt) {} [EventInterest(EventInterestOptions.Inherit)] [Obsolete("Use HandleEventBubbleUpDisabled.")] internal virtual void ExecuteDefaultActionDisabled(EventBase evt) {} #pragma warning disable 618 [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void ExecuteDefaultActionInternal(EventBase evt) => ExecuteDefaultAction(evt); [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void ExecuteDefaultActionDisabledInternal(EventBase evt) => ExecuteDefaultActionDisabled(evt); [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void ExecuteDefaultActionAtTargetInternal(EventBase evt) => ExecuteDefaultActionAtTarget(evt); [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void ExecuteDefaultActionDisabledAtTargetInternal(EventBase evt) => ExecuteDefaultActionDisabledAtTarget(evt); internal const string ExecuteDefaultActionName = nameof(ExecuteDefaultAction); internal const string ExecuteDefaultActionAtTargetName = nameof(ExecuteDefaultActionAtTarget); #pragma warning restore 618 /// <summary> /// Informs the data binding system that a property of a control has changed. /// </summary> /// <param name="property">The property that has changed.</param> protected void NotifyPropertyChanged(in BindingId property) { var element = this as VisualElement; if (null == element?.elementPanel) return; using var evt = PropertyChangedEvent.GetPooled(property); evt.target = this; SendEvent(evt); } } }
UnityCsReference/Modules/UIElements/Core/Events/EventHandler.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Events/EventHandler.cs", "repo_id": "UnityCsReference", "token_count": 6569 }
486
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEngine.UIElements { // This is an event to hold unimplemented UnityEngine.Event EventType. // The goal of this is to be able to pass these events to IMGUI. /// <summary> /// Class used to send a IMGUI event that has no equivalent UIElements event. /// </summary> [EventCategory(EventCategory.IMGUI)] public class IMGUIEvent : EventBase<IMGUIEvent> { static IMGUIEvent() { SetCreateFunction(() => new IMGUIEvent()); } /// <summary> /// Gets an event from the event pool and initializes it with the given values. Use this function instead of creating new events. Events obtained using this method need to be released back to the pool. You can use `Dispose()` to release them. /// </summary> /// <param name="systemEvent">The IMGUI event used to initialize the event.</param> /// <returns>An initialized event.</returns> public static IMGUIEvent GetPooled(Event systemEvent) { IMGUIEvent e = GetPooled(); e.imguiEvent = systemEvent; return e; } /// <summary> /// Resets the event members to their initial values. /// </summary> protected override void Init() { base.Init(); LocalInit(); } void LocalInit() { propagation = EventPropagation.Bubbles | EventPropagation.TricklesDown; } /// <summary> /// Constructor. Use GetPooled() to get an event from a pool of reusable events. /// </summary> public IMGUIEvent() { LocalInit(); } internal override void Dispatch(BaseVisualElementPanel panel) { EventDispatchUtilities.DispatchToPanelRoot(this, panel); } } }
UnityCsReference/Modules/UIElements/Core/Events/UIEvent.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Events/UIEvent.cs", "repo_id": "UnityCsReference", "token_count": 790 }
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.Collections.Generic; namespace UnityEngine.UIElements { /// <summary> /// Interface used to implement group management for <see cref="IGroupBox"/>. /// </summary> internal interface IGroupManager { void Init(IGroupBox groupBox); IGroupBoxOption GetSelectedOption(); void OnOptionSelectionChanged(IGroupBoxOption selectedOption); void RegisterOption(IGroupBoxOption option); void UnregisterOption(IGroupBoxOption option); } /// <summary> /// This is the default implementation of group management for <see cref="IGroupBox"/>. /// It is by default used on <see cref="IPanel"/> and <see cref="GroupBox"/>. /// A different implementation can be provided by using <see cref="IGroupBox{T}"/> instead. /// </summary> internal class DefaultGroupManager : IGroupManager { List<IGroupBoxOption> m_GroupOptions = new List<IGroupBoxOption>(); IGroupBoxOption m_SelectedOption; IGroupBox m_GroupBox; public void Init(IGroupBox groupBox) { m_GroupBox = groupBox; } public IGroupBoxOption GetSelectedOption() { return m_SelectedOption; } public void OnOptionSelectionChanged(IGroupBoxOption selectedOption) { if (m_SelectedOption == selectedOption) return; m_SelectedOption = selectedOption; foreach (var option in m_GroupOptions) { option.SetSelected(option == m_SelectedOption); } } public void RegisterOption(IGroupBoxOption option) { if (!m_GroupOptions.Contains(option)) { m_GroupOptions.Add(option); m_GroupBox.OnOptionAdded(option); } } public void UnregisterOption(IGroupBoxOption option) { m_GroupOptions.Remove(option); m_GroupBox.OnOptionRemoved(option); } } }
UnityCsReference/Modules/UIElements/Core/IGroupManager.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/IGroupManager.cs", "repo_id": "UnityCsReference", "token_count": 915 }
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.Runtime.InteropServices; using Unity.Profiling; namespace UnityEngine.UIElements.Layout; interface ILayoutProcessor { void CalculateLayout( LayoutNode node, float parentWidth, float parentHeight, LayoutDirection parentDirection); } static class LayoutProcessor { static ILayoutProcessor s_Processor = new LayoutProcessorNative(); public static ILayoutProcessor Processor { get => s_Processor; set => s_Processor = value ?? new LayoutProcessorNative(); } public static void CalculateLayout( LayoutNode node, float parentWidth, float parentHeight, LayoutDirection parentDirection) { s_Processor.CalculateLayout(node, parentWidth, parentHeight, parentDirection); } } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void InvokeMeasureFunctionDelegate( ref LayoutNode node, float width, LayoutMeasureMode widthMode, float height, LayoutMeasureMode heightMode, ref IntPtr exception, out LayoutSize result); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate float InvokeBaselineFunctionDelegate( ref LayoutNode node, float width, float height); static class LayoutDelegates { static readonly ProfilerMarker s_InvokeMeasureFunctionMarker = new("InvokeMeasureFunction"); static readonly ProfilerMarker s_InvokeBaselineFunctionMarker = new("InvokeBaselineFunction"); [AOT.MonoPInvokeCallback(typeof(InvokeMeasureFunctionDelegate))] static void InvokeMeasureFunction( ref LayoutNode node, float width, LayoutMeasureMode widthMode, float height, LayoutMeasureMode heightMode, ref IntPtr exception, out LayoutSize result) { var measureFunction = node.Measure; if (measureFunction == null) { Debug.Assert(false, "Measure called on a null method"); result = default; return; } // Fix for UUM-48790: // AddressSanitizer (ASAN) is lost when we throw an exception from c# // which is called from c++, which in turn is called from c#. // C# : Measure Function <-- Exception // C++: LayoutNative // C# : LayoutProcessorNative <-- Catch // To solve this issue we return the exception using a GCHandle // to LayoutProcessorNative using intptr_t pointer in c++. try { using (s_InvokeMeasureFunctionMarker.Auto()) measureFunction(node.GetOwner(), ref node, width, widthMode, height, heightMode, out result); } catch (Exception e) { GCHandle handle = GCHandle.Alloc(e); exception = GCHandle.ToIntPtr(handle); result = default; } } [AOT.MonoPInvokeCallback(typeof(InvokeBaselineFunctionDelegate))] static float InvokeBaselineFunction( ref LayoutNode node, float width, float height) { var baselineFunction = node.Baseline; if (baselineFunction == null) { return 0f; } using (s_InvokeBaselineFunctionMarker.Auto()) return baselineFunction(ref node, width, height); } static readonly InvokeMeasureFunctionDelegate s_InvokeMeasureDelegate = InvokeMeasureFunction; static readonly InvokeBaselineFunctionDelegate s_InvokeBaselineDelegate = InvokeBaselineFunction; internal static readonly IntPtr s_InvokeMeasureFunction = Marshal.GetFunctionPointerForDelegate(s_InvokeMeasureDelegate); internal static readonly IntPtr s_InvokeBaselineFunction = Marshal.GetFunctionPointerForDelegate(s_InvokeBaselineDelegate); }
UnityCsReference/Modules/UIElements/Core/Layout/LayoutProcessor.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Layout/LayoutProcessor.cs", "repo_id": "UnityCsReference", "token_count": 1476 }
489
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEngine.UIElements.Layout; enum LayoutJustify { FlexStart, Center, FlexEnd, SpaceBetween, SpaceAround, SpaceEvenly, }
UnityCsReference/Modules/UIElements/Core/Layout/Model/LayoutJustify.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Layout/Model/LayoutJustify.cs", "repo_id": "UnityCsReference", "token_count": 109 }
490
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEngine.UIElements { /// <summary> /// Describes a MouseButton. /// </summary> public enum MouseButton { /// <summary> /// The Left Mouse Button. /// </summary> LeftMouse = 0, /// <summary> /// The Right Mouse Button. /// </summary> RightMouse = 1, /// <summary> /// The Middle Mouse Button. /// </summary> MiddleMouse = 2 } }
UnityCsReference/Modules/UIElements/Core/MouseButton.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/MouseButton.cs", "repo_id": "UnityCsReference", "token_count": 255 }
491
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; namespace UnityEngine.UIElements { static class ProjectionUtils { // Returns a matrix that maps (left, bottom, near) to (-1, -1, -1) and (right, top, far) to (1, 1, 1) // Warning: Do not confuse this with Matrix4x4.Ortho. public static Matrix4x4 Ortho(float left, float right, float bottom, float top, float near, float far) { var result = new Matrix4x4(); float rightMinusLeft = right - left; float topMinusBottom = top - bottom; float farMinusNear = far - near; result.m00 = 2 / rightMinusLeft; result.m11 = 2 / topMinusBottom; result.m22 = 2 / farMinusNear; result.m03 = -(right + left) / rightMinusLeft; result.m13 = -(top + bottom) / topMinusBottom; result.m23 = -(far + near) / farMinusNear; result.m33 = 1; return result; } } }
UnityCsReference/Modules/UIElements/Core/ProjectionUtils.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/ProjectionUtils.cs", "repo_id": "UnityCsReference", "token_count": 489 }
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; using Unity.Profiling; namespace UnityEngine.UIElements.UIR { /// <summary> /// This class manages a vertical atlas of horizontal GradientSettings. /// </summary> class GradientSettingsAtlas : IDisposable { static ProfilerMarker s_MarkerWrite = new ProfilerMarker("UIR.GradientSettingsAtlas.Write"); static ProfilerMarker s_MarkerCommit = new ProfilerMarker("UIR.GradientSettingsAtlas.Commit"); readonly int m_Length; readonly int m_ElemWidth; internal int length { get { return m_Length; } } BestFitAllocator m_Allocator; Texture2D m_Atlas; // Should be accessed through the property RawTexture m_RawAtlas; static int s_TextureCounter; #region Dispose Pattern protected bool disposed { get; private set; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposed) return; if (disposing) { UIRUtility.Destroy(m_Atlas); } else UnityEngine.UIElements.DisposeHelper.NotifyMissingDispose(this); disposed = true; } #endregion // Dispose Pattern public GradientSettingsAtlas(int length = 4096) { m_Length = length; m_ElemWidth = 3; Reset(); } public void Reset() { if (disposed) { DisposeHelper.NotifyDisposedUsed(this); return; } // TODO: Re-init should be deferred. m_Allocator = new BestFitAllocator((uint)m_Length); UIRUtility.Destroy(m_Atlas); m_RawAtlas = new RawTexture(); MustCommit = false; } public Texture2D atlas { get { return m_Atlas; } } public Alloc Add(int count) { Debug.Assert(count > 0); if (disposed) { DisposeHelper.NotifyDisposedUsed(this); return new Alloc(); } Alloc alloc = m_Allocator.Allocate((uint)count); return alloc; } public void Remove(Alloc alloc) { if (disposed) { DisposeHelper.NotifyDisposedUsed(this); return; } m_Allocator.Free(alloc); } public void Write(Alloc alloc, GradientSettings[] settings, GradientRemap remap) { if (disposed) { DisposeHelper.NotifyDisposedUsed(this); return; } if (m_RawAtlas.rgba == null) { m_RawAtlas = new RawTexture { rgba = new Color32[m_ElemWidth * m_Length], width = m_ElemWidth, height = m_Length }; int size = m_ElemWidth * m_Length; for (int i = 0; i < size; ++i) m_RawAtlas.rgba[i] = Color.black; } s_MarkerWrite.Begin(); int destY = (int)alloc.start; for (int i = 0, settingsCount = settings.Length; i < settingsCount; ++i) { int destX = 0; GradientSettings entry = settings[i]; Debug.Assert(remap == null || destY == remap.destIndex); if (entry.gradientType == GradientType.Radial) { var focus = entry.radialFocus; focus += Vector2.one; focus /= 2.0f; focus.y = 1.0f - focus.y; m_RawAtlas.WriteRawFloat4Packed((float)GradientType.Radial / 255, (float)entry.addressMode / 255, focus.x, focus.y, destX++, destY); } else if (entry.gradientType == GradientType.Linear) { m_RawAtlas.WriteRawFloat4Packed(0.0f, (float)entry.addressMode / 255, 0.0f, 0.0f, destX++, destY); } Vector2Int pos = new Vector2Int(entry.location.x, entry.location.y); var size = new Vector2(entry.location.width - 1, entry.location.height - 1); if (remap != null) { pos = new Vector2Int(remap.location.x, remap.location.y); size = new Vector2(remap.location.width - 1, remap.location.height - 1); } m_RawAtlas.WriteRawInt2Packed(pos.x, pos.y, destX++, destY); m_RawAtlas.WriteRawInt2Packed((int)size.x, (int)size.y, destX++, destY); remap = remap?.next; ++destY; } MustCommit = true; s_MarkerWrite.End(); } public bool MustCommit { get; private set; } public void Commit() { if (disposed) { DisposeHelper.NotifyDisposedUsed(this); return; } if (!MustCommit) return; PrepareAtlas(); s_MarkerCommit.Begin(); // TODO: This way of transferring is costly since it is a synchronous operation that flushes the pipeline. m_Atlas.SetPixels32(m_RawAtlas.rgba); m_Atlas.Apply(); s_MarkerCommit.End(); MustCommit = false; } void PrepareAtlas() { if (m_Atlas != null) return; m_Atlas = new Texture2D(m_ElemWidth, m_Length, TextureFormat.ARGB32, 0, true) { hideFlags = HideFlags.HideAndDontSave, name = "GradientSettings " + s_TextureCounter++, filterMode = FilterMode.Point }; } struct RawTexture { public Color32[] rgba; public int width; public int height; public void WriteRawInt2Packed(int v0, int v1, int destX, int destY) { byte r = (byte)(v0 / 255); byte g = (byte)(v0 - r * 255); byte b = (byte)(v1 / 255); byte a = (byte)(v1 - b * 255); int offset = destY * width + destX; rgba[offset] = new Color32(r, g, b, a); } public void WriteRawFloat4Packed(float f0, float f1, float f2, float f3, int destX, int destY) { byte r = (byte)(f0 * 255f + 0.5f); byte g = (byte)(f1 * 255f + 0.5f); byte b = (byte)(f2 * 255f + 0.5f); byte a = (byte)(f3 * 255f + 0.5f); int offset = destY * width + destX; rgba[offset] = new Color32(r, g, b, a); } } } }
UnityCsReference/Modules/UIElements/Core/Renderer/UIRGradientSettingsAtlas.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Renderer/UIRGradientSettingsAtlas.cs", "repo_id": "UnityCsReference", "token_count": 3869 }
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 Unity.Profiling; using UnityEngine.UIElements.UIR; namespace UnityEngine.UIElements { internal class UIRRepaintUpdater : BaseVisualTreeUpdater { BaseVisualElementPanel attachedPanel; internal RenderChain renderChain; // May be recreated any time. public UIRRepaintUpdater() { panelChanged += OnPanelChanged; } private static readonly string s_Description = "Update Rendering"; private static readonly ProfilerMarker s_ProfilerMarker = new ProfilerMarker(s_Description); public override ProfilerMarker profilerMarker => s_ProfilerMarker; public bool drawStats { get; set; } public bool breakBatches { get; set; } public override void OnVersionChanged(VisualElement ve, VersionChangeType versionChangeType) { if (renderChain == null) return; bool transformChanged = (versionChangeType & VersionChangeType.Transform) != 0; bool sizeChanged = (versionChangeType & VersionChangeType.Size) != 0; bool overflowChanged = (versionChangeType & VersionChangeType.Overflow) != 0; bool borderRadiusChanged = (versionChangeType & VersionChangeType.BorderRadius) != 0; bool borderWidthChanged = (versionChangeType & VersionChangeType.BorderWidth) != 0; bool renderHintsChanged = (versionChangeType & VersionChangeType.RenderHints) != 0; bool disableRenderingChanged = (versionChangeType & VersionChangeType.DisableRendering) != 0; bool repaintChanged = (versionChangeType & VersionChangeType.Repaint) != 0; if (renderHintsChanged) renderChain.UIEOnRenderHintsChanged(ve); if (transformChanged || sizeChanged || borderWidthChanged) renderChain.UIEOnTransformOrSizeChanged(ve, transformChanged, sizeChanged || borderWidthChanged); if (overflowChanged || borderRadiusChanged) renderChain.UIEOnClippingChanged(ve, false); if ((versionChangeType & VersionChangeType.Opacity) != 0) renderChain.UIEOnOpacityChanged(ve); if ((versionChangeType & VersionChangeType.Color) != 0) renderChain.UIEOnColorChanged(ve); if (repaintChanged) renderChain.UIEOnVisualsChanged(ve, false); if (disableRenderingChanged && !repaintChanged) // The disable rendering will be taken care of by the repaint (it clear all commands) renderChain.UIEOnDisableRenderingChanged(ve); } public override void Update() { if (renderChain == null) InitRenderChain(); if (renderChain == null || renderChain.device == null) return; renderChain.ProcessChanges(); // Apply these debug values every frame because the render chain may have been recreated. renderChain.drawStats = drawStats; renderChain.device.breakBatches = breakBatches; } void Render() { // Since the calls to Update and Render can be disjoint, this check seems reasonable. if (renderChain == null) return; Debug.Assert(!renderChain.drawInCameras); renderChain.Render(); } // Overriden in tests protected virtual RenderChain CreateRenderChain() { return new RenderChain(panel); } static UIRRepaintUpdater() { UIR.Utility.GraphicsResourcesRecreate += OnGraphicsResourcesRecreate; } static void OnGraphicsResourcesRecreate(bool recreate) { if (!recreate) UIRenderDevice.PrepareForGfxDeviceRecreate(); var it = UIElementsUtility.GetPanelsIterator(); while (it.MoveNext()) if (recreate) it.Current.Value.atlas?.Reset(); else (it.Current.Value.GetUpdater(VisualTreeUpdatePhase.Repaint) as UIRRepaintUpdater)?.DestroyRenderChain(); if (!recreate) UIRenderDevice.FlushAllPendingDeviceDisposes(); else UIRenderDevice.WrapUpGfxDeviceRecreate(); } void OnPanelChanged(BaseVisualElementPanel obj) { DetachFromPanel(); AttachToPanel(); } void AttachToPanel() { Debug.Assert(attachedPanel == null); if (panel == null) return; attachedPanel = panel; attachedPanel.SetRenderAction(Render); attachedPanel.isFlatChanged += OnPanelIsFlatChanged; attachedPanel.atlasChanged += OnPanelAtlasChanged; attachedPanel.standardShaderChanged += OnPanelStandardShaderChanged; attachedPanel.standardWorldSpaceShaderChanged += OnPanelStandardWorldSpaceShaderChanged; attachedPanel.hierarchyChanged += OnPanelHierarchyChanged; if (panel is BaseRuntimePanel runtimePanel) runtimePanel.drawsInCamerasChanged += OnPanelDrawsInCamerasChanged; } void DetachFromPanel() { if (attachedPanel == null) return; DestroyRenderChain(); if (panel is BaseRuntimePanel runtimePanel) runtimePanel.drawsInCamerasChanged -= OnPanelDrawsInCamerasChanged; attachedPanel.isFlatChanged -= OnPanelIsFlatChanged; attachedPanel.atlasChanged -= OnPanelAtlasChanged; attachedPanel.standardShaderChanged -= OnPanelStandardShaderChanged; attachedPanel.standardWorldSpaceShaderChanged -= OnPanelStandardWorldSpaceShaderChanged; attachedPanel.hierarchyChanged -= OnPanelHierarchyChanged; attachedPanel.SetRenderAction(null); attachedPanel = null; } void InitRenderChain() { Debug.Assert(attachedPanel != null); renderChain = CreateRenderChain(); renderChain.UIEOnChildAdded(attachedPanel.visualTree); OnPanelStandardShaderChanged(); if (panel.contextType == ContextType.Player) OnPanelStandardWorldSpaceShaderChanged(); } internal void DestroyRenderChain() { if (renderChain == null) return; renderChain.Dispose(); renderChain = null; ResetAllElementsDataRecursive(attachedPanel.visualTree); } void OnPanelIsFlatChanged() { DestroyRenderChain(); } void OnPanelAtlasChanged() { DestroyRenderChain(); } void OnPanelDrawsInCamerasChanged() { DestroyRenderChain(); } void OnPanelHierarchyChanged(VisualElement ve, HierarchyChangeType changeType) { if (renderChain == null) return; switch (changeType) { case HierarchyChangeType.Add: renderChain.UIEOnChildAdded(ve); break; case HierarchyChangeType.Remove: renderChain.UIEOnChildRemoving(ve); break; case HierarchyChangeType.Move: renderChain.UIEOnChildrenReordered(ve); break; } } void OnPanelStandardShaderChanged() { if (renderChain == null) return; Shader shader = panel.standardShader; if (shader == null) { shader = Shader.Find(UIRUtility.k_DefaultShaderName); Debug.Assert(shader != null, "Failed to load UIElements default shader"); if (shader != null) shader.hideFlags |= HideFlags.DontSaveInEditor; } renderChain.defaultShader = shader; } void OnPanelStandardWorldSpaceShaderChanged() { if (renderChain == null) return; Shader shader = panel.standardWorldSpaceShader; if (shader == null) { shader = Shader.Find(UIRUtility.k_DefaultWorldSpaceShaderName); Debug.Assert(shader != null, "Failed to load UIElements default world-space shader"); if (shader != null) shader.hideFlags |= HideFlags.DontSaveInEditor; } renderChain.defaultWorldSpaceShader = shader; } void ResetAllElementsDataRecursive(VisualElement ve) { ve.renderChainData = new RenderChainVEData(); // Fast reset, no need to go through device freeing // Recurse on children int childrenCount = ve.hierarchy.childCount - 1; while (childrenCount >= 0) ResetAllElementsDataRecursive(ve.hierarchy[childrenCount--]); } #region Dispose Pattern protected bool disposed { get; private set; } protected override void Dispose(bool disposing) { if (disposed) return; if (disposing) DetachFromPanel(); else UnityEngine.UIElements.DisposeHelper.NotifyMissingDispose(this); disposed = true; } #endregion // Dispose Pattern } }
UnityCsReference/Modules/UIElements/Core/Renderer/UIRRepaintUpdater.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Renderer/UIRRepaintUpdater.cs", "repo_id": "UnityCsReference", "token_count": 4331 }
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; namespace UnityEngine.UIElements { // All values are milliseconds // notes on precision: // the event will be fired no sooner than delayMs, and repeat no sooner than intervalMs // this means that depending on system and application state the events could be fired less often or intervals skipped entirely. // it is the registrar's responsibility to read the TimerState to determine the actual event timing // and make sure things like animation are smooth and time based. // a delayMs of 0 and intervalMs of 0 will be interpreted as "as often as possible" this should be used sparingly and the work done should be very small /// <summary> /// Contains timing information of scheduler events. /// </summary> public struct TimerState : IEquatable<TimerState> { /// <summary> /// Start time in milliseconds, or last callback time for repeatable <see cref="IScheduledItem"/>. /// </summary> public long start { get; set; } /// <summary> /// Current time in milliseconds. /// </summary> public long now { get; set; } /// <summary> /// Time difference in milliseconds between <see cref="now"/> and the previous callback. /// </summary> public long deltaTime { get { return now - start; } } /// <summary> /// Compare this object with another object and return true if they are equal. /// </summary> /// <param name="obj">The object to compare with.</param> /// <returns>True if the objects are equal.</returns> public override bool Equals(object obj) { return obj is TimerState && Equals((TimerState)obj); } /// <summary> /// Compare this object with another object and return true if they are equal. /// </summary> /// <param name="other">The object to compare with.</param> /// <returns>True if the objects are equal.</returns> public bool Equals(TimerState other) { return start == other.start && now == other.now && deltaTime == other.deltaTime; } public override int GetHashCode() { var hashCode = 540054806; hashCode = hashCode * -1521134295 + start.GetHashCode(); hashCode = hashCode * -1521134295 + now.GetHashCode(); hashCode = hashCode * -1521134295 + deltaTime.GetHashCode(); return hashCode; } /// <undoc/> public static bool operator==(TimerState state1, TimerState state2) { return state1.Equals(state2); } /// <undoc/> public static bool operator!=(TimerState state1, TimerState state2) { return !(state1 == state2); } } // the scheduler public interface internal interface IScheduler { ScheduledItem ScheduleOnce(Action<TimerState> timerUpdateEvent, long delayMs); ScheduledItem ScheduleUntil(Action<TimerState> timerUpdateEvent, long delayMs, long intervalMs, Func<bool> stopCondition = null); ScheduledItem ScheduleForDuration(Action<TimerState> timerUpdateEvent, long delayMs, long intervalMs, long durationMs); // removes the event. // an event that is never stopped will not be stopped until the panel is cleaned-up. void Unschedule(ScheduledItem item); void Schedule(ScheduledItem item); void UpdateScheduledEvents(); } internal abstract class ScheduledItem //: IScheduledItem { // delegate that returns a boolean public Func<bool> timerUpdateStopCondition; public static readonly Func<bool> OnceCondition = () => true; public static readonly Func<bool> ForeverCondition = () => false; public long startMs { get; set; } public long delayMs { get; set; } public long intervalMs { get; set; } public long endTimeMs { get; private set; } public ScheduledItem() { ResetStartTime(); timerUpdateStopCondition = OnceCondition; } protected void ResetStartTime() { this.startMs = Panel.TimeSinceStartupMs(); } public void SetDuration(long durationMs) { endTimeMs = startMs + durationMs; } public abstract void PerformTimerUpdate(TimerState state); internal virtual void OnItemUnscheduled() {} public virtual bool ShouldUnschedule() { if (timerUpdateStopCondition != null) { return timerUpdateStopCondition(); } return false; } } // default scheduler implementation internal class TimerEventScheduler : IScheduler { private readonly List<ScheduledItem> m_ScheduledItems = new List<ScheduledItem>(); private bool m_TransactionMode; private readonly List<ScheduledItem> m_ScheduleTransactions = new List<ScheduledItem>(); // order is important schedules are executed in add order private readonly HashSet<ScheduledItem> m_UnscheduleTransactions = new HashSet<ScheduledItem>(); // order no important. removal from m_ScheduledItems has no side effect internal bool disableThrottling = false; private int m_LastUpdatedIndex = -1; private class TimerEventSchedulerItem : ScheduledItem { // delegate that takes a timer state and returns void private readonly Action<TimerState> m_TimerUpdateEvent; public TimerEventSchedulerItem(Action<TimerState> updateEvent) { m_TimerUpdateEvent = updateEvent; } public override void PerformTimerUpdate(TimerState state) { m_TimerUpdateEvent?.Invoke(state); } public override string ToString() { return m_TimerUpdateEvent.ToString(); } } public void Schedule(ScheduledItem item) { if (item == null) return; ScheduledItem scheduledItem = item; if (scheduledItem == null) { throw new NotSupportedException("Scheduled Item type is not supported by this scheduler"); } if (m_TransactionMode) { if (m_UnscheduleTransactions.Remove(scheduledItem)) { // The item was unscheduled then rescheduled in the same transaction. } else if (m_ScheduledItems.Contains(scheduledItem) || m_ScheduleTransactions.Contains(scheduledItem)) { throw new ArgumentException(string.Concat("Cannot schedule function ", scheduledItem, " more than once")); } else { m_ScheduleTransactions.Add(scheduledItem); } } else { if (m_ScheduledItems.Contains(scheduledItem)) { throw new ArgumentException(string.Concat("Cannot schedule function ", scheduledItem, " more than once")); } else { m_ScheduledItems.Add(scheduledItem); } } } public ScheduledItem ScheduleOnce(Action<TimerState> timerUpdateEvent, long delayMs) { var scheduleItem = new TimerEventSchedulerItem(timerUpdateEvent) { delayMs = delayMs }; Schedule(scheduleItem); return scheduleItem; } public ScheduledItem ScheduleUntil(Action<TimerState> timerUpdateEvent, long delayMs, long intervalMs, Func<bool> stopCondition) { var scheduleItem = new TimerEventSchedulerItem(timerUpdateEvent) { delayMs = delayMs, intervalMs = intervalMs, timerUpdateStopCondition = stopCondition }; Schedule(scheduleItem); return scheduleItem; } public ScheduledItem ScheduleForDuration(Action<TimerState> timerUpdateEvent, long delayMs, long intervalMs, long durationMs) { var scheduleItem = new TimerEventSchedulerItem(timerUpdateEvent) { delayMs = delayMs, intervalMs = intervalMs, timerUpdateStopCondition = null }; scheduleItem.SetDuration(durationMs); Schedule(scheduleItem); return scheduleItem; } private bool RemovedScheduledItemAt(int index) { if (index >= 0) { if (index <= m_LastUpdatedIndex) --m_LastUpdatedIndex; m_ScheduledItems.RemoveAt(index); return true; } return false; } public void Unschedule(ScheduledItem item) { ScheduledItem sItem = item; if (sItem != null) { if (m_TransactionMode) { if (m_UnscheduleTransactions.Contains(sItem)) { throw new ArgumentException("Cannot unschedule scheduled function twice" + sItem); } else if (m_ScheduleTransactions.Remove(sItem)) { // A item has been scheduled then unscheduled in the same transaction. which is valid. } else if (m_ScheduledItems.Contains(sItem)) { // Only add it to m_UnscheduleTransactions if it is in m_ScheduledItems. // if it was successfully removed from m_ScheduleTransaction we are fine. m_UnscheduleTransactions.Add(sItem); } else { throw new ArgumentException("Cannot unschedule unknown scheduled function " + sItem); } } else { if (!PrivateUnSchedule(sItem)) { throw new ArgumentException("Cannot unschedule unknown scheduled function " + sItem); } } sItem.OnItemUnscheduled(); // Call OnItemUnscheduled immediately after successful removal even if we are in transaction mode } } bool PrivateUnSchedule(ScheduledItem sItem) { return m_ScheduleTransactions.Remove(sItem) || RemovedScheduledItemAt(m_ScheduledItems.IndexOf(sItem)); } public void UpdateScheduledEvents() { try { m_TransactionMode = true; // TODO: On a GAME Panel game time should be per frame and not change during a frame. // TODO: On an Editor Panel time should be real time long currentTime = Panel.TimeSinceStartupMs(); int itemsCount = m_ScheduledItems.Count; const long maxMsPerUpdate = 20; long maxTime = currentTime + maxMsPerUpdate; int startIndex = m_LastUpdatedIndex + 1; if (startIndex >= itemsCount) startIndex = 0; for (int i = 0; i < itemsCount; i++) { currentTime = Panel.TimeSinceStartupMs(); if (!disableThrottling && currentTime >= maxTime) { //We spent too much time on this frame updating items, we break for now, we'll resume next frame break; } int index = startIndex + i; if (index >= itemsCount) { index -= itemsCount; } ScheduledItem scheduledItem = m_ScheduledItems[index]; bool unscheduleItem = false; if (currentTime - scheduledItem.delayMs >= scheduledItem.startMs) { TimerState timerState = new TimerState { start = scheduledItem.startMs, now = currentTime }; if (!m_UnscheduleTransactions.Contains(scheduledItem)) // Don't execute items that have been marked for future removal scheduledItem.PerformTimerUpdate(timerState); scheduledItem.startMs = currentTime; scheduledItem.delayMs = scheduledItem.intervalMs; if (scheduledItem.ShouldUnschedule()) { unscheduleItem = true; } } if (unscheduleItem || (scheduledItem.endTimeMs > 0 && currentTime > scheduledItem.endTimeMs)) { // if the scheduledItem has been unscheduled explicitly in PerformTimerUpdate then // it will be in m_UnscheduleTransactions and we shouldn't unschedule it again if (!m_UnscheduleTransactions.Contains(scheduledItem)) { Unschedule(scheduledItem); } } m_LastUpdatedIndex = index; } } finally { m_TransactionMode = false; // Rule: remove unscheduled transactions first foreach (var item in m_UnscheduleTransactions) { PrivateUnSchedule(item); } m_UnscheduleTransactions.Clear(); // Then add scheduled transactions foreach (var item in m_ScheduleTransactions) { Schedule(item); } m_ScheduleTransactions.Clear(); } } } }
UnityCsReference/Modules/UIElements/Core/Scheduler.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Scheduler.cs", "repo_id": "UnityCsReference", "token_count": 6930 }
495
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License /******************************************************************************/ // // DO NOT MODIFY // This file has been generated by the UIElementsGenerator tool // See InlineStyleInterfaceCsGenerator class for details // /******************************************************************************/ namespace UnityEngine.UIElements { /// <summary> /// This interface provides access to a VisualElement inline style data. /// </summary> /// <remarks> /// Reading properties from this object will read from the inline style data for this element. /// To read the style data computed for the element use <see cref="IComputedStyle"/> interface. /// Writing to a property will mask the value coming from USS with the provided value however other properties will still match the values from USS. /// </remarks> public partial interface IStyle { /// <summary> /// Alignment of the whole area of children on the cross axis if they span over multiple lines in this container. /// </summary> StyleEnum<Align> alignContent { get; set; } /// <summary> /// Alignment of children on the cross axis of this container. /// </summary> StyleEnum<Align> alignItems { get; set; } /// <summary> /// Similar to align-items, but only for this specific element. /// </summary> StyleEnum<Align> alignSelf { get; set; } /// <summary> /// Background color to paint in the element's box. /// </summary> StyleColor backgroundColor { get; set; } /// <summary> /// Background image to paint in the element's box. /// </summary> StyleBackground backgroundImage { get; set; } /// <summary> /// Background image x position value. /// </summary> StyleBackgroundPosition backgroundPositionX { get; set; } /// <summary> /// Background image y position value. /// </summary> StyleBackgroundPosition backgroundPositionY { get; set; } /// <summary> /// Background image repeat value. /// </summary> StyleBackgroundRepeat backgroundRepeat { get; set; } /// <summary> /// Background image size value. /// </summary> StyleBackgroundSize backgroundSize { get; set; } /// <summary> /// Color of the element's bottom border. /// </summary> StyleColor borderBottomColor { get; set; } /// <summary> /// The radius of the bottom-left corner when a rounded rectangle is drawn in the element's box. /// </summary> StyleLength borderBottomLeftRadius { get; set; } /// <summary> /// The radius of the bottom-right corner when a rounded rectangle is drawn in the element's box. /// </summary> StyleLength borderBottomRightRadius { get; set; } /// <summary> /// Space reserved for the bottom edge of the border during the layout phase. /// </summary> StyleFloat borderBottomWidth { get; set; } /// <summary> /// Color of the element's left border. /// </summary> StyleColor borderLeftColor { get; set; } /// <summary> /// Space reserved for the left edge of the border during the layout phase. /// </summary> StyleFloat borderLeftWidth { get; set; } /// <summary> /// Color of the element's right border. /// </summary> StyleColor borderRightColor { get; set; } /// <summary> /// Space reserved for the right edge of the border during the layout phase. /// </summary> StyleFloat borderRightWidth { get; set; } /// <summary> /// Color of the element's top border. /// </summary> StyleColor borderTopColor { get; set; } /// <summary> /// The radius of the top-left corner when a rounded rectangle is drawn in the element's box. /// </summary> StyleLength borderTopLeftRadius { get; set; } /// <summary> /// The radius of the top-right corner when a rounded rectangle is drawn in the element's box. /// </summary> StyleLength borderTopRightRadius { get; set; } /// <summary> /// Space reserved for the top edge of the border during the layout phase. /// </summary> StyleFloat borderTopWidth { get; set; } /// <summary> /// Bottom distance from the element's box during layout. /// </summary> StyleLength bottom { get; set; } /// <summary> /// Color to use when drawing the text of an element. /// </summary> /// <remarks> /// This property is inherited by default. /// </remarks> StyleColor color { get; set; } /// <summary> /// Mouse cursor to display when the mouse pointer is over an element. /// </summary> StyleCursor cursor { get; set; } /// <summary> /// Defines how an element is displayed in the layout. /// </summary> /// <remarks> /// Unlike the visibility property, this property affects the layout of the element. /// This is a convenient way to hide an element without removing it from the hierarchy (when using the <see cref="DisplayStyle.None"/>). /// </remarks> StyleEnum<DisplayStyle> display { get; set; } /// <summary> /// Initial main size of a flex item, on the main flex axis. The final layout might be smaller or larger, according to the flex shrinking and growing determined by the other flex properties. /// </summary> StyleLength flexBasis { get; set; } /// <summary> /// Direction of the main axis to layout children in a container. /// </summary> StyleEnum<FlexDirection> flexDirection { get; set; } /// <summary> /// Specifies how the item will grow relative to the rest of the flexible items inside the same container. /// </summary> StyleFloat flexGrow { get; set; } /// <summary> /// Specifies how the item will shrink relative to the rest of the flexible items inside the same container. /// </summary> StyleFloat flexShrink { get; set; } /// <summary> /// Placement of children over multiple lines if not enough space is available in this container. /// </summary> StyleEnum<Wrap> flexWrap { get; set; } /// <summary> /// Font size to draw the element's text. /// </summary> /// <remarks> /// This property is inherited by default. /// </remarks> StyleLength fontSize { get; set; } /// <summary> /// Fixed height of an element for the layout. /// </summary> StyleLength height { get; set; } /// <summary> /// Justification of children on the main axis of this container. /// </summary> StyleEnum<Justify> justifyContent { get; set; } /// <summary> /// Left distance from the element's box during layout. /// </summary> StyleLength left { get; set; } /// <summary> /// Increases or decreases the space between characters. /// </summary> StyleLength letterSpacing { get; set; } /// <summary> /// Space reserved for the bottom edge of the margin during the layout phase. /// </summary> StyleLength marginBottom { get; set; } /// <summary> /// Space reserved for the left edge of the margin during the layout phase. /// </summary> StyleLength marginLeft { get; set; } /// <summary> /// Space reserved for the right edge of the margin during the layout phase. /// </summary> StyleLength marginRight { get; set; } /// <summary> /// Space reserved for the top edge of the margin during the layout phase. /// </summary> StyleLength marginTop { get; set; } /// <summary> /// Maximum height for an element, when it is flexible or measures its own size. /// </summary> StyleLength maxHeight { get; set; } /// <summary> /// Maximum width for an element, when it is flexible or measures its own size. /// </summary> StyleLength maxWidth { get; set; } /// <summary> /// Minimum height for an element, when it is flexible or measures its own size. /// </summary> StyleLength minHeight { get; set; } /// <summary> /// Minimum width for an element, when it is flexible or measures its own size. /// </summary> StyleLength minWidth { get; set; } /// <summary> /// Specifies the transparency of an element and of its children. /// </summary> /// <remarks> /// The opacity can be between 0.0 and 1.0. The lower value, the more transparent. /// </remarks> StyleFloat opacity { get; set; } /// <summary> /// How a container behaves if its content overflows its own box. /// </summary> StyleEnum<Overflow> overflow { get; set; } /// <summary> /// Space reserved for the bottom edge of the padding during the layout phase. /// </summary> StyleLength paddingBottom { get; set; } /// <summary> /// Space reserved for the left edge of the padding during the layout phase. /// </summary> StyleLength paddingLeft { get; set; } /// <summary> /// Space reserved for the right edge of the padding during the layout phase. /// </summary> StyleLength paddingRight { get; set; } /// <summary> /// Space reserved for the top edge of the padding during the layout phase. /// </summary> StyleLength paddingTop { get; set; } /// <summary> /// Element's positioning in its parent container. /// </summary> /// <remarks> /// This property is used in conjunction with left, top, right and bottom properties. /// </remarks> StyleEnum<Position> position { get; set; } /// <summary> /// Right distance from the element's box during layout. /// </summary> StyleLength right { get; set; } /// <summary> /// A rotation transformation. /// </summary> StyleRotate rotate { get; set; } /// <summary> /// A scaling transformation. /// </summary> StyleScale scale { get; set; } /// <summary> /// The element's text overflow mode. /// </summary> StyleEnum<TextOverflow> textOverflow { get; set; } /// <summary> /// Drop shadow of the text. /// </summary> StyleTextShadow textShadow { get; set; } /// <summary> /// Top distance from the element's box during layout. /// </summary> StyleLength top { get; set; } /// <summary> /// The transformation origin is the point around which a transformation is applied. /// </summary> StyleTransformOrigin transformOrigin { get; set; } /// <summary> /// Duration to wait before starting a property's transition effect when its value changes. /// </summary> StyleList<TimeValue> transitionDelay { get; set; } /// <summary> /// Time a transition animation should take to complete. /// </summary> StyleList<TimeValue> transitionDuration { get; set; } /// <summary> /// Properties to which a transition effect should be applied. /// </summary> StyleList<StylePropertyName> transitionProperty { get; set; } /// <summary> /// Determines how intermediate values are calculated for properties modified by a transition effect. /// </summary> StyleList<EasingFunction> transitionTimingFunction { get; set; } /// <summary> /// A translate transformation. /// </summary> StyleTranslate translate { get; set; } /// <summary> /// Tinting color for the element's backgroundImage. /// </summary> StyleColor unityBackgroundImageTintColor { get; set; } /// <summary> /// Font to draw the element's text, defined as a Font object. /// </summary> /// <remarks> /// This property is inherited by default. /// </remarks> StyleFont unityFont { get; set; } /// <summary> /// Font to draw the element's text, defined as a FontDefinition structure. It takes precedence over `-unity-font`. /// </summary> /// <remarks> /// This property is inherited by default. /// </remarks> StyleFontDefinition unityFontDefinition { get; set; } /// <summary> /// Font style and weight (normal, bold, italic) to draw the element's text. /// </summary> /// <remarks> /// This property is inherited by default. /// </remarks> StyleEnum<FontStyle> unityFontStyleAndWeight { get; set; } /// <summary> /// Specifies which box the element content is clipped against. /// </summary> StyleEnum<OverflowClipBox> unityOverflowClipBox { get; set; } /// <summary> /// Increases or decreases the space between paragraphs. /// </summary> StyleLength unityParagraphSpacing { get; set; } /// <summary> /// Size of the 9-slice's bottom edge when painting an element's background image. /// </summary> StyleInt unitySliceBottom { get; set; } /// <summary> /// Size of the 9-slice's left edge when painting an element's background image. /// </summary> StyleInt unitySliceLeft { get; set; } /// <summary> /// Size of the 9-slice's right edge when painting an element's background image. /// </summary> StyleInt unitySliceRight { get; set; } /// <summary> /// Scale applied to an element's slices. /// </summary> StyleFloat unitySliceScale { get; set; } /// <summary> /// Size of the 9-slice's top edge when painting an element's background image. /// </summary> StyleInt unitySliceTop { get; set; } /// <summary> /// Horizontal and vertical text alignment in the element's box. /// </summary> /// <remarks> /// This property is inherited by default. /// </remarks> StyleEnum<TextAnchor> unityTextAlign { get; set; } /// <summary> /// Switches between Unity's standard and advanced text generator /// </summary> /// <remarks> /// The advanced text generator supports comprehensive Unicode and text shaping for various languages and scripts, including RTL languages. However, it's currently in development and may not have full feature parity with the standard generator. This property is inherited by default and affects text rendering capabilities. /// </remarks> StyleEnum<TextGeneratorType> unityTextGenerator { get; set; } /// <summary> /// Outline color of the text. /// </summary> StyleColor unityTextOutlineColor { get; set; } /// <summary> /// Outline width of the text. /// </summary> StyleFloat unityTextOutlineWidth { get; set; } /// <summary> /// The element's text overflow position. /// </summary> StyleEnum<TextOverflowPosition> unityTextOverflowPosition { get; set; } /// <summary> /// Specifies whether or not an element is visible. /// </summary> /// <remarks> /// This property is inherited by default. /// </remarks> StyleEnum<Visibility> visibility { get; set; } /// <summary> /// Word wrap over multiple lines if not enough space is available to draw the text of an element. /// </summary> /// <remarks> /// This property is inherited by default. /// </remarks> StyleEnum<WhiteSpace> whiteSpace { get; set; } /// <summary> /// Fixed width of an element for the layout. /// </summary> StyleLength width { get; set; } /// <summary> /// Increases or decreases the space between words. /// </summary> StyleLength wordSpacing { get; set; } } }
UnityCsReference/Modules/UIElements/Core/Style/Generated/IStyle.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Style/Generated/IStyle.cs", "repo_id": "UnityCsReference", "token_count": 6317 }
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; using System.Collections.Generic; using Unity.Properties; using UnityEngine.Scripting; using UnityEngine.TextCore.Text; namespace UnityEngine.UIElements { partial class InlineStyleAccessPropertyBag : PropertyBag<InlineStyleAccess>, INamedProperties<InlineStyleAccess> { readonly List<IProperty<InlineStyleAccess>> m_PropertiesList; readonly Dictionary<string, IProperty<InlineStyleAccess>> m_PropertiesHash; abstract class InlineStyleProperty<TStyleValue, TValue> : Property<InlineStyleAccess, TStyleValue> where TStyleValue : IStyleValue<TValue>, new() { protected InlineStyleProperty() { // Defines basic conversions between value, keyword and StyleValue ConverterGroups.RegisterGlobal((ref TStyleValue sv) => sv.value); ConverterGroups.RegisterGlobal((ref TValue v) => new TStyleValue {value = v}); ConverterGroups.RegisterGlobal((ref TStyleValue sv) => sv.keyword); ConverterGroups.RegisterGlobal((ref StyleKeyword kw) => new TStyleValue {keyword = kw}); } public abstract string ussName { get; } } abstract class InlineStyleEnumProperty<TValue> : InlineStyleProperty<StyleEnum<TValue>, TValue> where TValue : struct, IConvertible { } abstract class InlineStyleColorProperty : InlineStyleProperty<StyleColor, Color> { protected InlineStyleColorProperty() { ConverterGroups.RegisterGlobal((ref Color32 v) => new StyleColor(v)); ConverterGroups.RegisterGlobal((ref StyleColor sv) => (Color32) sv.value); } } abstract class InlineStyleBackgroundProperty : InlineStyleProperty<StyleBackground, Background> { protected InlineStyleBackgroundProperty() { ConverterGroups.RegisterGlobal((ref Texture2D v) => new StyleBackground(v)); ConverterGroups.RegisterGlobal((ref Sprite v) => new StyleBackground(v)); ConverterGroups.RegisterGlobal((ref VectorImage v) => new StyleBackground(v)); ConverterGroups.RegisterGlobal((ref StyleBackground sv) => sv.value.texture); ConverterGroups.RegisterGlobal((ref StyleBackground sv) => sv.value.sprite); ConverterGroups.RegisterGlobal((ref StyleBackground sv) => sv.value.renderTexture); ConverterGroups.RegisterGlobal((ref StyleBackground sv) => sv.value.vectorImage); } } abstract class InlineStyleLengthProperty : InlineStyleProperty<StyleLength, Length> { protected InlineStyleLengthProperty() { ConverterGroups.RegisterGlobal((ref float v) => new StyleLength(v)); ConverterGroups.RegisterGlobal((ref int v) => new StyleLength(v)); ConverterGroups.RegisterGlobal((ref StyleLength sv) => sv.value.value); ConverterGroups.RegisterGlobal((ref StyleLength sv) => (int)sv.value.value); } } abstract class InlineStyleFloatProperty : InlineStyleProperty<StyleFloat, float> { protected InlineStyleFloatProperty() { ConverterGroups.RegisterGlobal((ref int v) => new StyleFloat(v)); ConverterGroups.RegisterGlobal((ref StyleFloat sv) => (int)sv.value); } } abstract class InlineStyleListProperty<T> : InlineStyleProperty<StyleList<T>, List<T>> { } abstract class InlineStyleFontProperty : InlineStyleProperty<StyleFont, Font> { } abstract class InlineStyleFontDefinitionProperty : InlineStyleProperty<StyleFontDefinition, FontDefinition> { protected InlineStyleFontDefinitionProperty() { ConverterGroups.RegisterGlobal((ref Font v) => new StyleFontDefinition(v)); ConverterGroups.RegisterGlobal((ref FontAsset v) => new StyleFontDefinition(v)); ConverterGroups.RegisterGlobal((ref StyleFontDefinition sv) => sv.value.font); ConverterGroups.RegisterGlobal((ref StyleFontDefinition sv) => sv.value.fontAsset); } } abstract class InlineStyleIntProperty : InlineStyleProperty<StyleInt, int> { } abstract class InlineStyleRotateProperty : InlineStyleProperty<StyleRotate, Rotate> { } abstract class InlineStyleScaleProperty : InlineStyleProperty<StyleScale, Scale> { } abstract class InlineStyleCursorProperty : InlineStyleProperty<StyleCursor, Cursor> { } abstract class InlineStyleTextShadowProperty : InlineStyleProperty<StyleTextShadow, TextShadow> { } abstract class InlineStyleTransformOriginProperty : InlineStyleProperty<StyleTransformOrigin, TransformOrigin> { } abstract class InlineStyleTranslateProperty : InlineStyleProperty<StyleTranslate, Translate> { } abstract class InlineStyleBackgroundPositionProperty : InlineStyleProperty<StyleBackgroundPosition, BackgroundPosition> { } abstract class InlineStyleBackgroundRepeatProperty : InlineStyleProperty<StyleBackgroundRepeat, BackgroundRepeat> { } abstract class InlineStyleBackgroundSizeProperty : InlineStyleProperty<StyleBackgroundSize, BackgroundSize> { } void AddProperty<TStyleValue, TValue>(InlineStyleProperty<TStyleValue, TValue> property) where TStyleValue : IStyleValue<TValue>, new() { m_PropertiesList.Add(property); m_PropertiesHash.Add(property.Name, property); if (string.CompareOrdinal(property.Name, property.ussName) != 0) m_PropertiesHash.Add(property.ussName, property); } public override PropertyCollection<InlineStyleAccess> GetProperties() => new PropertyCollection<InlineStyleAccess>(m_PropertiesList); public override PropertyCollection<InlineStyleAccess> GetProperties(ref InlineStyleAccess container) => new PropertyCollection<InlineStyleAccess>(m_PropertiesList); public bool TryGetProperty(ref InlineStyleAccess container, string name, out IProperty<InlineStyleAccess> property) => m_PropertiesHash.TryGetValue(name, out property); } }
UnityCsReference/Modules/UIElements/Core/Style/InlineStyleAccess.PropertyBag.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Style/InlineStyleAccess.PropertyBag.cs", "repo_id": "UnityCsReference", "token_count": 2682 }
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 Unity.Profiling; using UnityEngine.Bindings; namespace UnityEngine.UIElements { [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal struct StyleDataRef<T> : IEquatable<StyleDataRef<T>> where T : struct, IEquatable<T>, IStyleDataGroup<T> { private class RefCounted { private static uint m_NextId = 1; private int m_RefCount; private readonly uint m_Id; public T value; public int refCount => m_RefCount; public uint id => m_Id; public RefCounted() { m_RefCount = 1; m_Id = ++m_NextId; } public void Acquire() => ++ m_RefCount; public void Release() { --m_RefCount; } public RefCounted Copy() { return new RefCounted {value = value.Copy()}; } } private RefCounted m_Ref; public int refCount => m_Ref?.refCount ?? 0; public uint id => m_Ref?.id ?? 0; public StyleDataRef<T> Acquire() { m_Ref.Acquire(); return this; } public void Release() { m_Ref.Release(); m_Ref = null; } public void CopyFrom(StyleDataRef<T> other) { if (m_Ref.refCount == 1) { m_Ref.value.CopyFrom(ref other.m_Ref.value); } else { m_Ref.Release(); m_Ref = other.m_Ref; m_Ref.Acquire(); } } public ref readonly T Read() => ref m_Ref.value; public ref T Write() { if (m_Ref.refCount == 1) return ref m_Ref.value; var oldRef = m_Ref; m_Ref = m_Ref.Copy(); oldRef.Release(); return ref m_Ref.value; } public static StyleDataRef<T> Create() { return new StyleDataRef<T> {m_Ref = new RefCounted()}; } public override int GetHashCode() { return m_Ref != null ? m_Ref.value.GetHashCode() : 0; } public static bool operator==(StyleDataRef<T> lhs, StyleDataRef<T> rhs) { return lhs.m_Ref == rhs.m_Ref || lhs.m_Ref.value.Equals(rhs.m_Ref.value); } public static bool operator!=(StyleDataRef<T> lhs, StyleDataRef<T> rhs) { return !(lhs == rhs); } public bool Equals(StyleDataRef<T> other) { return other == this; } public override bool Equals(object obj) { return obj is StyleDataRef<T> other && Equals(other); } public bool ReferenceEquals(StyleDataRef<T> other) { return m_Ref == other.m_Ref; } } }
UnityCsReference/Modules/UIElements/Core/Style/StyleDataRef.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Style/StyleDataRef.cs", "repo_id": "UnityCsReference", "token_count": 1646 }
498
// 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; using UnityEngine.Scripting; namespace UnityEngine.UIElements { class StyleValuePropertyBag<TContainer, TValue> : ContainerPropertyBag<TContainer> where TContainer : IStyleValue<TValue> { class ValueProperty : Property<TContainer, TValue> { public override string Name { get; } = nameof(IStyleValue<TValue>.value); public override bool IsReadOnly { get; } = false; public override TValue GetValue(ref TContainer container) => container.value; public override void SetValue(ref TContainer container, TValue value) => container.value = value; } class KeywordProperty : Property<TContainer, StyleKeyword> { public override string Name { get; } = nameof(IStyleValue<TValue>.keyword); public override bool IsReadOnly { get; } = false; public override StyleKeyword GetValue(ref TContainer container) => container.keyword; public override void SetValue(ref TContainer container, StyleKeyword value) => container.keyword = value; } public StyleValuePropertyBag() { AddProperty(new ValueProperty()); AddProperty(new KeywordProperty()); } } }
UnityCsReference/Modules/UIElements/Core/Style/StyleValue.PropertyBag.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Style/StyleValue.PropertyBag.cs", "repo_id": "UnityCsReference", "token_count": 536 }
499
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine.Bindings; namespace UnityEngine.UIElements { [Serializable] [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal class StyleProperty { [SerializeField] string m_Name; public string name { get { return m_Name; } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal set { m_Name = value; } } [SerializeField] int m_Line; public int line { get { return m_Line; } internal set { m_Line = value; } } [SerializeField] StyleValueHandle[] m_Values; public StyleValueHandle[] values { get { return m_Values; } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal set { m_Values = value; } } [NonSerialized] internal bool isCustomProperty; [NonSerialized] internal bool requireVariableResolve; } }
UnityCsReference/Modules/UIElements/Core/StyleSheets/StyleProperty.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/StyleSheets/StyleProperty.cs", "repo_id": "UnityCsReference", "token_count": 771 }
500
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine.Bindings; namespace UnityEngine.UIElements { [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal enum StyleValueFunction { Unknown, Var, Env, LinearGradient } internal static class StyleValueFunctionExtension { public const string k_Var = "var"; public const string k_Env = "env"; public const string k_LinearGradient = "linear-gradient"; public static StyleValueFunction FromUssString(string ussValue) { ussValue = ussValue.ToLower(); switch (ussValue) { case k_Var: return StyleValueFunction.Var; case k_Env: return StyleValueFunction.Env; case k_LinearGradient: return StyleValueFunction.LinearGradient; default: throw new ArgumentOutOfRangeException(nameof(ussValue), ussValue, "Unknown function name"); } } public static string ToUssString(this StyleValueFunction svf) { switch (svf) { case StyleValueFunction.Var: return k_Var; case StyleValueFunction.Env: return k_Env; case StyleValueFunction.LinearGradient: return k_LinearGradient; default: throw new ArgumentOutOfRangeException(nameof(svf), svf, $"Unknown {nameof(StyleValueFunction)}"); } } } }
UnityCsReference/Modules/UIElements/Core/StyleSheets/StyleValueFunction.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/StyleSheets/StyleValueFunction.cs", "repo_id": "UnityCsReference", "token_count": 859 }
501
// 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.UIElements { [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal class TextSelectingManipulator { [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal TextSelectingUtilities m_SelectingUtilities; bool selectAllOnMouseUp; TextElement m_TextElement; Vector2 m_ClickStartPosition; bool m_Dragged; bool m_IsClicking; const int k_DragThresholdSqr = 16; private int m_ConsecutiveMouseDownCount; private long m_LastMouseDownTimeStamp = 0; internal bool isClicking { get => m_IsClicking; private set { if (m_IsClicking == value) return; m_IsClicking = value; } } public TextSelectingManipulator(TextElement textElement) { m_TextElement = textElement; m_SelectingUtilities = new TextSelectingUtilities(m_TextElement.uitkTextHandle); m_SelectingUtilities.OnCursorIndexChange += OnCursorIndexChange; m_SelectingUtilities.OnSelectIndexChange += OnSelectIndexChange; m_SelectingUtilities.OnRevealCursorChange += OnRevealCursor; } internal int cursorIndex { get => m_SelectingUtilities?.cursorIndex ?? -1; set => m_SelectingUtilities.cursorIndex = value; } internal int selectIndex { get => m_SelectingUtilities?.selectIndex ?? -1; set => m_SelectingUtilities.selectIndex = value; } void OnRevealCursor() { m_TextElement.IncrementVersion(VersionChangeType.Repaint); } void OnSelectIndexChange() { m_TextElement.IncrementVersion(VersionChangeType.Repaint); if(HasSelection() && m_TextElement.focusController != null) m_TextElement.focusController.selectedTextElement = m_TextElement; if(m_SelectingUtilities.revealCursor) m_TextElement.edition.UpdateScrollOffset?.Invoke(false); } void OnCursorIndexChange() { m_TextElement.IncrementVersion(VersionChangeType.Repaint); if(HasSelection() && m_TextElement.focusController != null) m_TextElement.focusController.selectedTextElement = m_TextElement; if(m_SelectingUtilities.revealCursor) m_TextElement.edition.UpdateScrollOffset?.Invoke(false); } internal bool RevealCursor() { return m_SelectingUtilities.revealCursor; } internal bool HasSelection() { return m_SelectingUtilities.hasSelection; } internal bool HasFocus() { return m_TextElement.hasFocus; } internal void HandleEventBubbleUp(EventBase evt) { if (evt is BlurEvent) { m_TextElement.uitkTextHandle.RemoveTextInfoFromCache(); } else if ((evt is not PointerMoveEvent && evt is not MouseMoveEvent) || isClicking) { m_TextElement.uitkTextHandle.AddTextInfoToCache(); } switch (evt) { case FocusEvent: OnFocusEvent(); break; case BlurEvent: OnBlurEvent(); break; case ValidateCommandEvent vce: OnValidateCommandEvent(vce); break; case ExecuteCommandEvent ece: OnExecuteCommandEvent(ece); break; case KeyDownEvent kde: OnKeyDown(kde); break; case PointerDownEvent pde: OnPointerDownEvent(pde); break; case PointerMoveEvent pme: OnPointerMoveEvent(pme); break; case PointerUpEvent pue: OnPointerUpEvent(pue); break; } } void OnFocusEvent() { selectAllOnMouseUp = false; // If focus was given to this element from a mouse click or a Panel.Focus call, allow select on mouse up. if (PointerDeviceState.GetPressedButtons(PointerId.mousePointerId) != 0 || m_TextElement.panel.contextType == ContextType.Editor && Event.current == null) selectAllOnMouseUp = m_TextElement.selection.selectAllOnMouseUp; m_SelectingUtilities.OnFocus(m_TextElement.selection.selectAllOnFocus && !isClicking); } void OnBlurEvent() { selectAllOnMouseUp = m_TextElement.selection.selectAllOnMouseUp; } readonly Event m_ImguiEvent = new Event(); void OnKeyDown(KeyDownEvent evt) { if (!m_TextElement.hasFocus) return; evt.GetEquivalentImguiEvent(m_ImguiEvent); if (m_SelectingUtilities.HandleKeyEvent(m_ImguiEvent)) evt.StopPropagation(); } //Changed to not rely on evt.clickCount to fix https://fogbugz.unity3d.com/f/cases/1409098/ //This is necessary because default event system doesn't support triple click void OnPointerDownEvent(PointerDownEvent evt) { var pointerPosition = evt.localPosition - (Vector3)m_TextElement.contentRect.min; if (evt.button == (int)MouseButton.LeftMouse) { //only move cursor to position if it wasn't a double or triple click. if (evt.timestamp - m_LastMouseDownTimeStamp < Event.GetDoubleClickTime()) m_ConsecutiveMouseDownCount++; else m_ConsecutiveMouseDownCount = 1; if (m_ConsecutiveMouseDownCount == 2 && m_TextElement.selection.doubleClickSelectsWord) { // We need to assign the correct cursor and select index to the current cursor position // prior to selecting the current word. Because selectAllOnMouseUp is true, it'll always // use a cursorIndex of 0. if (cursorIndex == 0 && cursorIndex != selectIndex) m_SelectingUtilities.MoveCursorToPosition_Internal(pointerPosition, evt.shiftKey); m_SelectingUtilities.SelectCurrentWord(); } else if (m_ConsecutiveMouseDownCount == 3 && m_TextElement.selection.tripleClickSelectsLine) m_SelectingUtilities.SelectCurrentParagraph(); else { m_SelectingUtilities.MoveCursorToPosition_Internal(pointerPosition, evt.shiftKey); m_TextElement.edition.UpdateScrollOffset?.Invoke(false); } m_LastMouseDownTimeStamp = evt.timestamp; isClicking = true; m_TextElement.CapturePointer(evt.pointerId); m_ClickStartPosition = pointerPosition; evt.StopPropagation(); } } void OnPointerMoveEvent(PointerMoveEvent evt) { if (!isClicking) return; var pointerPosition = evt.localPosition - (Vector3)m_TextElement.contentRect.min; m_Dragged = m_Dragged || MoveDistanceQualifiesForDrag(m_ClickStartPosition, pointerPosition); if (m_Dragged) { m_SelectingUtilities.SelectToPosition(pointerPosition); m_TextElement.edition.UpdateScrollOffset?.Invoke(false); selectAllOnMouseUp = m_TextElement.selection.selectAllOnMouseUp && !m_SelectingUtilities.hasSelection; } evt.StopPropagation(); } void OnPointerUpEvent(PointerUpEvent evt) { if (evt.button != (int)MouseButton.LeftMouse || !isClicking) return; if (selectAllOnMouseUp) m_SelectingUtilities.SelectAll(); selectAllOnMouseUp = false; m_Dragged = false; isClicking = false; m_TextElement.ReleasePointer(evt.pointerId); evt.StopPropagation(); } void OnValidateCommandEvent(ValidateCommandEvent evt) { if (!m_TextElement.hasFocus) return; switch (evt.commandName) { case EventCommandNames.Cut: case EventCommandNames.Paste: case EventCommandNames.Delete: case EventCommandNames.UndoRedoPerformed: return; case EventCommandNames.Copy: if (!m_SelectingUtilities.hasSelection) return; break; case EventCommandNames.SelectAll: break; } evt.StopPropagation(); } void OnExecuteCommandEvent(ExecuteCommandEvent evt) { if (!m_TextElement.hasFocus) return; switch (evt.commandName) { case EventCommandNames.OnLostFocus: evt.StopPropagation(); return; case EventCommandNames.Copy: m_SelectingUtilities.Copy(); evt.StopPropagation(); return; case EventCommandNames.SelectAll: m_SelectingUtilities.SelectAll(); evt.StopPropagation(); return; } } private bool MoveDistanceQualifiesForDrag(Vector2 start, Vector2 current) { return (start - current).sqrMagnitude >= k_DragThresholdSqr; } } }
UnityCsReference/Modules/UIElements/Core/Text/TextSelectingManipulator.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Text/TextSelectingManipulator.cs", "repo_id": "UnityCsReference", "token_count": 5146 }
502
// 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.UIElements { [VisibleToOtherModules("UnityEditor.UIBuilderModule")] class EnumFieldValueDecoratorAttribute : PropertyAttribute { } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] class EnumFlagsFieldValueDecoratorAttribute : PropertyAttribute { } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] class TagFieldValueDecoratorAttribute : PropertyAttribute { } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] class ImageFieldValueDecoratorAttribute : PropertyAttribute { } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] class FixedItemHeightDecoratorAttribute : PropertyAttribute { } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] class MultilineDecoratorAttribute : PropertyAttribute { } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] class MultilineTextFieldAttribute : PropertyAttribute { } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] class LayerDecoratorAttribute : PropertyAttribute { } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] class BindingModeDrawerAttribute : PropertyAttribute { } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] class DataSourceDrawerAttribute : PropertyAttribute { } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] class AdvanceTextGeneratorDecoratorAttribute : PropertyAttribute { } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] class BindingPathDrawerAttribute : PropertyAttribute { } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] class ConverterDrawerAttribute : PropertyAttribute { public bool isConverterToSource; } }
UnityCsReference/Modules/UIElements/Core/UXML/FieldRenderingAttributes.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/UXML/FieldRenderingAttributes.cs", "repo_id": "UnityCsReference", "token_count": 592 }
503
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using UnityEngine.Assertions; using UnityEngine.Bindings; using UnityEngine.Pool; namespace UnityEngine.UIElements { [Serializable] [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal class VisualElementAsset : UxmlAsset, ISerializationCallbackReceiver { [SerializeField] private string m_Name = string.Empty; [SerializeField] private int m_RuleIndex = -1; public int ruleIndex { get { return m_RuleIndex; } set { m_RuleIndex = value; } } [SerializeField] private string m_Text = string.Empty; [SerializeField] private PickingMode m_PickingMode = PickingMode.Position; [SerializeField] private string[] m_Classes; public string[] classes { get { return m_Classes; } set { m_Classes = value; } } [SerializeField] private List<string> m_StylesheetPaths; public List<string> stylesheetPaths { get { return m_StylesheetPaths ?? (m_StylesheetPaths = new List<string>()); } set { m_StylesheetPaths = value; } } public bool hasStylesheetPaths => m_StylesheetPaths != null; [SerializeField] private List<StyleSheet> m_Stylesheets; public List<StyleSheet> stylesheets { get => m_Stylesheets ??= new List<StyleSheet>(); set => m_Stylesheets = value; } public bool hasStylesheets => m_Stylesheets != null; [SerializeReference] internal UxmlSerializedData m_SerializedData; public UxmlSerializedData serializedData { get => m_SerializedData; set => m_SerializedData = value; } [SerializeField] private bool m_SkipClone; [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal bool skipClone { get => m_SkipClone; set => m_SkipClone = value; } public VisualElementAsset(string fullTypeName, UxmlNamespaceDefinition xmlNamespace = default) : base(fullTypeName, xmlNamespace) { } public void OnBeforeSerialize() {} public void OnAfterDeserialize() { // These properties were previously treated in a special way. // Now they are treated like all other properties. Put them in // the property list. if (!string.IsNullOrEmpty(m_Name) && !m_Properties.Contains("name")) { SetAttribute("name", m_Name); } if (!string.IsNullOrEmpty(m_Text) && !m_Properties.Contains("text")) { SetAttribute("text", m_Text); } if (m_PickingMode != PickingMode.Position && !m_Properties.Contains("picking-mode") && !m_Properties.Contains("pickingMode")) { SetAttribute("picking-mode", m_PickingMode.ToString()); } } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal virtual VisualElement Instantiate(CreationContext cc) { var ve = (VisualElement) serializedData.CreateInstance(); serializedData.Deserialize(ve); if (cc.hasOverrides) { // Applying the overrides in reverse order. This means that the deepest overrides, the ones from nested VisualTreeAssets, // will be applied first and might be overridden by parent VisualTreeAssets. for (var i = cc.serializedDataOverrides.Count - 1; i >= 0; --i) { foreach (var attributeOverride in cc.serializedDataOverrides[i].attributeOverrides) { if (attributeOverride.m_ElementId == id) { attributeOverride.m_SerializedData.Deserialize(ve); } } } } if (hasStylesheetPaths) { for (var i = 0; i < stylesheetPaths.Count; i++) ve.AddStyleSheetPath(stylesheetPaths[i]); } if (hasStylesheets) { for (var i = 0; i < stylesheets.Count; ++i) { if (stylesheets[i] != null) ve.styleSheets.Add(stylesheets[i]); } } if (classes != null) { for (var i = 0; i < classes.Length; i++) ve.AddToClassList(classes[i]); } return ve; } public override string ToString() => $"{m_Name}({fullTypeName})({id})"; } }
UnityCsReference/Modules/UIElements/Core/UXML/VisualElementAsset.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/UXML/VisualElementAsset.cs", "repo_id": "UnityCsReference", "token_count": 2447 }
504
// Unity C# 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; namespace UnityEngine.UIElements { /// <summary> /// Represents a scheduled task created with a VisualElement's schedule interface. /// </summary> public interface IVisualElementScheduledItem { /// <summary> /// Returns the VisualElement this object is associated with. /// </summary> VisualElement element { get; } /// <summary> /// Will be true when this item is scheduled. Note that an item's callback will only be executed when it's VisualElement is attached to a panel. /// </summary> bool isActive { get; } /// <summary> /// If not already active, will schedule this item on its VisualElement's scheduler. /// </summary> void Resume(); /// <summary> /// Removes this item from its VisualElement's scheduler. /// </summary> void Pause(); //will reset the delay of this item // If the item is not currently scheduled, it will resume it /// <summary> /// Cancels any previously scheduled execution of this item and re-schedules the item. /// </summary> /// <param name="delayMs">Minimum time in milliseconds before this item will be executed.</param> void ExecuteLater(long delayMs); //Fluent interface to set parameters /// <summary> /// Adds a delay to the first invokation. /// </summary> /// <param name="delayMs">The minimum number of milliseconds after activation where this item's action will be executed.</param> /// <returns>This ScheduledItem.</returns> IVisualElementScheduledItem StartingIn(long delayMs); /// <summary> /// Repeats this action after a specified time. /// </summary> /// <param name="intervalMs">Minimum amount of time in milliseconds between each action execution.</param> /// <returns>This ScheduledItem.</returns> IVisualElementScheduledItem Every(long intervalMs); /// <summary> /// Item will be unscheduled automatically when specified condition is met. /// </summary> /// <param name="stopCondition">When condition returns true, the item will be unscheduled.</param> /// <returns>This ScheduledItem.</returns> IVisualElementScheduledItem Until(Func<bool> stopCondition); /// <summary> /// After specified duration, the item will be automatically unscheduled. /// </summary> /// <param name="durationMs">The total duration in milliseconds where this item will be active.</param> /// <returns>This ScheduledItem.</returns> IVisualElementScheduledItem ForDuration(long durationMs); } /// <summary> /// A scheduler allows you to register actions to be executed at a later point. /// </summary> public interface IVisualElementScheduler { /// <summary> /// Schedule this action to be executed later. /// </summary> /// <param name="timerUpdateEvent">The action to be executed.</param> /// <returns>Reference to the scheduled action.</returns> IVisualElementScheduledItem Execute(Action<TimerState> timerUpdateEvent); /// <summary> /// Schedule this action to be executed later. /// </summary> /// <param name="updateEvent">The action to be executed.</param> /// <returns>Reference to the scheduled action.</returns> IVisualElementScheduledItem Execute(Action updateEvent); } /// <summary> /// Base class for objects that are part of the UIElements visual tree. /// </summary> /// <remarks> /// VisualElement contains several features that are common to all controls in UIElements, such as layout, styling and event handling. /// Several other classes derive from it to implement custom rendering and define behaviour for controls. /// </remarks> public partial class VisualElement : IVisualElementScheduler { /// <summary> /// Retrieves this VisualElement's IVisualElementScheduler /// </summary> public IVisualElementScheduler schedule { get { return this; } } /// <summary> /// This class is needed in order for its VisualElement to be notified when the scheduler removes an item /// </summary> private abstract class BaseVisualElementScheduledItem : ScheduledItem, IVisualElementScheduledItem { public VisualElement element { get; private set; } public bool isScheduled = false; public bool isActive { get; private set; } public bool isDetaching { get; private set; } private readonly EventCallback<AttachToPanelEvent> m_OnAttachToPanelCallback; private readonly EventCallback<DetachFromPanelEvent> m_OnDetachFromPanelCallback; protected BaseVisualElementScheduledItem(VisualElement handler) { element = handler; m_OnAttachToPanelCallback = OnElementAttachToPanelCallback; m_OnDetachFromPanelCallback = OnElementDetachFromPanelCallback; } private void SetActive(bool action) { if (isActive != action) { isActive = action; if (isActive) { element.RegisterCallback(m_OnAttachToPanelCallback); element.RegisterCallback(m_OnDetachFromPanelCallback); SendActivation(); } else { element.UnregisterCallback(m_OnAttachToPanelCallback); element.UnregisterCallback(m_OnDetachFromPanelCallback); SendDeactivation(); } } } private void SendActivation() { if (CanBeActivated()) { OnPanelActivate(); } } private void SendDeactivation() { if (CanBeActivated()) { OnPanelDeactivate(); } } private void OnElementAttachToPanelCallback(AttachToPanelEvent evt) { if (isActive) { SendActivation(); } } private void OnElementDetachFromPanelCallback(DetachFromPanelEvent evt) { if (!isActive) return; isDetaching = true; try { SendDeactivation(); } finally { isDetaching = false; } } public IVisualElementScheduledItem StartingIn(long delayMs) { this.delayMs = delayMs; return this; } public IVisualElementScheduledItem Until(Func<bool> stopCondition) { if (stopCondition == null) { stopCondition = ForeverCondition; } timerUpdateStopCondition = stopCondition; return this; } public IVisualElementScheduledItem ForDuration(long durationMs) { this.SetDuration(durationMs); return this; } public IVisualElementScheduledItem Every(long intervalMs) { this.intervalMs = intervalMs; if (timerUpdateStopCondition == OnceCondition) { timerUpdateStopCondition = ForeverCondition; } return this; } internal override void OnItemUnscheduled() { base.OnItemUnscheduled(); isScheduled = false; if (!isDetaching) { SetActive(false); } } public void Resume() { SetActive(true); } public void Pause() { SetActive(false); } public void ExecuteLater(long delayMs) { if (!isScheduled) { Resume(); } ResetStartTime(); StartingIn(delayMs); } public void OnPanelActivate() { if (!isScheduled) { isScheduled = true; ResetStartTime(); element.elementPanel.scheduler.Schedule(this); } } public void OnPanelDeactivate() { if (isScheduled) { isScheduled = false; element.elementPanel.scheduler.Unschedule(this); } } public bool CanBeActivated() { return element != null && element.elementPanel != null && element.elementPanel.scheduler != null; } } /// <summary> /// We invoke updateEvents in subclasses to avoid lambda wrapping allocations /// </summary> private abstract class VisualElementScheduledItem<ActionType> : BaseVisualElementScheduledItem { public ActionType updateEvent; public VisualElementScheduledItem(VisualElement handler, ActionType upEvent) : base(handler) { updateEvent = upEvent; } public static bool Matches(ScheduledItem item, ActionType updateEvent) { VisualElementScheduledItem<ActionType> vItem = item as VisualElementScheduledItem<ActionType>; if (vItem != null) { return EqualityComparer<ActionType>.Default.Equals(vItem.updateEvent, updateEvent); } return false; } } private class TimerStateScheduledItem : VisualElementScheduledItem<Action<TimerState>> { public TimerStateScheduledItem(VisualElement handler, Action<TimerState> updateEvent) : base(handler, updateEvent) { } public override void PerformTimerUpdate(TimerState state) { if (isScheduled) { updateEvent(state); } } } //we're doing this to avoid allocating a lambda for simple callbacks that don't need TimerState private class SimpleScheduledItem : VisualElementScheduledItem<Action> { public SimpleScheduledItem(VisualElement handler, Action updateEvent) : base(handler, updateEvent) { } public override void PerformTimerUpdate(TimerState state) { if (isScheduled) { updateEvent(); } } } IVisualElementScheduledItem IVisualElementScheduler.Execute(Action<TimerState> timerUpdateEvent) { var item = new TimerStateScheduledItem(this, timerUpdateEvent) { timerUpdateStopCondition = ScheduledItem.OnceCondition }; item.Resume(); return item; } IVisualElementScheduledItem IVisualElementScheduler.Execute(Action updateEvent) { var item = new SimpleScheduledItem(this, updateEvent) { timerUpdateStopCondition = ScheduledItem.OnceCondition }; item.Resume(); return item; } } }
UnityCsReference/Modules/UIElements/Core/VisualElementScheduler.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/VisualElementScheduler.cs", "repo_id": "UnityCsReference", "token_count": 5794 }
505
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace UnityEngine.UIElements; /// <summary> /// A <see cref="VisualNodeChildren"/> represents a low level view over the children of a <see cref="VisualNode"/>. /// </summary> readonly unsafe struct VisualNodeChildren : IEnumerable<VisualNode> { public struct Enumerator : IEnumerator<VisualNode> { readonly VisualManager m_Manager; readonly VisualNodeChildrenData m_Children; int m_Position; internal Enumerator(VisualManager manager, in VisualNodeChildrenData children) { m_Manager = manager; m_Children = children; m_Position = -1; } public bool MoveNext() => ++m_Position < m_Children.Count; public void Reset() => m_Position = -1; public VisualNode Current => new(m_Manager, m_Children[m_Position]); object IEnumerator.Current => Current; public void Dispose() { } } /// <summary> /// The manager storing the actual node data. /// </summary> readonly VisualManager m_Manager; /// <summary> /// The handle to the underlying data. /// </summary> readonly VisualNodeHandle m_Handle; /// <summary> /// Gets the internal property data ptr. This is only valid outside of structural changes. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] VisualNodeChildrenData* GetDataPtr() => (VisualNodeChildrenData*) m_Manager.GetChildrenPtr(in m_Handle).ToPointer(); /// <summary> /// Gets the number of children. /// </summary> public int Count => m_Manager.GetChildrenCount(in m_Handle); /// <summary> /// Gets the child at the specified index. /// </summary> /// <param name="index">The index of the child to get.</param> public VisualNode this[int index] { get { var data = GetDataPtr(); if ((uint)index >= data->Count) throw new IndexOutOfRangeException(); return new VisualNode(m_Manager, data->ElementAt(index)); } } /// <summary> /// Initializes a new instance of <see cref="VisualNodeChildren"/> for the specified <see cref="VisualNodeHandle"/>. /// </summary> /// <param name="manager">The manager containing the data.</param> /// <param name="handle">The handle to the node.</param> public VisualNodeChildren(VisualManager manager, VisualNodeHandle handle) { m_Manager = manager; m_Handle = handle; } /// <summary> /// Adds the given child to the list. /// </summary> /// <param name="child">The child to add.</param> public void Add(in VisualNode child) { m_Manager.AddChild(m_Handle, child.Handle); } /// <summary> /// Removes the given child from the list. /// </summary> /// <param name="child">The child to remove.</param> public bool Remove(in VisualNode child) { return m_Manager.RemoveChild(m_Handle, child.Handle); } public Enumerator GetEnumerator() => new(m_Manager, *GetDataPtr()); IEnumerator<VisualNode> IEnumerable<VisualNode>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); }
UnityCsReference/Modules/UIElements/Managed/VisualNodeChildren.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Managed/VisualNodeChildren.cs", "repo_id": "UnityCsReference", "token_count": 1263 }
506
// Unity C# 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; namespace UnityEngine.UIElements; /// <summary> /// The <see cref="VisualPanelHandle"/> represents a lightweight handle to native visual panel data. /// </summary> [NativeType(Header = "Modules/UIElements/VisualPanelHandle.h")] [StructLayout(LayoutKind.Sequential)] readonly struct VisualPanelHandle : IEquatable<VisualPanelHandle> { /// <summary> /// Represents a null/invalid handle. /// </summary> public static readonly VisualPanelHandle Null; readonly int m_Id; readonly int m_Version; /// <summary> /// The unique id for this handle. /// </summary> public int Id => m_Id; /// <summary> /// The version number for this handle. /// </summary> public int Version => m_Version; /// <summary> /// Initializes a new instance of the <see cref="VisualPanelHandle"/> struct. /// </summary> /// <param name="id">The handle id.</param> /// <param name="version">The handle version.</param> public VisualPanelHandle(int id, int version) { m_Id = id; m_Version = version; } public static bool operator ==(in VisualPanelHandle lhs, in VisualPanelHandle rhs) => lhs.Id == rhs.Id && lhs.Version == rhs.Version; public static bool operator !=(in VisualPanelHandle lhs, in VisualPanelHandle rhs) => !(lhs == rhs); public bool Equals(VisualPanelHandle other) => other.Id == Id && other.Version == Version; public override string ToString() => $"{nameof(VisualPanelHandle)}({(this == Null ? nameof(Null) : $"{Id}:{Version}")})"; public override bool Equals(object obj) => obj is VisualPanelHandle node && Equals(node); public override int GetHashCode() => HashCode.Combine(Id, Version); }
UnityCsReference/Modules/UIElements/ScriptBindings/VisualPanelHandle.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/ScriptBindings/VisualPanelHandle.bindings.cs", "repo_id": "UnityCsReference", "token_count": 632 }
507
// Unity 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.UIElements.Bindings; abstract class SerializedObjectBindingToBaseField<TValue, TField> : SerializedObjectBindingBase where TField : class, INotifyValueChanged<TValue> { private bool isUpdating; EventCallback<ChangeEvent<TValue>> m_FieldValueChanged; protected override string bindingId { get; } = BindingExtensions.s_SerializedBindingId; protected TField field { get { return m_Field as TField; } set { var ve = field as VisualElement; ve?.UnregisterCallback(m_FieldValueChanged, TrickleDown.TrickleDown); boundElement = value as IBindable; ve = field as VisualElement; ve?.RegisterCallback(m_FieldValueChanged, TrickleDown.TrickleDown); } } protected SerializedObjectBindingToBaseField() { m_FieldValueChanged = FieldValueChanged; } private void FieldValueChanged(ChangeEvent<TValue> evt) { if (isReleased || isUpdating) return; if (evt.target != m_Field) return; try { var undoGroup = Undo.GetCurrentGroup(); var bindable = evt.target as IBindable; var element = (VisualElement) bindable; if (element?.GetBinding(BindingExtensions.s_SerializedBindingId) == this && ResolveProperty()) { if (!isFieldAttached) { //we don't update when field is not attached to a panel //but we don't kill binding either return; } UpdateLastFieldValue(); if (SyncFieldValueToProperty()) { bindingContext.UpdateRevision(); //we make sure to Poll the ChangeTracker here bindingContext.ResetUpdate(); } var fieldUndoGroup = (int?)(field as VisualElement)?.GetProperty(UndoGroupPropertyKey); Undo.CollapseUndoOperations(fieldUndoGroup ?? undoGroup); BindingsStyleHelpers.UpdateElementStyle(field as VisualElement, boundProperty); return; } } catch (NullReferenceException e) when (e.Message.Contains("SerializedObject of SerializedProperty has been Disposed.")) { //this can happen when serializedObject has been disposed of } // Something was wrong Unbind(); } protected override void ResetCachedValues() { UpdateLastFieldValue(); UpdateFieldIsAttached(); if (field is ObjectField objectField) { objectField.SetProperty(ObjectField.serializedPropertyKey, boundProperty); objectField.UpdateDisplay(); } } public override void OnPropertyValueChanged(SerializedProperty currentPropertyIterator) { if (isReleased) return; try { isUpdating = true; var veField = field as VisualElement; if (veField?.GetBinding(bindingId) == this) { SyncPropertyToField(field, currentPropertyIterator); BindingsStyleHelpers.UpdateElementStyle(veField, currentPropertyIterator); return; } } catch (NullReferenceException e) when (e.Message.Contains("SerializedObject of SerializedProperty has been Disposed.")) { //this can happen when serializedObject has been disposed of } finally { isUpdating = false; } // We unbind here Unbind(); } public override void SyncValueWithoutNotify(object value) { if (value is TValue castValue) { SyncFieldValueToPropertyWithoutNotify(castValue); } } public override BindingResult OnUpdate(in BindingContext context) { if (isReleased) { return new BindingResult(BindingStatus.Pending); } try { ResetUpdate(); if (!IsSynced()) { return new BindingResult(BindingStatus.Pending); } isUpdating = true; var veField = field as VisualElement; // Value might not have changed but prefab state could have been reverted, so we need to // at least update the prefab override visual if necessary. Happens when user reverts a // field where the value is the same as the prefab registered value. Case 1276154. BindingsStyleHelpers.UpdatePrefabStateStyle(veField, boundProperty); if (EditorApplication.isPlaying && SerializedObject.GetLivePropertyFeatureGlobalState() && boundProperty.isLiveModified) BindingsStyleHelpers.UpdateLivePropertyStateStyle(veField, boundProperty); return default; } catch (NullReferenceException e) when (e.Message.Contains("SerializedObject of SerializedProperty has been Disposed.")) { //this can happen when serializedObject has been disposed of } finally { isUpdating = false; } // Something failed, we unbind here Unbind(); return new BindingResult(BindingStatus.Pending); } protected internal static string GetUndoMessage(SerializedProperty serializedProperty) { var undoMessage = $"Modified {serializedProperty.name}"; var target = serializedProperty.m_SerializedObject.targetObject; if (target != null && target.name != string.Empty) { undoMessage += $" in {serializedProperty.m_SerializedObject.targetObject.name}"; } return undoMessage; } // Read the value from the ui field and save it. protected abstract void UpdateLastFieldValue(); protected abstract bool SyncFieldValueToProperty(); protected abstract void SyncPropertyToField(TField c, SerializedProperty p); protected void SyncFieldValueToPropertyWithoutNotify(TValue value) { field.SetValueWithoutNotify(value); } }
UnityCsReference/Modules/UIElementsEditor/Bindings/SerializedObjectBindingToBaseField.cs/0
{ "file_path": "UnityCsReference/Modules/UIElementsEditor/Bindings/SerializedObjectBindingToBaseField.cs", "repo_id": "UnityCsReference", "token_count": 2694 }
508