text
stringlengths
7
35.3M
id
stringlengths
11
185
metadata
dict
__index_level_0__
int64
0
2.14k
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEditor.AnimatedValues; using UnityEditor.Build; using UnityEditor.Inspector.VisualElements.ProjectSettings; using UnityEditor.Rendering; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.UIElements; namespace UnityEditor.Inspector.GraphicsSettingsInspectors { internal class TierSettingsWindow : EditorWindow { static TierSettingsWindow s_Instance; public static void CreateWindow() { s_Instance = GetWindow<TierSettingsWindow>(); s_Instance.minSize = new Vector2(600, 300); s_Instance.titleContent = GraphicsSettingsInspectorTierSettings.Styles.tierSettings; } internal static TierSettingsWindow GetInstance() { return s_Instance; } SerializedObject m_SerializedObject; void OnEnable() { s_Instance = this; m_SerializedObject = new SerializedObject(GraphicsSettings.GetGraphicsSettings()); var graphicsSettingsInspectorTierSettings = new GraphicsSettingsInspectorTierSettings() { style = { marginTop = 5, marginBottom = 5, marginLeft = 5, marginRight = 5 }, UseAnimation = false, VerticalLayout = false }; var scrollView = new ScrollView(ScrollViewMode.Vertical); rootVisualElement.Add(scrollView); graphicsSettingsInspectorTierSettings.Initialize(m_SerializedObject); scrollView.contentContainer.Add(graphicsSettingsInspectorTierSettings); RenderPipelineManager.activeRenderPipelineAssetChanged += RenderPipelineAssetChanged; } void RenderPipelineAssetChanged(RenderPipelineAsset previous, RenderPipelineAsset next) { if (next != null) Close(); } void OnDisable() { RenderPipelineManager.activeRenderPipelineAssetChanged -= RenderPipelineAssetChanged; rootVisualElement.Clear(); if (s_Instance == this) s_Instance = null; } } internal class GraphicsSettingsInspectorTierSettings : GraphicsSettingsElement { [Serializable] public new class UxmlSerializedData : VisualElement.UxmlSerializedData { public override object CreateInstance() => new GraphicsSettingsInspectorTierSettings(); } internal class Styles { public static readonly GUIContent[] shaderQualityName = { EditorGUIUtility.TrTextContent("Low"), EditorGUIUtility.TrTextContent("Medium"), EditorGUIUtility.TrTextContent("High") }; public static readonly int[] shaderQualityValue = { (int)ShaderQuality.Low, (int)ShaderQuality.Medium, (int)ShaderQuality.High }; public static readonly GUIContent[] renderingPathName = { EditorGUIUtility.TrTextContent("Forward"), EditorGUIUtility.TrTextContent("Deferred"), EditorGUIUtility.TrTextContent("Legacy Vertex Lit") }; public static readonly int[] renderingPathValue = { (int)RenderingPath.Forward, (int)RenderingPath.DeferredShading, (int)RenderingPath.VertexLit }; public static readonly GUIContent[] hdrModeName = { EditorGUIUtility.TrTextContent("FP16"), EditorGUIUtility.TrTextContent("R11G11B10") }; public static readonly int[] hdrModeValue = { (int)CameraHDRMode.FP16, (int)CameraHDRMode.R11G11B10 }; public static readonly GUIContent[] realtimeGICPUUsageName = { EditorGUIUtility.TrTextContent("Low"), EditorGUIUtility.TrTextContent("Medium"), EditorGUIUtility.TrTextContent("High"), EditorGUIUtility.TrTextContent("Unlimited") }; public static readonly int[] realtimeGICPUUsageValue = { (int)RealtimeGICPUUsage.Low, (int)RealtimeGICPUUsage.Medium, (int)RealtimeGICPUUsage.High, (int)RealtimeGICPUUsage.Unlimited }; public static readonly GUIContent showEditorWindow = EditorGUIUtility.TrTextContent("Open Editor..."); public static readonly GUIContent closeEditorWindow = EditorGUIUtility.TrTextContent("Close Editor"); public static readonly GUIContent tierSettings = EditorGUIUtility.TrTextContent("Tier Settings"); public static readonly GUIContent[] tierName = { EditorGUIUtility.TrTextContent("Low (Tier 1)"), EditorGUIUtility.TrTextContent("Medium (Tier 2)"), EditorGUIUtility.TrTextContent("High (Tier 3)") }; public static readonly GUIContent empty = EditorGUIUtility.TextContent(""); public static readonly GUIContent autoSettingsLabel = EditorGUIUtility.TrTextContent("Use Defaults"); public static readonly GUIContent standardShaderSettings = EditorGUIUtility.TrTextContent("Standard Shader"); public static readonly GUIContent renderingSettings = EditorGUIUtility.TrTextContent("Rendering"); public static readonly GUIContent standardShaderQuality = EditorGUIUtility.TrTextContent("Standard Shader Quality"); public static readonly GUIContent reflectionProbeBoxProjection = EditorGUIUtility.TrTextContent("Reflection Probes Box Projection", "Enable projection for reflection UV mappings on Reflection Probes."); public static readonly GUIContent reflectionProbeBlending = EditorGUIUtility.TrTextContent("Reflection Probes Blending", "Gradually fade out one probe's cubemap while fading in the other's as the reflective object passes from one zone to the other."); public static readonly GUIContent detailNormalMap = EditorGUIUtility.TrTextContent("Detail Normal Map", "Enable Detail (secondary) Normal Map sampling for up-close viewing, if assigned."); public static readonly GUIContent cascadedShadowMaps = EditorGUIUtility.TrTextContent("Cascaded Shadows"); public static readonly GUIContent prefer32BitShadowMaps = EditorGUIUtility.TrTextContent("Prefer 32-bit shadow maps", "Enable 32-bit float shadow map when you are targeting PS4 or platforms using DX11 or DX12."); public static readonly GUIContent semitransparentShadows = EditorGUIUtility.TrTextContent("Enable Semitransparent Shadows"); public static readonly GUIContent enableLPPV = EditorGUIUtility.TrTextContent("Enable Light Probe Proxy Volume", "Enable rendering a 3D grid of interpolated Light Probes inside a Bounding Volume."); public static readonly GUIContent renderingPath = EditorGUIUtility.TrTextContent("Rendering Path", "Choose how Unity should render graphics. Different rendering paths affect the performance of your game, and how lighting and shading are calculated."); public static readonly GUIContent useHDR = EditorGUIUtility.TrTextContent("Use HDR", "Enable High Dynamic Range rendering for this tier."); public static readonly GUIContent hdrMode = EditorGUIUtility.TrTextContent("HDR Mode", "Color render texture format for the HDR buffer to use when HDR is enabled."); public static readonly GUIContent realtimeGICPUUsage = EditorGUIUtility.TrTextContent("Realtime Global Illumination CPU Usage", "How many CPU worker threads to create for Realtime Global Illumination lighting calculations in the Player. Increasing this makes the system react faster to changes in lighting at a cost of using more CPU time. The higher the CPU Usage value, the more worker threads are created for solving Realtime GI."); } public override bool BuiltinOnly => true; public bool UseAnimation { get; set; } = true; public bool VerticalLayout { get; set; } = true; // this is category animation is blatantly copied from PlayerSettingsEditor.cs bool m_ShowTierSettingsUI = true; // show by default, as otherwise users are confused AnimBool m_TierSettingsAnimator; protected override void Initialize() { var container = new IMGUIContainer(Draw); Add(container); if (UseAnimation) { m_TierSettingsAnimator = new AnimBool(m_ShowTierSettingsUI, container.MarkDirtyRepaint); } } void Draw() { using var settingsScope = new LabelWidthScope(); using var wideScreenScope = new WideScreenScope(this); if (m_TierSettingsAnimator == null) OnInspectorGUI(); else TierSettingsGUI(); } void HandleEditorWindowButton() { var window = TierSettingsWindow.GetInstance(); var text = window == null ? Styles.showEditorWindow : Styles.closeEditorWindow; if (!GUILayout.Button(text, EditorStyles.miniButton, GUILayout.Width(110))) return; if (window) { window.Close(); } else { TierSettingsWindow.CreateWindow(); TierSettingsWindow.GetInstance().Show(); } } void TierSettingsGUI() { var enabled = GUI.enabled; GUI.enabled = true; // we don't want to disable the expand behavior EditorGUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.Height(20)); EditorGUILayout.BeginHorizontal(); var r = GUILayoutUtility.GetRect(20, 21); r.x += 3; r.width += 6; m_ShowTierSettingsUI = EditorGUI.FoldoutTitlebar(r, Styles.tierSettings, m_ShowTierSettingsUI, true, EditorStyles.inspectorTitlebarFlat, EditorStyles.inspectorTitlebarText); HandleEditorWindowButton(); EditorGUILayout.EndHorizontal(); m_TierSettingsAnimator.target = m_ShowTierSettingsUI; GUI.enabled = enabled; if (EditorGUILayout.BeginFadeGroup(m_TierSettingsAnimator.faded) && TierSettingsWindow.GetInstance() == null) OnInspectorGUI(); EditorGUILayout.EndFadeGroup(); EditorGUILayout.EndVertical(); } void OnInspectorGUI() { using var highlightScope = new EditorGUI.LabelHighlightScope(m_SettingsWindow.GetSearchText(), HighlightSelectionColor, HighlightColor); var validPlatforms = BuildPlatforms.instance.GetValidPlatforms().ToArray(); var platform = validPlatforms[EditorGUILayout.BeginPlatformGrouping(validPlatforms, null, EditorStyles.frameBox)]; if (VerticalLayout) OnGuiVertical(platform); else OnGuiHorizontal(platform); EditorGUILayout.EndPlatformGrouping(); } void OnFieldLabelsGUI(bool vertical) { if (!vertical) EditorGUILayout.LabelField(Styles.standardShaderSettings, EditorStyles.boldLabel); EditorGUILayout.LabelField(Styles.standardShaderQuality); EditorGUILayout.LabelField(Styles.reflectionProbeBoxProjection); EditorGUILayout.LabelField(Styles.reflectionProbeBlending); EditorGUILayout.LabelField(Styles.detailNormalMap); EditorGUILayout.LabelField(Styles.semitransparentShadows); if (SupportedRenderingFeatures.active.lightProbeProxyVolumes) EditorGUILayout.LabelField(Styles.enableLPPV); if (!vertical) { EditorGUILayout.LabelField(Styles.empty, EditorStyles.boldLabel); EditorGUILayout.LabelField(Styles.renderingSettings, EditorStyles.boldLabel); } EditorGUILayout.LabelField(Styles.cascadedShadowMaps); EditorGUILayout.LabelField(Styles.prefer32BitShadowMaps); EditorGUILayout.LabelField(Styles.useHDR); EditorGUILayout.LabelField(Styles.hdrMode); EditorGUILayout.LabelField(Styles.renderingPath); if (SupportedRenderingFeatures.IsLightmapBakeTypeSupported(LightmapBakeType.Realtime)) EditorGUILayout.LabelField(Styles.realtimeGICPUUsage); } // custom enum handling ShaderQuality ShaderQualityPopup(ShaderQuality sq) => (ShaderQuality)EditorGUILayout.IntPopup((int)sq, Styles.shaderQualityName, Styles.shaderQualityValue); RenderingPath RenderingPathPopup(RenderingPath rp) => (RenderingPath)EditorGUILayout.IntPopup((int)rp, Styles.renderingPathName, Styles.renderingPathValue); CameraHDRMode HDRModePopup(CameraHDRMode mode) => (CameraHDRMode)EditorGUILayout.IntPopup((int)mode, Styles.hdrModeName, Styles.hdrModeValue); RealtimeGICPUUsage RealtimeGICPUUsagePopup(RealtimeGICPUUsage usage) => (RealtimeGICPUUsage)EditorGUILayout.IntPopup((int)usage, Styles.realtimeGICPUUsageName, Styles.realtimeGICPUUsageValue); void OnTierGUI(BuildPlatform platform, GraphicsTier tier, bool vertical) { var ts = EditorGraphicsSettings.GetTierSettings(platform.namedBuildTarget, tier); EditorGUI.BeginChangeCheck(); if (!vertical) EditorGUILayout.LabelField(Styles.empty, EditorStyles.boldLabel); ts.standardShaderQuality = ShaderQualityPopup(ts.standardShaderQuality); ts.reflectionProbeBoxProjection = EditorGUILayout.Toggle(ts.reflectionProbeBoxProjection); ts.reflectionProbeBlending = EditorGUILayout.Toggle(ts.reflectionProbeBlending); ts.detailNormalMap = EditorGUILayout.Toggle(ts.detailNormalMap); ts.semitransparentShadows = EditorGUILayout.Toggle(ts.semitransparentShadows); if (SupportedRenderingFeatures.active.lightProbeProxyVolumes) ts.enableLPPV = EditorGUILayout.Toggle(ts.enableLPPV); if (!vertical) { EditorGUILayout.LabelField(Styles.empty, EditorStyles.boldLabel); EditorGUILayout.LabelField(Styles.empty, EditorStyles.boldLabel); } ts.cascadedShadowMaps = EditorGUILayout.Toggle(ts.cascadedShadowMaps); ts.prefer32BitShadowMaps = EditorGUILayout.Toggle(ts.prefer32BitShadowMaps); ts.hdr = EditorGUILayout.Toggle(ts.hdr); ts.hdrMode = HDRModePopup(ts.hdrMode); ts.renderingPath = RenderingPathPopup(ts.renderingPath); if (!GraphicsSettings.isScriptableRenderPipelineEnabled) if (SupportedRenderingFeatures.IsLightmapBakeTypeSupported(LightmapBakeType.Realtime)) ts.realtimeGICPUUsage = RealtimeGICPUUsagePopup(ts.realtimeGICPUUsage); if (EditorGUI.EndChangeCheck()) { // TODO: it should be doable in c# now as we "expose" GraphicsSettings anyway EditorGraphicsSettings.RegisterUndo(); EditorGraphicsSettings.SetTierSettings(platform.namedBuildTarget, tier, ts); } } void OnGuiHorizontal(BuildPlatform platform) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginVertical(); EditorGUIUtility.labelWidth = 140; EditorGUILayout.LabelField(Styles.empty, EditorStyles.boldLabel); OnFieldLabelsGUI(false); EditorGUILayout.LabelField(Styles.empty, EditorStyles.boldLabel); EditorGUILayout.LabelField(Styles.autoSettingsLabel, EditorStyles.boldLabel); EditorGUILayout.EndVertical(); EditorGUIUtility.labelWidth = 50; foreach (GraphicsTier tier in Enum.GetValues(typeof(GraphicsTier))) { bool autoSettings = EditorGraphicsSettings.AreTierSettingsAutomatic(platform.namedBuildTarget.ToBuildTargetGroup(), tier); EditorGUILayout.BeginVertical(); EditorGUILayout.LabelField(Styles.tierName[(int)tier], EditorStyles.boldLabel); using (new EditorGUI.DisabledScope(autoSettings)) OnTierGUI(platform, tier, false); EditorGUILayout.LabelField(Styles.empty, EditorStyles.boldLabel); EditorGUI.BeginChangeCheck(); autoSettings = EditorGUILayout.Toggle(autoSettings); if (EditorGUI.EndChangeCheck()) { EditorGraphicsSettings.RegisterUndo(); EditorGraphicsSettings.MakeTierSettingsAutomatic(platform.namedBuildTarget.ToBuildTargetGroup(), tier, autoSettings); EditorGraphicsSettings.OnUpdateTierSettings(platform.namedBuildTarget.ToBuildTargetGroup(), true); } EditorGUILayout.EndVertical(); } EditorGUIUtility.labelWidth = 0; EditorGUILayout.EndHorizontal(); } void OnGuiVertical(BuildPlatform platform) { EditorGUILayout.BeginVertical(); foreach (GraphicsTier tier in Enum.GetValues(typeof(GraphicsTier))) { var autoSettings = EditorGraphicsSettings.AreTierSettingsAutomatic(platform.namedBuildTarget.ToBuildTargetGroup(), tier); EditorGUI.BeginChangeCheck(); { GUILayout.BeginHorizontal(); EditorGUIUtility.labelWidth = 80; EditorGUILayout.LabelField(Styles.tierName[(int)tier], EditorStyles.boldLabel); GUILayout.FlexibleSpace(); EditorGUIUtility.labelWidth = 80; autoSettings = EditorGUILayout.Toggle(Styles.autoSettingsLabel, autoSettings); GUILayout.EndHorizontal(); } if (EditorGUI.EndChangeCheck()) { EditorGraphicsSettings.RegisterUndo(); EditorGraphicsSettings.MakeTierSettingsAutomatic(platform.namedBuildTarget.ToBuildTargetGroup(), tier, autoSettings); EditorGraphicsSettings.OnUpdateTierSettings(platform.namedBuildTarget.ToBuildTargetGroup(), true); } using (new EditorGUI.DisabledScope(autoSettings)) { EditorGUI.indentLevel++; EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginVertical(); EditorGUIUtility.labelWidth = 140; OnFieldLabelsGUI(true); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(); EditorGUIUtility.labelWidth = 50; OnTierGUI(platform, tier, true); EditorGUILayout.EndVertical(); GUILayout.EndHorizontal(); EditorGUI.indentLevel--; } } GUILayout.EndVertical(); EditorGUIUtility.labelWidth = 0; } } }
UnityCsReference/Editor/Mono/Inspector/GraphicsSettingsInspectors/GraphicsSettingsInspectorTierSettings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/GraphicsSettingsInspectors/GraphicsSettingsInspectorTierSettings.cs", "repo_id": "UnityCsReference", "token_count": 8174 }
309
// 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.AnimatedValues; using UnityEditor.EditorTools; using UnityEditor.IMGUI.Controls; using UnityEngine; namespace UnityEditor { [CustomEditor(typeof(LineRenderer))] [CanEditMultipleObjects] internal class LineRendererInspector : RendererEditorBase { class Styles { public static readonly GUIContent alignment = EditorGUIUtility.TrTextContent("Alignment", "Lines can rotate to face their transform component or the camera. When using Local mode, lines face the XY plane of the Transform."); public static readonly GUIContent colorGradient = EditorGUIUtility.TrTextContent("Color", "The gradient describing the color along the line."); public static readonly string disabledEditMessage = L10n.Tr("Editing is only available when editing a single LineRenderer in a scene."); public static readonly GUIContent inputMode = EditorGUIUtility.TrTextContent("Input", "Use mouse position or physics raycast to determine where to create points."); public static readonly GUIContent layerMask = EditorGUIUtility.TrTextContent("Layer Mask", "The layer mask to use when performing raycasts."); public static readonly GUIContent normalOffset = EditorGUIUtility.TrTextContent("Offset", "The offset applied to created points either from the scene camera or raycast normal, when using physics."); public static readonly GUIContent numCapVertices = EditorGUIUtility.TrTextContent("End Cap Vertices", "How many vertices to add at each end."); public static readonly GUIContent numCornerVertices = EditorGUIUtility.TrTextContent("Corner Vertices", "How many vertices to add for each corner."); public static readonly GUIContent pointSeparation = EditorGUIUtility.TrTextContent("Min Vertex Distance", "When dragging the mouse, a new point will be created after the distance has been exceeded."); public static readonly GUIContent positions = EditorGUIUtility.TrTextContent("Positions"); public static readonly GUIContent propertyMenuContent = EditorGUIUtility.TrTextContent("Delete Selected Array Elements"); public static readonly GUIContent showWireframe = EditorGUIUtility.TrTextContent("Show Wireframe", "Show the wireframe visualizing the line."); public static readonly GUIContent simplify = EditorGUIUtility.TrTextContent("Simplify", "Generates a simplified version of the original line by removing points that fall within the specified tolerance."); public static readonly GUIContent simplifyPreview = EditorGUIUtility.TrTextContent("Simplify Preview", "Show a preview of the simplified version of the line."); public static readonly GUIContent subdivide = EditorGUIUtility.TrTextContent("Subdivide Selected" , "Inserts a new point in between selected adjacent points."); public static readonly GUIContent textureMode = EditorGUIUtility.TrTextContent("Texture Mode", "Should the U coordinate be stretched or tiled?"); public static readonly GUIContent textureScale = EditorGUIUtility.TrTextContent("Texture Scale", "Scale the texture along the UV coordinates using this multiplier."); public static readonly GUIContent tolerance = EditorGUIUtility.TrTextContent("Tolerance", "Used to evaluate which points should be removed from the line. A higher value results in a simpler line (fewer points). A value of 0 results in the exact same line with little to no reduction."); public static readonly GUIContent shadowBias = EditorGUIUtility.TrTextContent("Shadow Bias", "Apply a shadow bias to prevent self-shadowing artifacts. The specified value is the proportion of the line width at each segment."); public static readonly GUIContent generateLightingData = EditorGUIUtility.TrTextContent("Generate Lighting Data", "Toggle generation of normal and tangent data, for use in lit shaders."); public static readonly GUIContent sceneTools = EditorGUIUtility.TrTextContent("Scene Tools"); public static readonly GUIContent applyActiveColorSpace = EditorGUIUtility.TrTextContent("Apply Active Color Space", "When using Linear Rendering, colors will be converted appropriately before being passed to the GPU."); } abstract class LineRendererTool : EditorTool { protected LineRendererEditor pointEditor { get { if (m_PointEditor == null) m_PointEditor = new LineRendererEditor(target as LineRenderer); return m_PointEditor; } } public override void OnActivated() { pointEditor.Deselect(); } public override void OnWillBeDeactivated() { pointEditor.Deselect(); } public void RemoveInvalidSelections() { pointEditor.RemoveInvalidSelections(); } public List<int> pointSelection { set => pointEditor.m_Selection = value; get => pointEditor.m_Selection; } public Bounds selectedPositionsBounds { get => pointEditor.selectedPositionsBounds; } public override bool IsAvailable() { return !targets.Skip(1).Any(); // TODO - multi-edit disabled for now. Need to make LineRendererEditor support multiple targets, and fix m_IsGameObjectEditable } public abstract void DrawToolbar(SerializedProperty positions); public virtual void OnSceneGUIDelegate(SerializedProperty positions, LineRendererPositionsView positionsView) { } private LineRendererEditor m_PointEditor; } [EditorTool("Edit Points", typeof(LineRenderer))] class LineRendererEditPointsTool : LineRendererTool { public override GUIContent toolbarIcon { get { return EditorGUIUtility.TrIconContent("EditCollider", "Edit LineRenderer Points in the Scene View."); } } public override void OnToolGUI(EditorWindow window) { pointEditor.EditSceneGUI(window); } public override void DrawToolbar(SerializedProperty positions) { EditorGUI.BeginChangeCheck(); LineRendererEditor.showWireframe = GUILayout.Toggle(LineRendererEditor.showWireframe, Styles.showWireframe); if (EditorGUI.EndChangeCheck()) { SceneView.RepaintAll(); } bool adjacentPointsSelected = HasAdjacentPointsSelected(); using (new EditorGUI.DisabledGroupScope(!adjacentPointsSelected)) { GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(Styles.subdivide, GUILayout.Width(150))) { SubdivideSelected(positions); } GUILayout.EndHorizontal(); } } public override void OnSceneGUIDelegate(SerializedProperty positions, LineRendererPositionsView positionsView) { // We need to wait for m_Positions to be updated next frame or we risk calling SetSelection with invalid indexes. if (pointEditor.Count == positions.arraySize) { if (positions.arraySize != positionsView.GetRows().Count) positionsView.Reload(); positionsView.SetSelection(pointSelection, TreeViewSelectionOptions.RevealAndFrame); } } private bool HasAdjacentPointsSelected() { var selection = pointSelection; selection.Sort(); if (selection.Count < 2) return false; for (int i = 0; i < selection.Count - 1; ++i) { if (selection[i + 1] == selection[i] + 1) return true; } return false; } private void SubdivideSelected(SerializedProperty positions) { var selection = pointSelection; if (selection.Count < 2) return; selection.Sort(); var insertedIndexes = new List<int>(); int numInserted = 0; // As we insert new nodes, the selected indexes will become offset so we need to keep track of this. for (int i = 0; i < selection.Count - 1; ++i) { if (selection[i + 1] == selection[i] + 1) { int fromIndex = selection[i] + numInserted; int toIndex = selection[i + 1] + numInserted; var from = positions.GetArrayElementAtIndex(fromIndex).vector3Value; var to = positions.GetArrayElementAtIndex(toIndex).vector3Value; var midPoint = Vector3.Lerp(from, to, 0.5f); positions.InsertArrayElementAtIndex(toIndex); positions.GetArrayElementAtIndex(toIndex).vector3Value = midPoint; insertedIndexes.Add(toIndex); numInserted++; } } pointSelection = insertedIndexes; } } [EditorTool("Add Points", typeof(LineRenderer))] class LineRendererAddPointsTool : LineRendererTool { public override GUIContent toolbarIcon { get { return EditorGUIUtility.TrIconContent("Toolbar Plus", "Create LineRenderer Points in the Scene View."); } } public override void OnToolGUI(EditorWindow window) { pointEditor.CreateSceneGUI(); } public override void DrawToolbar(SerializedProperty positions) { LineRendererEditor.inputMode = (LineRendererEditor.InputMode)EditorGUILayout.EnumPopup(Styles.inputMode, LineRendererEditor.inputMode); if (LineRendererEditor.inputMode == LineRendererEditor.InputMode.PhysicsRaycast) { LineRendererEditor.raycastMask = EditorGUILayout.LayerMaskField(LineRendererEditor.raycastMask, Styles.layerMask); } LineRendererEditor.createPointSeparation = EditorGUILayout.FloatField(Styles.pointSeparation, LineRendererEditor.createPointSeparation); LineRendererEditor.creationOffset = EditorGUILayout.FloatField(Styles.normalOffset, LineRendererEditor.creationOffset); } } public static float simplifyTolerance { get { return EditorPrefs.GetFloat("LineRendererInspectorSimplifyTolerance", 1.0f); } set { EditorPrefs.SetFloat("LineRendererInspectorSimplifyTolerance", value < 0 ? 0 : value); } } public static bool showSimplifyPreview { get { return EditorPrefs.GetBool("LineRendererEditorShowSimplifyPreview", false); } set { EditorPrefs.SetBool("LineRendererEditorShowSimplifyPreview", value); } } private Vector3[] m_PreviewPoints; private LineRendererCurveEditor m_CurveEditor = new LineRendererCurveEditor(); private SerializedProperty m_Alignment; private SerializedProperty m_ColorGradient; private SerializedProperty m_ShadowBias; private SerializedProperty m_GenerateLightingData; private SerializedProperty m_Loop; private SerializedProperty m_ApplyActiveColorSpace; private SerializedProperty m_NumCapVertices; private SerializedProperty m_NumCornerVertices; private SerializedProperty m_Positions; private SerializedProperty m_PositionsSize; private SerializedProperty m_TextureMode; private SerializedProperty m_TextureScale; private SerializedProperty m_UseWorldSpace; private SerializedProperty m_MaskInteraction; private LineRendererPositionsView m_PositionsView; AnimBool m_ShowPositionsAnimation; bool m_IsMultiEditing; bool m_IsGameObjectEditable; public static readonly float kPositionsViewMinHeight = 30; private LineRendererTool activeSceneViewTool { get { return EditorToolManager.activeTool as LineRendererTool; } } private bool canEditInScene { get { return !m_IsMultiEditing && m_IsGameObjectEditable; } } public override void OnEnable() { base.OnEnable(); var lineRenderer = target as LineRenderer; SceneView.duringSceneGui += OnSceneGUIDelegate; Undo.undoRedoEvent += UndoRedoPerformed; m_CurveEditor.OnEnable(serializedObject); m_Loop = serializedObject.FindProperty("m_Loop"); m_ApplyActiveColorSpace = serializedObject.FindProperty("m_ApplyActiveColorSpace"); m_Positions = serializedObject.FindProperty("m_Positions"); m_PositionsSize = serializedObject.FindProperty("m_Positions.Array.size"); m_ColorGradient = serializedObject.FindProperty("m_Parameters.colorGradient"); m_NumCornerVertices = serializedObject.FindProperty("m_Parameters.numCornerVertices"); m_NumCapVertices = serializedObject.FindProperty("m_Parameters.numCapVertices"); m_Alignment = serializedObject.FindProperty("m_Parameters.alignment"); m_TextureMode = serializedObject.FindProperty("m_Parameters.textureMode"); m_TextureScale = serializedObject.FindProperty("m_Parameters.textureScale"); m_GenerateLightingData = serializedObject.FindProperty("m_Parameters.generateLightingData"); m_ShadowBias = serializedObject.FindProperty("m_Parameters.shadowBias"); m_UseWorldSpace = serializedObject.FindProperty("m_UseWorldSpace"); m_MaskInteraction = serializedObject.FindProperty("m_MaskInteraction"); m_PositionsView = new LineRendererPositionsView(m_Positions); m_PositionsView.selectionChangedCallback += PositionsViewSelectionChanged; if (targets.Length == 1) m_PositionsView.lineRenderer = lineRenderer; m_ShowPositionsAnimation = new AnimBool(false, Repaint) { value = m_Positions.isExpanded }; EditorApplication.contextualPropertyMenu += OnPropertyContextMenu; // We cannot access isEditingMultipleObjects when drawing the SceneView so we need to cache it here for later use. m_IsMultiEditing = serializedObject.isEditingMultipleObjects; m_IsGameObjectEditable = (lineRenderer.gameObject.hideFlags & HideFlags.NotEditable) == 0; } void OnPropertyContextMenu(GenericMenu menu, SerializedProperty property) { if (m_PositionsView == null) return; if (property.propertyPath.Contains("m_Positions") && m_PositionsView.GetSelection().Count > 1) { menu.AddItem(Styles.propertyMenuContent, false, () => { var selection = m_PositionsView.GetSelection().ToList(); var query = selection.OrderByDescending(c => c); foreach (var index in query) { m_Positions.DeleteArrayElementAtIndex(index); } m_Positions.serializedObject.ApplyModifiedProperties(); m_PositionsView.SetSelection(new int[0]); m_PositionsView.Reload(); ResetSimplifyPreview(); }); } } void PositionsViewSelectionChanged(List<int> selected) { var sceneTool = activeSceneViewTool; if (sceneTool != null) sceneTool.pointSelection = selected; SceneView.RepaintAll(); } public void OnDisable() { m_CurveEditor.OnDisable(); Undo.undoRedoEvent -= UndoRedoPerformed; SceneView.duringSceneGui -= OnSceneGUIDelegate; EditorApplication.contextualPropertyMenu -= OnPropertyContextMenu; } private void UndoRedoPerformed(in UndoRedoInfo info) { m_PositionsView.Reload(); var sceneTool = activeSceneViewTool; if (sceneTool != null) { sceneTool.RemoveInvalidSelections(); m_PositionsView.SetSelection(sceneTool.pointSelection); } ResetSimplifyPreview(); } private void DrawToolbar() { if (!canEditInScene) { EditorGUILayout.HelpBox(Styles.disabledEditMessage, MessageType.Info); } EditorGUILayout.BeginVertical("GroupBox"); EditorGUI.BeginDisabled(!canEditInScene); EditorGUILayout.EditorToolbarForTarget(Styles.sceneTools, this); // Editing mode toolbar var sceneTools = activeSceneViewTool; if (sceneTools != null) { sceneTools.DrawToolbar(m_Positions); } else { EditorGUI.BeginChangeCheck(); showSimplifyPreview = EditorGUILayout.Toggle(Styles.simplifyPreview, showSimplifyPreview); EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(Styles.tolerance); simplifyTolerance = Mathf.Max(0, EditorGUILayout.FloatField(simplifyTolerance, GUILayout.MaxWidth(35.0f))); if (GUILayout.Button(Styles.simplify, EditorStyles.miniButton)) { SimplifyPoints(); } if (EditorGUI.EndChangeCheck()) { ResetSimplifyPreview(); SceneView.RepaintAll(); } EditorGUILayout.EndHorizontal(); } EditorGUI.EndDisabled(); EditorGUILayout.EndVertical(); } private void SimplifyPoints() { var lineRenderer = target as LineRenderer; Undo.RecordObject(lineRenderer, "Simplify Line"); lineRenderer.Simplify(simplifyTolerance); } private void ResetSimplifyPreview() { m_PreviewPoints = null; } private void DrawSimplifyPreview() { var lineRenderer = target as LineRenderer; if (!showSimplifyPreview || !canEditInScene || !lineRenderer.enabled) return; if (m_PreviewPoints == null && lineRenderer.positionCount > 2) { m_PreviewPoints = new Vector3[lineRenderer.positionCount]; lineRenderer.GetPositions(m_PreviewPoints); var simplePoints = new List<Vector3>(); LineUtility.Simplify(m_PreviewPoints.ToList(), simplifyTolerance, simplePoints); if (lineRenderer.loop) simplePoints.Add(simplePoints[0]); m_PreviewPoints = simplePoints.ToArray(); } if (m_PreviewPoints != null) { Handles.color = Color.yellow; var oldMatrix = Handles.matrix; if (!lineRenderer.useWorldSpace) Handles.matrix = lineRenderer.transform.localToWorldMatrix; Handles.DrawAAPolyLine(10, m_PreviewPoints.Length, m_PreviewPoints); Handles.matrix = oldMatrix; } } public override void OnInspectorGUI() { serializedObject.Update(); DrawToolbar(); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(m_Loop); if (EditorGUI.EndChangeCheck()) ResetSimplifyPreview(); EditorGUILayout.PropertyField(m_ApplyActiveColorSpace, Styles.applyActiveColorSpace); m_ShowPositionsAnimation.target = m_Positions.isExpanded = EditorGUILayout.Foldout(m_Positions.isExpanded, Styles.positions, true); if (m_ShowPositionsAnimation.faded > 0) { EditorGUILayout.PropertyField(m_PositionsSize); if (m_Positions.arraySize != m_PositionsView.GetRows().Count) { m_PositionsView.Reload(); ResetSimplifyPreview(); } m_PositionsView.OnGUI(EditorGUILayout.GetControlRect(false, Mathf.Lerp(kPositionsViewMinHeight, m_PositionsView.totalHeight, m_ShowPositionsAnimation.faded))); if (serializedObject.hasModifiedProperties) ResetSimplifyPreview(); } EditorGUILayout.Space(); m_CurveEditor.CheckCurveChangedExternally(); m_CurveEditor.OnInspectorGUI(); EditorGUILayout.Space(); EditorGUILayout.PropertyField(m_ColorGradient, Styles.colorGradient); EditorGUILayout.PropertyField(m_NumCornerVertices, Styles.numCornerVertices); EditorGUILayout.PropertyField(m_NumCapVertices, Styles.numCapVertices); EditorGUILayout.PropertyField(m_Alignment, Styles.alignment); EditorGUILayout.PropertyField(m_TextureMode, Styles.textureMode); EditorGUILayout.PropertyField(m_TextureScale, Styles.textureScale); EditorGUILayout.PropertyField(m_ShadowBias, Styles.shadowBias); EditorGUILayout.PropertyField(m_GenerateLightingData, Styles.generateLightingData); EditorGUILayout.PropertyField(m_UseWorldSpace); EditorGUILayout.PropertyField(m_MaskInteraction); DrawMaterials(); LightingSettingsGUI(false); OtherSettingsGUI(true, false, true); serializedObject.ApplyModifiedProperties(); } public void OnSceneGUIDelegate(SceneView sceneView) { var sceneTool = activeSceneViewTool; if (sceneTool != null) { sceneTool.OnSceneGUIDelegate(m_Positions, m_PositionsView); ResetSimplifyPreview(); } else { DrawSimplifyPreview(); } } public bool HasFrameBounds() { var sceneTool = activeSceneViewTool; return (sceneTool != null) && (sceneTool.pointSelection.Count > 0); } public Bounds OnGetFrameBounds() { var sceneTool = activeSceneViewTool; return (sceneTool != null) ? sceneTool.selectedPositionsBounds : new Bounds(); } internal override Bounds GetWorldBoundsOfTarget(Object targetObject) { var sceneTool = activeSceneViewTool; if (sceneTool != null) return sceneTool.selectedPositionsBounds; return base.GetWorldBoundsOfTarget(targetObject); } } }
UnityCsReference/Editor/Mono/Inspector/LineRendererEditor.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/LineRendererEditor.cs", "repo_id": "UnityCsReference", "token_count": 10505 }
310
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEngine.AI; namespace UnityEditor { [CanEditMultipleObjects] [CustomEditor(typeof(NavMeshAgent))] internal class NavMeshAgentInspector : Editor { private SerializedProperty m_AgentTypeID; private SerializedProperty m_Radius; private SerializedProperty m_Height; private SerializedProperty m_WalkableMask; private SerializedProperty m_Speed; private SerializedProperty m_Acceleration; private SerializedProperty m_AngularSpeed; private SerializedProperty m_StoppingDistance; private SerializedProperty m_AutoTraverseOffMeshLink; private SerializedProperty m_AutoBraking; private SerializedProperty m_AutoRepath; private SerializedProperty m_BaseOffset; private SerializedProperty m_ObstacleAvoidanceType; private SerializedProperty m_AvoidancePriority; private static class Styles { public static readonly GUIContent AgentSteeringHeader = EditorGUIUtility.TrTextContent("Steering"); public static readonly GUIContent AgentAvoidanceHeader = EditorGUIUtility.TrTextContent("Obstacle Avoidance"); public static readonly GUIContent AgentPathFindingHeader = EditorGUIUtility.TrTextContent("Path Finding"); public static readonly GUIContent AgentType = EditorGUIUtility.TrTextContent("Agent Type", "The agent characteristics for which a NavMesh has been built."); public static readonly GUIContent BaseOffset = EditorGUIUtility.TrTextContent("Base Offset", "The relative vertical displacement of the owning GameObject."); public static readonly GUIContent Speed = EditorGUIUtility.TrTextContent("Speed", "Maximum movement speed when following a path."); public static readonly GUIContent AngularSpeed = EditorGUIUtility.TrTextContent("Angular Speed", "Maximum turning speed in (deg/s) while following a path."); public static readonly GUIContent Acceleration = EditorGUIUtility.TrTextContent("Acceleration", "The maximum acceleration of an agent as it follows a path, given in units / sec^2."); public static readonly GUIContent StoppingDistance = EditorGUIUtility.TrTextContent("Stopping Distance", "Stop within this distance from the target position."); public static readonly GUIContent AutoBraking = EditorGUIUtility.TrTextContent("Auto Braking", "The agent will avoid overshooting the destination point by slowing down in time."); public static readonly GUIContent Radius = EditorGUIUtility.TrTextContent("Radius", "The minimum distance to keep clear between the center of this agent and any other agents or obstacles nearby."); public static readonly GUIContent Height = EditorGUIUtility.TrTextContent("Height", "The height of the agent for purposes of passing under obstacles."); public static readonly GUIContent Quality = EditorGUIUtility.TrTextContent("Quality", "Higher quality avoidance reduces more the chance of agents overlapping but it is slower to compute than lower quality avoidance."); public static readonly GUIContent Priority = EditorGUIUtility.TrTextContent("Priority", "This agent will ignore all other agents for which this number is higher. A lower value implies higher importance."); public static readonly GUIContent AutoTraverseOffMeshLink = EditorGUIUtility.TrTextContent("Auto Traverse Off Mesh Link", "The agent moves across Off Mesh Links automatically."); public static readonly GUIContent AutoRepath = EditorGUIUtility.TrTextContent("Auto Repath", "The agent will attempt to acquire a new path if the existing path becomes invalid."); public static readonly GUIContent AreaMask = EditorGUIUtility.TrTextContent("Area Mask", "The agent plans a path and moves only through the selected NavMesh area types."); } void OnEnable() { m_AgentTypeID = serializedObject.FindProperty("m_AgentTypeID"); m_Radius = serializedObject.FindProperty("m_Radius"); m_Height = serializedObject.FindProperty("m_Height"); m_WalkableMask = serializedObject.FindProperty("m_WalkableMask"); m_Speed = serializedObject.FindProperty("m_Speed"); m_Acceleration = serializedObject.FindProperty("m_Acceleration"); m_AngularSpeed = serializedObject.FindProperty("m_AngularSpeed"); m_StoppingDistance = serializedObject.FindProperty("m_StoppingDistance"); m_AutoTraverseOffMeshLink = serializedObject.FindProperty("m_AutoTraverseOffMeshLink"); m_AutoBraking = serializedObject.FindProperty("m_AutoBraking"); m_AutoRepath = serializedObject.FindProperty("m_AutoRepath"); m_BaseOffset = serializedObject.FindProperty("m_BaseOffset"); m_ObstacleAvoidanceType = serializedObject.FindProperty("m_ObstacleAvoidanceType"); m_AvoidancePriority = serializedObject.FindProperty("avoidancePriority"); } public override void OnInspectorGUI() { AI.NavMeshEditorHelpers.DisplayInstallPackageButtonIfNeeded(); serializedObject.Update(); AgentTypePopupInternal(m_AgentTypeID); EditorGUILayout.PropertyField(m_BaseOffset, Styles.BaseOffset); EditorGUILayout.Space(); EditorGUILayout.LabelField(Styles.AgentSteeringHeader, EditorStyles.boldLabel); EditorGUILayout.PropertyField(m_Speed, Styles.Speed); EditorGUILayout.PropertyField(m_AngularSpeed, Styles.AngularSpeed); EditorGUILayout.PropertyField(m_Acceleration, Styles.Acceleration); EditorGUILayout.PropertyField(m_StoppingDistance, Styles.StoppingDistance); EditorGUILayout.PropertyField(m_AutoBraking, Styles.AutoBraking); EditorGUILayout.Space(); EditorGUILayout.LabelField(Styles.AgentAvoidanceHeader, EditorStyles.boldLabel); EditorGUILayout.PropertyField(m_Radius, Styles.Radius); EditorGUILayout.PropertyField(m_Height, Styles.Height); EditorGUILayout.PropertyField(m_ObstacleAvoidanceType, Styles.Quality); EditorGUILayout.PropertyField(m_AvoidancePriority, Styles.Priority); EditorGUILayout.Space(); EditorGUILayout.LabelField(Styles.AgentPathFindingHeader, EditorStyles.boldLabel); EditorGUILayout.PropertyField(m_AutoTraverseOffMeshLink, Styles.AutoTraverseOffMeshLink); EditorGUILayout.PropertyField(m_AutoRepath, Styles.AutoRepath); //Initially needed data var areaNames = NavMesh.GetAreaNames(); var currentMask = m_WalkableMask.longValue; var compressedMask = 0; if (currentMask == 0xffffffff) { compressedMask = ~0; } else { //Need to find the index as the list of names will compress out empty areas for (var i = 0; i < areaNames.Length; i++) { var areaIndex = NavMesh.GetAreaFromName(areaNames[i]); if (((1 << areaIndex) & currentMask) != 0) compressedMask = compressedMask | (1 << i); } } var position = EditorGUILayout.GetControlRect(); EditorGUI.BeginProperty(position, GUIContent.none, m_WalkableMask); EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = m_WalkableMask.hasMultipleDifferentValues; var areaMask = EditorGUI.MaskField(position, Styles.AreaMask, compressedMask, areaNames, EditorStyles.layerMaskField); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { if (areaMask == ~0) { m_WalkableMask.longValue = 0xffffffff; } else { uint newMask = 0; for (var i = 0; i < areaNames.Length; i++) { //If the bit has been set in the compacted mask if (((areaMask >> i) & 1) != 0) { //Find out the 'real' layer from the name, then set it in the new mask newMask = newMask | (uint)(1 << NavMesh.GetAreaFromName(areaNames[i])); } } m_WalkableMask.longValue = newMask; } } EditorGUI.EndProperty(); serializedObject.ApplyModifiedProperties(); } private static void AgentTypePopupInternal(SerializedProperty agentTypeID) { var index = -1; var count = NavMesh.GetSettingsCount(); var agentTypeNames = new string[count + 2]; for (var i = 0; i < count; i++) { var id = NavMesh.GetSettingsByIndex(i).agentTypeID; var name = NavMesh.GetSettingsNameFromID(id); agentTypeNames[i] = name; if (id == agentTypeID.intValue) index = i; } agentTypeNames[count] = ""; agentTypeNames[count + 1] = "Open Agent Settings..."; bool validAgentType = index != -1; if (!validAgentType) { EditorGUILayout.HelpBox("Agent Type invalid.", MessageType.Warning); } var rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight); EditorGUI.BeginProperty(rect, GUIContent.none, agentTypeID); EditorGUI.BeginChangeCheck(); index = EditorGUI.Popup(rect, Styles.AgentType, index, agentTypeNames); if (EditorGUI.EndChangeCheck()) { if (index >= 0 && index < count) { var id = NavMesh.GetSettingsByIndex(index).agentTypeID; agentTypeID.intValue = id; } else if (index == count + 1) { UnityEditor.AI.NavMeshEditorHelpers.OpenAgentSettings(-1); } } EditorGUI.EndProperty(); } } }
UnityCsReference/Editor/Mono/Inspector/NavMeshAgentInspector.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/NavMeshAgentInspector.cs", "repo_id": "UnityCsReference", "token_count": 4364 }
311
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Diagnostics; using UnityEditor.SceneManagement; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Experimental.Rendering; using UnityEngine.SceneManagement; using Debug = UnityEngine.Debug; using Object = UnityEngine.Object; namespace UnityEditor { internal class PreviewScene : IDisposable { private readonly Scene m_Scene; private readonly List<GameObject> m_GameObjects = new List<GameObject>(); private readonly Camera m_Camera; public PreviewScene(string sceneName) { m_Scene = EditorSceneManager.NewPreviewScene(); if (!m_Scene.IsValid()) throw new InvalidOperationException("Preview scene could not be created"); m_Scene.name = sceneName; var camGO = EditorUtility.CreateGameObjectWithHideFlags("Preview Scene Camera", HideFlags.HideAndDontSave, typeof(Camera)); AddGameObject(camGO); m_Camera = camGO.GetComponent<Camera>(); camera.cameraType = CameraType.Preview; camera.enabled = false; camera.clearFlags = CameraClearFlags.Depth; camera.fieldOfView = 15; camera.farClipPlane = 10.0f; camera.nearClipPlane = 2.0f; // Explicitly use forward rendering for all previews // (deferred fails when generating some static previews at editor launch; and we never want // vertex lit previews if that is chosen in the player settings) camera.renderingPath = RenderingPath.Forward; camera.useOcclusionCulling = false; camera.scene = m_Scene; } public Camera camera { get { return m_Camera; } } public Scene scene { get { return m_Scene; } } public void AddGameObject(GameObject go) { if (m_GameObjects.Contains(go)) return; SceneManager.MoveGameObjectToScene(go, m_Scene); m_GameObjects.Add(go); } public void AddManagedGO(GameObject go) { SceneManager.MoveGameObjectToScene(go, m_Scene); } public void Dispose() { EditorSceneManager.ClosePreviewScene(m_Scene); foreach (var go in m_GameObjects) Object.DestroyImmediate(go); m_GameObjects.Clear(); } } public class PreviewRenderUtility { private readonly PreviewScene m_PreviewScene; private RenderTexture m_RenderTexture; private Rect m_TargetRect; private SavedRenderTargetState m_SavedState; private bool m_PixelPerfect; private Material m_InvisibleMaterial; private bool m_previewOpened; private string m_Type; // This is used to track colour space changes // and try to keep colour values in sync private ColorSpace colorSpace; private Color defaultBackgroundColor; public PreviewRenderUtility(bool renderFullScene) : this() {} public PreviewRenderUtility(bool renderFullScene, bool pixelPerfect) : this() { m_PixelPerfect = pixelPerfect; } public PreviewRenderUtility() { m_PreviewScene = new PreviewScene("Preview Scene"); var l0 = CreateLight(); previewScene.AddGameObject(l0); Light0 = l0.GetComponent<Light>(); var l1 = CreateLight(); previewScene.AddGameObject(l1); Light1 = l1.GetComponent<Light>(); Light0.color = SceneView.kSceneViewFrontLight; Light1.transform.rotation = Quaternion.Euler(340, 218, 177); Light1.color = new Color(.4f, .4f, .45f, 0f) * .7f; m_PixelPerfect = false; // Set a default background color defaultBackgroundColor = new Color(49.0f / 255.0f, 49.0f / 255.0f, 49.0f / 255.0f, 1.0f); colorSpace = QualitySettings.activeColorSpace; camera.backgroundColor = colorSpace == ColorSpace.Gamma ? defaultBackgroundColor : defaultBackgroundColor.linear; if (Unsupported.IsDeveloperMode()) { var stackTrace = new StackTrace(); for (int i = 0; i < stackTrace.FrameCount; i++) { var frame = stackTrace.GetFrame(i); var type = frame.GetMethod().DeclaringType; if (type != null && (type.IsSubclassOf(typeof(Editor)) || type.IsSubclassOf(typeof(EditorWindow)))) { m_Type = type.Name; break; } } } m_previewOpened = false; } ~PreviewRenderUtility() { if (m_Type != null) { Debug.LogErrorFormat("{0} created a PreviewRenderUtility but didn't call its Cleanup() during OnDisable (or its execution was interrupted). This is leaking the Preview scene in the Editor and should be fixed.", m_Type); } else { Debug.LogError("A PreviewRenderUtility was not clean up properly before assembly reloading which lead to leaking this scene in the Editor. " + "This can be caused by not calling Cleanup() (or its execution being interrupted) during the OnDisable of an Editor or an EditorWindow."); } } internal static void SetEnabledRecursive(GameObject go, bool enabled) { foreach (Renderer renderer in go.GetComponentsInChildren<Renderer>()) renderer.enabled = enabled; } [Obsolete("Use the property camera instead (UnityUpgradable) -> camera", false)] public Camera m_Camera; public Camera camera { get { return previewScene.camera; } } [Obsolete("Use the property cameraFieldOfView (UnityUpgradable) -> cameraFieldOfView", false)] public float m_CameraFieldOfView; public float cameraFieldOfView { get { return camera.fieldOfView; } set { camera.fieldOfView = value; } } public Color ambientColor { get; set; } [Obsolete("Use the property lights (UnityUpgradable) -> lights", false)] public Light[] m_Light; public Light[] lights { get { return new[] { Light0, Light1 }; } } private Light Light0 { get; set; } private Light Light1 { get; set; } internal RenderTexture renderTexture { get { return m_RenderTexture; } } internal PreviewScene previewScene { get { return m_PreviewScene; } } public void Cleanup() { if (m_previewOpened) { Debug.LogError("Missing EndPreview() before cleanup of PreviewRenderUtility"); EndPreview(); } if (m_RenderTexture) { Object.DestroyImmediate(m_RenderTexture); m_RenderTexture = null; } if (m_InvisibleMaterial != null) { Object.DestroyImmediate(m_InvisibleMaterial); m_InvisibleMaterial = null; } previewScene.Dispose(); GC.SuppressFinalize(this); } public void BeginPreview(Rect r, GUIStyle previewBackground) { if(m_previewOpened) { Debug.LogError("Previous PreviewRenderUtility.BeginPreview() was not closed with PreviewRenderUtility.EndPreview()"); return; } m_previewOpened = true; Texture defaultEnvTexture = ReflectionProbe.defaultTexture; if (Unsupported.SetOverrideLightingSettings(previewScene.scene)) { RenderSettings.defaultReflectionMode = UnityEngine.Rendering.DefaultReflectionMode.Custom; RenderSettings.customReflectionTexture = defaultEnvTexture; } InitPreview(r); if (previewBackground == null || previewBackground == GUIStyle.none || previewBackground.normal.background == null) return; Graphics.DrawTexture( previewBackground.overflow.Add(new Rect(0, 0, m_RenderTexture.width, m_RenderTexture.height)), previewBackground.normal.background, new Rect(0, 0, 1, 1), previewBackground.border.left, previewBackground.border.right, previewBackground.border.top, previewBackground.border.bottom, new Color(.5f, .5f, .5f, 0.5f), null ); } public void BeginStaticPreview(Rect r) { InitPreview(r); var color = new Color(82 / 255f, 82 / 255f, 82 / 255f, 1.0f); var darkGreyBackground = new Texture2D(1, 1, TextureFormat.RGBA32, true); darkGreyBackground.SetPixel(0, 0, color); darkGreyBackground.Apply(); Graphics.DrawTexture(new Rect(0, 0, m_RenderTexture.width, m_RenderTexture.height), darkGreyBackground); Object.DestroyImmediate(darkGreyBackground); if (!EditorApplication.isUpdating && Unsupported.SetOverrideLightingSettings(previewScene.scene)) { RenderSettings.defaultReflectionMode = UnityEngine.Rendering.DefaultReflectionMode.Custom; RenderSettings.customReflectionTexture = GetDefaultReflection(); } } private static Cubemap s_DefaultReflection; private static Cubemap GetDefaultReflection() { // Reflection texture set to default prefab mode cubemap so that there are at least some reflections // (cannot use ReflectionProbe.defaultTexture as static previews are generated before it is set, case UUM-1820) const string path = "PrefabMode/DefaultReflectionForPrefabMode.exr"; if (s_DefaultReflection == null) s_DefaultReflection = EditorGUIUtility.Load(path) as Cubemap; if (s_DefaultReflection == null) Debug.LogError("Could not find: " + path); return s_DefaultReflection; } private void InitPreview(Rect r) { // If the background colour has changed then we can't make any assumptions // about colour space, otherwise flip to the background colour to the correct one if (colorSpace != QualitySettings.activeColorSpace && (camera.backgroundColor == defaultBackgroundColor || camera.backgroundColor.linear == defaultBackgroundColor.linear)) { camera.backgroundColor = QualitySettings.activeColorSpace == ColorSpace.Linear ? defaultBackgroundColor.linear : defaultBackgroundColor; } m_TargetRect = r; float scaleFac = EditorGUIUtility.pixelsPerPoint; int rtWidth = (int)(r.width * scaleFac); int rtHeight = (int)(r.height * scaleFac); if (!m_RenderTexture || m_RenderTexture.width != rtWidth || m_RenderTexture.height != rtHeight) { if (m_RenderTexture) { Object.DestroyImmediate(m_RenderTexture); m_RenderTexture = null; } // Do not use GetTemporary to manage render textures. Temporary RTs are only // garbage collected each N frames, and in the editor we might be wildly resizing // the inspector, thus using up tons of memory. GraphicsFormat format = camera.allowHDR ? GraphicsFormat.R16G16B16A16_SFloat : GraphicsFormat.R8G8B8A8_UNorm; m_RenderTexture = new RenderTexture(rtWidth, rtHeight, format, SystemInfo.GetGraphicsFormat(DefaultFormat.DepthStencil)); m_RenderTexture.hideFlags = HideFlags.HideAndDontSave; camera.targetTexture = m_RenderTexture; foreach (var light in lights) light.enabled = true; } if (Event.current != null && Event.current.type == EventType.Repaint) camera.pixelRect = new Rect(0, 0, rtWidth, rtHeight); else if (Event.current != null && Event.current.type == EventType.Layout) camera.pixelRect = EditorGUIUtility.PointsToPixels(r); m_SavedState = new SavedRenderTargetState(); EditorGUIUtility.SetRenderTextureNoViewport(m_RenderTexture); GL.LoadOrtho(); GL.LoadPixelMatrix(0, m_RenderTexture.width, m_RenderTexture.height, 0); ShaderUtil.rawViewportRect = new Rect(0, 0, m_RenderTexture.width, m_RenderTexture.height); ShaderUtil.rawScissorRect = new Rect(0, 0, m_RenderTexture.width, m_RenderTexture.height); GL.Clear(true, true, camera.backgroundColor); foreach (var light in lights) light.enabled = true; } public float GetScaleFactor(float width, float height) { float scaleFacX = Mathf.Max(Mathf.Min(width * 2, 1024), width) / width; float scaleFacY = Mathf.Max(Mathf.Min(height * 2, 1024), height) / height; float result = Mathf.Min(scaleFacX, scaleFacY) * EditorGUIUtility.pixelsPerPoint; if (m_PixelPerfect) result = Mathf.Max(Mathf.Round(result), 1f); return result; } [Obsolete("This method has been marked obsolete, use BeginStaticPreview() instead (UnityUpgradable) -> BeginStaticPreview(*)", false)] public void BeginStaticPreviewHDR(Rect r) { BeginStaticPreview(r); } [Obsolete("This method has been marked obsolete, use BeginPreview() instead (UnityUpgradable) -> BeginPreview(*)", false)] public void BeginPreviewHDR(Rect r, GUIStyle previewBackground) { BeginPreview(r, previewBackground); } public Texture EndPreview() { Unsupported.RestoreOverrideLightingSettings(); m_SavedState.Restore(); FinishFrame(); m_previewOpened = false; return m_RenderTexture; } private void FinishFrame() { Unsupported.RestoreOverrideLightingSettings(); foreach (var light in lights) light.enabled = false; } public void EndAndDrawPreview(Rect r) { var texture = EndPreview(); DrawPreview(r, texture); } internal static void DrawPreview(Rect r, Texture texture) { GUI.DrawTexture(r, texture, ScaleMode.StretchToFill, false); } public Texture2D EndStaticPreview() { if (!EditorApplication.isUpdating) Unsupported.RestoreOverrideLightingSettings(); var tmp = RenderTexture.GetTemporary((int)m_TargetRect.width, (int)m_TargetRect.height, 0, GraphicsFormat.R8G8B8A8_UNorm); Graphics.Blit(m_RenderTexture, tmp, EditorGUIUtility.GUITextureBlit2SRGBMaterial); RenderTexture.active = tmp; var copy = new Texture2D((int)m_TargetRect.width, (int)m_TargetRect.height, TextureFormat.RGB24, false, false); copy.ReadPixels(new Rect(0, 0, m_TargetRect.width, m_TargetRect.height), 0, 0); copy.Apply(); RenderTexture.ReleaseTemporary(tmp); m_SavedState.Restore(); FinishFrame(); return copy; } [Obsolete("AddSingleGO(GameObject go, bool instantiateAtZero) has been deprecated, use AddSingleGo(GameObject go) instead. instantiateAtZero has no effect and is not supported.")] public void AddSingleGO(GameObject go, bool instantiateAtZero) { AddSingleGO(go); } public void AddSingleGO(GameObject go) { previewScene.AddGameObject(go); } public GameObject InstantiatePrefabInScene(GameObject prefab) { var instance = (GameObject)PrefabUtility.InstantiatePrefab(prefab, m_PreviewScene.scene); return instance; } internal void AddManagedGO(GameObject go) { m_PreviewScene.AddManagedGO(go); } public void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material mat, int subMeshIndex) { DrawMesh(mesh, matrix, mat, subMeshIndex, null, null, false); } public void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material mat, int subMeshIndex, MaterialPropertyBlock customProperties) { DrawMesh(mesh, matrix, mat, subMeshIndex, customProperties, null, false); } public void DrawMesh(Mesh mesh, Matrix4x4 m, Material mat, int subMeshIndex, MaterialPropertyBlock customProperties, Transform probeAnchor, bool useLightProbe) { var quat = Quaternion.LookRotation(m.GetColumn(2), m.GetColumn(1)); var pos = m.GetColumn(3); var scale = new Vector3( m.GetColumn(0).magnitude, m.GetColumn(1).magnitude, m.GetColumn(2).magnitude ); DrawMesh(mesh, pos, scale, quat, mat, subMeshIndex, customProperties, probeAnchor, useLightProbe); } public void DrawMesh(Mesh mesh, Vector3 pos, Quaternion rot, Material mat, int subMeshIndex) { DrawMesh(mesh, pos, rot, mat, subMeshIndex, null, null, false); } public void DrawMesh(Mesh mesh, Vector3 pos, Quaternion rot, Material mat, int subMeshIndex, MaterialPropertyBlock customProperties) { DrawMesh(mesh, pos, rot, mat, subMeshIndex, customProperties, null, false); } public void DrawMesh(Mesh mesh, Vector3 pos, Quaternion rot, Material mat, int subMeshIndex, MaterialPropertyBlock customProperties, Transform probeAnchor) { DrawMesh(mesh, pos, rot, mat, subMeshIndex, customProperties, probeAnchor, false); } public void DrawMesh(Mesh mesh, Vector3 pos, Quaternion rot, Material mat, int subMeshIndex, MaterialPropertyBlock customProperties, Transform probeAnchor, bool useLightProbe) { DrawMesh(mesh, pos, Vector3.one, rot, mat, subMeshIndex, customProperties, probeAnchor, useLightProbe); } public void DrawMesh(Mesh mesh, Vector3 pos, Vector3 scale, Quaternion rot, Material mat, int subMeshIndex, MaterialPropertyBlock customProperties, Transform probeAnchor, bool useLightProbe) { Graphics.DrawMesh(mesh, Matrix4x4.TRS(pos, rot, scale), mat, 0, camera, subMeshIndex, customProperties, ShadowCastingMode.Off, false, probeAnchor, useLightProbe); } internal static Mesh GetPreviewSphere() { var handleGo = (GameObject)EditorGUIUtility.LoadRequired("Previews/PreviewMaterials.fbx"); // Temp workaround to make it not render in the scene handleGo.SetActive(false); foreach (Transform t in handleGo.transform) { if (t.name == "sphere") return t.GetComponent<MeshFilter>().sharedMesh; } return null; } protected static GameObject CreateLight() { GameObject lightGO = EditorUtility.CreateGameObjectWithHideFlags("PreRenderLight", HideFlags.HideAndDontSave, typeof(Light)); var light = lightGO.GetComponent<Light>(); light.type = LightType.Directional; light.intensity = 1.0f; light.enabled = false; return lightGO; } public void Render(bool allowScriptableRenderPipeline = false, bool updatefov = true) { if (!EditorApplication.isUpdating && Unsupported.SetOverrideLightingSettings(previewScene.scene)) { // User can set an ambientColor if they want to override the default black color // Cannot grab the main scene light probe/color instead as this is sometimes run on a worker without access to the original probe/color. RenderSettings.ambientMode = AmbientMode.Flat; RenderSettings.ambientLight = ambientColor; } foreach (var light in lights) light.enabled = true; var oldAllowPipes = Unsupported.useScriptableRenderPipeline; Unsupported.useScriptableRenderPipeline = allowScriptableRenderPipeline; float saveFieldOfView = camera.fieldOfView; if (updatefov) { // Calculate a view multiplier to avoid clipping when the preview width is smaller than the height. float viewMultiplier = (m_RenderTexture.width <= 0 ? 1.0f : Mathf.Max(1.0f, (float)m_RenderTexture.height / m_RenderTexture.width)); // Multiply the viewing area by the viewMultiplier - it requires some conversions since the camera view is expressed as an angle. camera.fieldOfView = Mathf.Atan(viewMultiplier * Mathf.Tan(camera.fieldOfView * 0.5f * Mathf.Deg2Rad)) * Mathf.Rad2Deg * 2.0f; } camera.Render(); camera.fieldOfView = saveFieldOfView; Unsupported.useScriptableRenderPipeline = oldAllowPipes; } } internal class SavedRenderTargetState { RenderTexture renderTexture; Rect viewport; Rect scissor; internal SavedRenderTargetState() { GL.PushMatrix(); if (ShaderUtil.hardwareSupportsRectRenderTexture) renderTexture = RenderTexture.active; viewport = ShaderUtil.rawViewportRect; scissor = ShaderUtil.rawScissorRect; } internal void Restore() { if (ShaderUtil.hardwareSupportsRectRenderTexture) EditorGUIUtility.SetRenderTextureNoViewport(renderTexture); ShaderUtil.rawViewportRect = viewport; ShaderUtil.rawScissorRect = scissor; GL.PopMatrix(); } } }
UnityCsReference/Editor/Mono/Inspector/PreviewRenderUtility.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/PreviewRenderUtility.cs", "repo_id": "UnityCsReference", "token_count": 9941 }
312
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEngine.Animations; namespace UnityEditor { [CustomEditor(typeof(ScaleConstraint))] [CanEditMultipleObjects] internal class ScaleConstraintEditor : ConstraintEditorBase { private SerializedProperty m_ScaleAtRest; private SerializedProperty m_ScaleOffset; private SerializedProperty m_Weight; private SerializedProperty m_IsContraintActive; private SerializedProperty m_IsLocked; private SerializedProperty m_Sources; internal override SerializedProperty atRest { get { return m_ScaleAtRest; } } internal override SerializedProperty offset { get { return m_ScaleOffset; } } internal override SerializedProperty weight { get { return m_Weight; } } internal override SerializedProperty isContraintActive { get { return m_IsContraintActive; } } internal override SerializedProperty isLocked { get { return m_IsLocked; } } internal override SerializedProperty sources { get { return m_Sources; } } private class Styles : ConstraintStyleBase { GUIContent m_ScaleAtRest = EditorGUIUtility.TrTextContent("Scale At Rest"); GUIContent m_ScaleOffset = EditorGUIUtility.TrTextContent("Scale Offset"); GUIContent m_ScalingAxes = EditorGUIUtility.TrTextContent("Freeze Scaling Axes"); public override GUIContent AtRest { get { return m_ScaleAtRest; } } public override GUIContent Offset { get { return m_ScaleOffset; } } public GUIContent FreezeAxes { get { return m_ScalingAxes; } } } private static Styles s_Style; public void OnEnable() { if (s_Style == null) s_Style = new Styles(); m_ScaleAtRest = serializedObject.FindProperty("m_ScaleAtRest"); m_ScaleOffset = serializedObject.FindProperty("m_ScaleOffset"); m_Weight = serializedObject.FindProperty("m_Weight"); m_IsContraintActive = serializedObject.FindProperty("m_Active"); m_IsLocked = serializedObject.FindProperty("m_IsLocked"); m_Sources = serializedObject.FindProperty("m_Sources"); OnEnable(s_Style); } internal override void OnValueAtRestChanged() { foreach (var t in targets) (t as ScaleConstraint).transform.localScale = atRest.vector3Value; } internal override void ShowFreezeAxesControl() { Rect drawRect = EditorGUILayout.GetControlRect(true, EditorGUI.GetPropertyHeight(SerializedPropertyType.Vector3, s_Style.FreezeAxes), EditorStyles.toggle); EditorGUI.MultiPropertyField(drawRect, s_Style.Axes, serializedObject.FindProperty("m_AffectScalingX"), s_Style.FreezeAxes); } public override void OnInspectorGUI() { if (s_Style == null) s_Style = new Styles(); serializedObject.Update(); ShowConstraintEditor<ScaleConstraint>(s_Style); serializedObject.ApplyModifiedProperties(); } } }
UnityCsReference/Editor/Mono/Inspector/ScaleConstraintEditor.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/ScaleConstraintEditor.cs", "repo_id": "UnityCsReference", "token_count": 1284 }
313
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using Unity.IntegerTime; using UnityEngine; namespace UnityEditor { [CustomEditor(typeof(TimeManager))] internal class TimeManagerEditor : Editor { class Content { public static readonly GUIContent fixedTimestepLabel = EditorGUIUtility.TrTextContent("Fixed Timestep", "A framerate-independent interval that dictates when physics calculations and FixedUpdate() events are performed."); public static readonly GUIContent maxAllowedTimestepLabel = EditorGUIUtility.TrTextContent("Maximum Allowed Timestep", "A framerate-independent interval that caps the worst-case scenario when framerate is low. Physics calculations and FixedUpdate() events will not be performed for longer time than specified."); public static readonly GUIContent timeScaleLabel = EditorGUIUtility.TrTextContent("Time Scale", "The speed at which time progresses. Change this value to simulate bullet-time effects. A value of 1 means real-time. A value of .5 means half speed; a value of 2 is double speed."); public static readonly GUIContent maxParticleTimestepLabel = EditorGUIUtility.TrTextContent("Maximum Particle Timestep", "The maximum frame delta time Unity permits for a single iteration of the Particle System update. If the delta time is larger than this value, Unity will run the Particle System update multiple times during the frame with smaller timesteps. This preserves the quality of the simulation."); } SerializedProperty m_FixedTimestepCountProperty; SerializedProperty m_MaxAllowedTimestepProperty; SerializedProperty m_TimeScaleProperty; SerializedProperty m_MaxParticleTimestepProperty; static RationalTime.TicksPerSecond m_FixedTimeTicksPerSecond; const float MinFixedTimeStep = 0.0001f; public void OnEnable() { var fixedTimestepProperty = serializedObject.FindProperty("Fixed Timestep"); m_FixedTimestepCountProperty = fixedTimestepProperty.FindPropertyRelative("m_Count"); m_MaxAllowedTimestepProperty = serializedObject.FindProperty("Maximum Allowed Timestep"); m_TimeScaleProperty = serializedObject.FindProperty("m_TimeScale"); m_MaxParticleTimestepProperty = serializedObject.FindProperty("Maximum Particle Timestep"); if (!m_FixedTimeTicksPerSecond.Valid) // FixedTime has a constant ticks per second value { var numerator = fixedTimestepProperty.FindPropertyRelative("m_Rate.m_Numerator"); var denominator = fixedTimestepProperty.FindPropertyRelative("m_Rate.m_Denominator"); m_FixedTimeTicksPerSecond = new RationalTime.TicksPerSecond(numerator.uintValue, denominator.uintValue); } } public override void OnInspectorGUI() { serializedObject.Update(); DrawFixedTimeAsFloat(m_FixedTimestepCountProperty); EditorGUILayout.PropertyField(m_MaxAllowedTimestepProperty, Content.maxAllowedTimestepLabel); EditorGUILayout.PropertyField(m_TimeScaleProperty, Content.timeScaleLabel); EditorGUILayout.PropertyField(m_MaxParticleTimestepProperty, Content.maxParticleTimestepLabel); serializedObject.ApplyModifiedProperties(); } static void DrawFixedTimeAsFloat(SerializedProperty prop) { var fixedTime = (float)new RationalTime(prop.longValue, m_FixedTimeTicksPerSecond).ToDouble(); // Convert a tick count to a float using (var c = new EditorGUI.ChangeCheckScope()) { var maxFixedTime = MathF.Max(fixedTime, MinFixedTimeStep); var roundedTime = Math.Round(maxFixedTime, 4, MidpointRounding.AwayFromZero); fixedTime = EditorGUILayout.FloatField(Content.fixedTimestepLabel, (float)roundedTime); if (c.changed) { var newCount = RationalTime .FromDouble(fixedTime, m_FixedTimeTicksPerSecond) .Count; // convert it back to a count to store in the property prop.longValue = newCount; } } } [SettingsProvider] internal static SettingsProvider CreateProjectSettingsProvider() { var provider = AssetSettingsProvider.CreateProviderFromAssetPath( "Project/Time", "ProjectSettings/TimeManager.asset", SettingsProvider.GetSearchKeywordsFromGUIContentProperties<Content>()); return provider; } } }
UnityCsReference/Editor/Mono/Inspector/TimeManagerInspector.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/TimeManagerInspector.cs", "repo_id": "UnityCsReference", "token_count": 1804 }
314
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEditor.Experimental; using UnityEditor.StyleSheets; using UnityEngine; using UnityEngine.UIElements; using Object = UnityEngine.Object; namespace UnityEditor.UIElements.ProjectSettings { internal class ProjectSettingsTitleBar : ProjectSettingsElementWithSO { [UnityEngine.Internal.ExcludeFromDocs, Serializable] public new class UxmlSerializedData : VisualElement.UxmlSerializedData { #pragma warning disable 649 [SerializeField] string label; [SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags label_UxmlAttributeFlags; #pragma warning restore 649 public override object CreateInstance() => new ProjectSettingsTitleBar(); public override void Deserialize(object obj) { base.Deserialize(obj); if (ShouldWriteAttributeValue(label_UxmlAttributeFlags)) { var e = (ProjectSettingsTitleBar)obj; e.label = label; } } } internal class Styles { public static StyleBlock settingsBtn { get; } = EditorResources.GetStyle("sb-settings-icon-btn"); public const string k_TitleBarClassName = "project-settings-title-bar"; public const string k_TitleLabelClassName = "project-settings-title-bar__label"; } string m_Label; public string label { get => m_Label; set { m_Label = value; m_LabelElement.text = m_Label; } } readonly Label m_LabelElement; Object[] m_TargetObjects; public ProjectSettingsTitleBar() : this (null) { } public ProjectSettingsTitleBar(string label) { AddToClassList(Styles.k_TitleBarClassName); m_LabelElement = new Label(); m_LabelElement.AddToClassList(Styles.k_TitleLabelClassName); Add(m_LabelElement); Add(new IMGUIContainer(DrawEditorHeaderItems)); if (!string.IsNullOrEmpty(label)) this.label = label; } protected override void Initialize() { m_TargetObjects = m_SerializedObject.targetObjects; } void DrawEditorHeaderItems() { GUILayout.BeginHorizontal(); var btnWidth = Styles.settingsBtn.GetFloat(StyleCatalogKeyword.width); var btnHeight = Styles.settingsBtn.GetFloat(StyleCatalogKeyword.height); var btnMargin = Styles.settingsBtn.GetFloat(StyleCatalogKeyword.marginTop); var currentRect = GUILayoutUtility.GetRect(btnWidth, btnHeight); currentRect.y = btnMargin; currentRect.x += btnWidth; EditorGUIUtility.DrawEditorHeaderItems(currentRect, m_TargetObjects); //This needs to be here to not draw HeaderItems and Dropdown for Presets on the same place var settingsRect = GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.optionsButtonStyle); settingsRect.y = currentRect.y; // Settings; process event even for disabled UI var wasEnabled = GUI.enabled; GUI.enabled = true; var dropdownRect = GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.optionsButtonStyle); dropdownRect.y = currentRect.y; var showMenu = EditorGUI.DropdownButton(dropdownRect, GUIContent.none, FocusType.Passive, EditorStyles.optionsButtonStyle); GUI.enabled = wasEnabled; if (showMenu) EditorUtility.DisplayObjectContextMenu(dropdownRect, m_TargetObjects, 0); GUILayout.EndHorizontal(); } } }
UnityCsReference/Editor/Mono/Inspector/VisualElements/ProjectSettings/ProjectSettingsTitleBar.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/VisualElements/ProjectSettings/ProjectSettingsTitleBar.cs", "repo_id": "UnityCsReference", "token_count": 1759 }
315
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; using Object = UnityEngine.Object; using ShaderPropertyType = UnityEngine.Rendering.ShaderPropertyType; using ShaderPropertyFlags = UnityEngine.Rendering.ShaderPropertyFlags; namespace UnityEditor { // match MonoMaterialProperty layout! [StructLayout(LayoutKind.Sequential)] public sealed partial class MaterialProperty { public delegate bool ApplyPropertyCallback(MaterialProperty prop, int changeMask, object previousValue); private Object[] m_Targets; private ApplyPropertyCallback m_ApplyPropertyCallback; private string m_Name; private string m_DisplayName; private System.Object m_Value; private Vector4 m_TextureScaleAndOffset; private Vector2 m_RangeLimits; private ShaderPropertyType m_Type; private ShaderPropertyFlags m_Flags; private UnityEngine.Rendering.TextureDimension m_TextureDimension; private int m_MixedValueMask; public Object[] targets { get { return m_Targets; } } public PropType type { get { return (PropType)m_Type; } } public string name { get { return m_Name; } } public string displayName { get { return m_DisplayName; } } public PropFlags flags { get { return (PropFlags)m_Flags; } } public UnityEngine.Rendering.TextureDimension textureDimension { get { return m_TextureDimension; } } public Vector2 rangeLimits { get { return m_RangeLimits; } } public bool hasMixedValue { get { return (m_MixedValueMask & 1) != 0; } } public ApplyPropertyCallback applyPropertyCallback { get { return m_ApplyPropertyCallback; } set { m_ApplyPropertyCallback = value; } } // Textures have 5 different mixed values for texture + UV scale/offset internal int mixedValueMask { get { return m_MixedValueMask; } } public void ReadFromMaterialPropertyBlock(MaterialPropertyBlock block) { ShaderUtil.ApplyMaterialPropertyBlockToMaterialProperty(block, this); } public void WriteToMaterialPropertyBlock(MaterialPropertyBlock materialblock, int changedPropertyMask) { ShaderUtil.ApplyMaterialPropertyToMaterialPropertyBlock(this, changedPropertyMask, materialblock); } public Color colorValue { get { if (m_Type == ShaderPropertyType.Color) return (Color)m_Value; return Color.black; } set { if (m_Type != ShaderPropertyType.Color) return; if (!hasMixedValue && value == (Color)m_Value) return; ApplyProperty(value); } } public Vector4 vectorValue { get { if (m_Type == ShaderPropertyType.Vector) return (Vector4)m_Value; return Vector4.zero; } set { if (m_Type != ShaderPropertyType.Vector) return; if (!hasMixedValue && value == (Vector4)m_Value) return; ApplyProperty(value); } } internal static bool IsTextureOffsetAndScaleChangedMask(int changedMask) { changedMask >>= 1; return changedMask != 0; } public float floatValue { get { if (m_Type == ShaderPropertyType.Float || m_Type == ShaderPropertyType.Range) return (float)m_Value; return 0.0f; } set { if (m_Type != ShaderPropertyType.Float && m_Type != ShaderPropertyType.Range) return; if (!hasMixedValue && value == (float)m_Value) return; ApplyProperty(value); } } public int intValue { get { if (m_Type == ShaderPropertyType.Int) return (int)m_Value; return 0; } set { if (m_Type != ShaderPropertyType.Int) return; if (!hasMixedValue && value == (int)m_Value) return; ApplyProperty(value); } } public Texture textureValue { get { if (m_Type == ShaderPropertyType.Texture) return (Texture)m_Value; return null; } set { if (m_Type != ShaderPropertyType.Texture) return; if (!hasMixedValue && value == (Texture)m_Value) return; m_MixedValueMask &= ~1; object previousValue = m_Value; m_Value = value; ApplyProperty(previousValue, 1); } } public Vector4 textureScaleAndOffset { get { if (m_Type == ShaderPropertyType.Texture) return m_TextureScaleAndOffset; return Vector4.zero; } set { if (m_Type != ShaderPropertyType.Texture) return; if (!hasMixedValue && value == m_TextureScaleAndOffset) return; m_MixedValueMask &= 1; int changedMask = 0; for (int c = 1; c < 5; c++) changedMask |= 1 << c; object previousValue = m_TextureScaleAndOffset; m_TextureScaleAndOffset = value; ApplyProperty(previousValue, changedMask); } } private void ApplyProperty(object newValue) { m_MixedValueMask = 0; object previousValue = m_Value; m_Value = newValue; ApplyProperty(previousValue, 1); } private void ApplyProperty(object previousValue, int changedPropertyMask) { if (targets == null || targets.Length == 0) throw new ArgumentException("No material targets provided"); Object[] mats = targets; string targetTitle; if (mats.Length == 1) targetTitle = mats[0].name; else targetTitle = mats.Length + " " + ObjectNames.NicifyVariableName(ObjectNames.GetClassName(mats[0])) + "s"; //@TODO: Maybe all this logic should be moved to C++ // reduces api surface... bool didApply = false; if (m_ApplyPropertyCallback != null) didApply = m_ApplyPropertyCallback(this, changedPropertyMask, previousValue); if (!didApply) ShaderUtil.ApplyProperty(this, changedPropertyMask, "Modify " + displayName + " of " + targetTitle); } // -------- helper functions to handle material variant overrides // It displays the override bar on the left, the lock icon, and the bold font // It also creates the context menu when left clicking a property private static class Styles { public static string revertMultiText = L10n.Tr("Revert on {0} Material(s)"); public static string applyToMaterialText = L10n.Tr("Apply to Material '{0}'"); public static string applyToVariantText = L10n.Tr("Apply as Override in Variant '{0}'"); static Color overrideLineColor_l = new Color32(0x09, 0x09, 0x09, 0xFF); static Color overrideLineColor_d = new Color32(0xC4, 0xC4, 0xC4, 0xFF); public static Color overrideLineColor { get { return EditorGUIUtility.isProSkin ? overrideLineColor_d : overrideLineColor_l; } } public static readonly GUIContent revertContent = EditorGUIUtility.TrTextContent("Revert"); public static readonly GUIContent revertAllContent = EditorGUIUtility.TrTextContent("Revert all Overrides"); public static readonly GUIContent lockContent = EditorGUIUtility.TrTextContent("Lock in children"); public static readonly GUIContent lockOriginContent = EditorGUIUtility.TrTextContent("See lock origin"); public static readonly GUIContent resetContent = EditorGUIUtility.TrTextContent("Reset"); public static readonly GUIContent copyContent = EditorGUIUtility.TrTextContent("Copy"); public static readonly GUIContent pasteContent = EditorGUIUtility.TrTextContent("Paste"); static readonly Texture lockInChildrenIcon = EditorGUIUtility.IconContent("HierarchyLock").image; public static readonly GUIContent lockInChildrenContent = EditorGUIUtility.TrTextContent(string.Empty, "Locked properties cannot be overriden by a child.", lockInChildrenIcon); static readonly Texture lockedByAncestorIcon = EditorGUIUtility.IconContent("IN LockButton on").image; public static readonly GUIContent lockedByAncestorContent = EditorGUIUtility.TrTextContent(string.Empty, "This property is set and locked by an ancestor.", lockedByAncestorIcon); public static readonly GUIStyle centered = new GUIStyle(EditorStyles.label) { alignment = TextAnchor.MiddleLeft }; } struct PropertyData { public MaterialProperty property; public MaterialSerializedProperty serializedProperty; public Object[] targets; public bool wasBoldDefaultFont; public bool allowLocking; public bool isLockedInChildren, isLockedByAncestor, isOverriden; public float startY; public Rect position; private static List<MaterialProperty> capturedProperties = new List<MaterialProperty>(); private static List<MaterialSerializedProperty> capturedSerializedProperties = new List<MaterialSerializedProperty>(); private bool HasMixedValues<T>(Func<Material, T> getter) { T value = getter(targets[0] as Material); for (int i = 1; i < targets.Length; ++i) { if (!EqualityComparer<T>.Default.Equals(value, getter(targets[i] as Material))) return true; } return false; } public bool hasMixedValue { get { if (property != null) return property.hasMixedValue; if (serializedProperty == MaterialSerializedProperty.EnableInstancingVariants) return HasMixedValues((mat) => mat.enableInstancing); else if (serializedProperty == MaterialSerializedProperty.LightmapFlags) return HasMixedValues((mat) => mat.globalIlluminationFlags); else if (serializedProperty == MaterialSerializedProperty.DoubleSidedGI) return HasMixedValues((mat) => mat.doubleSidedGI); else if (serializedProperty == MaterialSerializedProperty.CustomRenderQueue) return HasMixedValues((mat) => mat.rawRenderQueue); return false; } } public void Init() { isLockedInChildren = false; isLockedByAncestor = false; allowLocking = true; isOverriden = true; int nameId = property != null ? Shader.PropertyToID(property.name) : -1; foreach (Material target in targets) { bool l, b, o; if (property != null) target.GetPropertyState(nameId, out o, out l, out b); else target.GetPropertyState(serializedProperty, out o, out l, out b); // When multi editing: // 1. Show property as locked if any target is locked, to prevent bypassing the lock // 2. Show property as overriden if all targets override it, to not show overrides on materials isLockedInChildren |= l; isLockedByAncestor |= b; isOverriden &= o; allowLocking &= target.allowLocking; } } static void MergeStack(out bool lockedInChildren, out bool lockedByAncestor, out bool overriden) { // We have to copy the property stack, because access from the Menu callbacks is delayed capturedProperties.Clear(); capturedSerializedProperties.Clear(); lockedInChildren = false; lockedByAncestor = false; overriden = false; for (int i = 0; i < s_PropertyStack.Count; i++) { // When multiple properties are displayed on the same line, we *or* everything otherwise it gets confusing. if (s_PropertyStack[i].targets == null) continue; lockedInChildren |= s_PropertyStack[i].isLockedInChildren; lockedByAncestor |= s_PropertyStack[i].isLockedByAncestor; overriden |= s_PropertyStack[i].isOverriden; if (s_PropertyStack[i].property != null) capturedProperties.Add(s_PropertyStack[i].property); else capturedSerializedProperties.Add(s_PropertyStack[i].serializedProperty); } } static string GetMultiEditingDisplayName(string multiEditSuffix) { int nonEmptyCount = capturedProperties.Count + capturedSerializedProperties.Count; if (nonEmptyCount != 1) return nonEmptyCount + " " + multiEditSuffix; else if (capturedProperties.Count != 0) return capturedProperties[0].displayName; else return capturedSerializedProperties[0].ToString(); } public static void DoPropertyContextMenu(bool lockMenusOnly, Object[] targets, bool allowLocking) { MergeStack(out bool lockedInChildren, out bool lockedByAncestor, out bool overriden); GenericMenu menu = new GenericMenu(); if (lockedByAncestor) { if (targets.Length != 1) return; menu.AddItem(Styles.lockOriginContent, false, () => GotoLockOriginAction(targets)); } else if (GUI.enabled) { if (!lockMenusOnly) DoRegularMenu(menu, overriden, targets); DoLockPropertiesMenu(menu, !lockedInChildren, targets, allowLocking); } if (Event.current.shift && capturedProperties.Count == 1) { if (menu.GetItemCount() != 0) menu.AddSeparator(""); menu.AddItem(EditorGUIUtility.TrTextContent("Copy Property Name"), false, () => EditorGUIUtility.systemCopyBuffer = capturedProperties[0].name); } if (menu.GetItemCount() == 0) return; Event.current.Use(); menu.ShowAsContext(); } enum DisplayMode { Material, Variant, Mixed }; static DisplayMode GetDisplayMode(Object[] targets) { int variantCount = MaterialEditor.GetVariantCount(targets); if (variantCount == 0) return DisplayMode.Material; if (variantCount == targets.Length) return DisplayMode.Variant; return DisplayMode.Mixed; } static void ResetMaterialProperties() { foreach (var property in capturedProperties) { // fetch default value from shader var shader = (property.targets[0] as Material).shader; int nameId = shader.FindPropertyIndex(property.name); switch (property.type) { case PropType.Float: case PropType.Range: property.floatValue = shader.GetPropertyDefaultFloatValue(nameId); break; case PropType.Vector: property.vectorValue = shader.GetPropertyDefaultVectorValue(nameId); break; case PropType.Color: property.colorValue = shader.GetPropertyDefaultVectorValue(nameId); break; case PropType.Int: property.intValue = shader.GetPropertyDefaultIntValue(nameId); break; case PropType.Texture: Texture texture = null; var importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(shader)) as ShaderImporter; if (importer != null) texture = importer.GetDefaultTexture(property.name); if (texture == null) texture = EditorMaterialUtility.GetShaderDefaultTexture(shader, property.name); property.textureValue = texture; property.textureScaleAndOffset = new Vector4(1, 1, 0, 0); break; } } } static void HandleApplyRevert(GenericMenu menu, bool singleEditing, Object[] targets) { // Apply if (singleEditing) { Material source = (Material)targets[0]; Material destination = (Material)targets[0]; while (destination = destination.parent as Material) { if (AssetDatabase.IsForeignAsset(destination)) continue; var text = destination.isVariant ? Styles.applyToVariantText : Styles.applyToMaterialText; var applyContent = new GUIContent(string.Format(text, destination.name)); menu.AddItem(applyContent, false, (object dest) => { foreach (var prop in capturedProperties) source.ApplyPropertyOverride((Material)dest, prop.name); foreach (var prop in capturedSerializedProperties) source.ApplyPropertyOverride((Material)dest, prop); }, destination); } } // Revert var content = singleEditing ? Styles.revertContent : EditorGUIUtility.TempContent(string.Format(Styles.revertMultiText, targets.Length)); menu.AddItem(content, false, () => { string displayName = GetMultiEditingDisplayName("overrides"); string targetName = singleEditing ? targets[0].name : targets.Length + " Materials"; Undo.RecordObjects(targets, "Revert " + displayName + " of " + targetName); foreach (Material target in targets) { foreach (var prop in capturedProperties) target.RevertPropertyOverride(prop.name); foreach (var prop in capturedSerializedProperties) target.RevertPropertyOverride(prop); } }); } static void HandleCopyPaste(GenericMenu menu) { GetCopyPasteAction(capturedProperties[0], out var copyAction, out var pasteAction); if (menu.GetItemCount() != 0) menu.AddSeparator(""); if (copyAction != null) menu.AddItem(Styles.copyContent, false, copyAction); else menu.AddDisabledItem(Styles.copyContent); if (pasteAction != null) menu.AddItem(Styles.pasteContent, false, pasteAction); else menu.AddDisabledItem(Styles.pasteContent); } static void HandleRevertAll(GenericMenu menu, bool singleEditing, Object[] targets) { foreach (Material target in targets) { if (target.overrideCount != 0) { if (menu.GetItemCount() != 0) menu.AddSeparator(""); menu.AddItem(Styles.revertAllContent, false, () => { string targetName = singleEditing ? targets[0].name : targets.Length + " Materials"; Undo.RecordObjects(targets, "Revert all overrides of " + targetName); foreach (Material target in targets) target.RevertAllPropertyOverrides(); }); break; } } } static void DoRegularMenu(GenericMenu menu, bool isOverriden, Object[] targets) { var singleEditing = targets.Length == 1; if (isOverriden) HandleApplyRevert(menu, singleEditing, targets); if (singleEditing && capturedProperties.Count == 1) HandleCopyPaste(menu); DisplayMode displayMode = GetDisplayMode(targets); if (displayMode == DisplayMode.Material) { if (menu.GetItemCount() != 0) menu.AddSeparator(""); menu.AddItem(Styles.resetContent, false, ResetMaterialProperties); } else if (displayMode == DisplayMode.Variant) HandleRevertAll(menu, singleEditing, targets); } static void GetCopyPasteAction(MaterialProperty prop, out GenericMenu.MenuFunction copyAction, out GenericMenu.MenuFunction pasteAction) { bool canCopy = !capturedProperties[0].hasMixedValue; bool canPaste = GUI.enabled; copyAction = null; pasteAction = null; switch (prop.type) { case PropType.Float: case PropType.Range: if (canCopy) copyAction = () => Clipboard.floatValue = prop.floatValue; if (canPaste && Clipboard.hasFloat) pasteAction = () => prop.floatValue = Clipboard.floatValue; break; case PropType.Int: if (canCopy) copyAction = () => Clipboard.integerValue = prop.intValue; if (canPaste && Clipboard.hasInteger) pasteAction = () => prop.intValue = Clipboard.integerValue; break; case PropType.Color: if (canCopy) copyAction = () => Clipboard.colorValue = prop.colorValue; if (canPaste && Clipboard.hasColor) pasteAction = () => prop.colorValue = Clipboard.colorValue; break; case PropType.Vector: if (canCopy) copyAction = () => Clipboard.vector4Value = prop.vectorValue; if (canPaste && Clipboard.hasVector4) pasteAction = () => prop.vectorValue = Clipboard.vector4Value; break; case PropType.Texture: if (canCopy) copyAction = () => Clipboard.guidValue = AssetDatabase.GUIDFromAssetPath(AssetDatabase.GetAssetPath(prop.textureValue)); if (canPaste && Clipboard.hasGuid) pasteAction = () => prop.textureValue = AssetDatabase.LoadMainAssetAtPath(AssetDatabase.GUIDToAssetPath(Clipboard.guidValue)) as Texture; break; } } static void DoLockPropertiesMenu(GenericMenu menu, bool lockValue, Object[] targets, bool allowLocking) { if (menu.GetItemCount() != 0) menu.AddSeparator(""); if (allowLocking) { menu.AddItem(Styles.lockContent, !lockValue, () => { LockProperties(lockValue, targets); }); } else { menu.AddDisabledItem(Styles.lockContent); } } static void LockProperties(bool lockValue, Object[] targets) { string actionName = lockValue ? "locking" : "unlocking"; string displayName = GetMultiEditingDisplayName("properties"); string targetName = targets.Length == 1 ? targets[0].name : targets.Length + " Materials"; Undo.RecordObjects(targets, string.Format("{0} {1} of {2}", actionName, displayName, targetName)); foreach (Material target in targets) { foreach (var prop in capturedProperties) target.SetPropertyLock(prop.name, lockValue); foreach (var prop in capturedSerializedProperties) target.SetPropertyLock(prop, lockValue); } } static public void DoLockAction(Object[] targets) { MergeStack(out bool lockedInChildren, out bool lockedByAncestor, out bool _); if (lockedByAncestor) GotoLockOriginAction(targets); else LockProperties(!lockedInChildren, targets); Event.current.Use(); } static void GotoLockOriginAction(Object[] targets) { // Find lock origin Material origin = targets[0] as Material; while ((origin = origin.parent)) { bool isLocked = false; foreach (var prop in capturedProperties) { origin.GetPropertyState(Shader.PropertyToID(prop.name), out _, out isLocked, out _); if (isLocked) break; } if (isLocked) break; foreach (var prop in capturedSerializedProperties) { origin.GetPropertyState(prop, out _, out isLocked, out _); if (isLocked) break; } if (isLocked) break; } if (origin) { int clickCount = 1; if (Event.current != null) { clickCount = Event.current.clickCount; Event.current.Use(); } if (clickCount == 1) EditorGUIUtility.PingObject(origin); else { Selection.SetActiveObjectWithContext(origin, null); GUIUtility.ExitGUI(); } } } } static List<PropertyData> s_PropertyStack = new List<PropertyData>(); internal static void ClearStack() => s_PropertyStack.Clear(); internal static void BeginProperty(MaterialProperty prop, Object[] targets) { // Get the current Y coordinate before drawing the property // We define a new empty rect in order to grab the current height even if there was nothing drawn in the block // (GetLastRect cause issue if it was first element of block) MaterialProperty.BeginProperty(Rect.zero, prop, 0, targets, GUILayoutUtility.GetRect(0, 0).yMax); } internal static void BeginProperty(MaterialSerializedProperty prop, Object[] targets) { // Get the current Y coordinate before drawing the property // We define a new empty rect in order to grab the current height even if there was nothing drawn in the block // (GetLastRect cause issue if it was first element of block) MaterialProperty.BeginProperty(Rect.zero, null, prop, targets, GUILayoutUtility.GetRect(0, 0).yMax); } internal static void BeginProperty(Rect totalRect, MaterialProperty prop, MaterialSerializedProperty serializedProp, Object[] targets, float startY = -1) { if (targets == null || IsRegistered(prop, serializedProp)) { s_PropertyStack.Add(new PropertyData() { targets = null }); return; } PropertyData data = new PropertyData() { property = prop, serializedProperty = serializedProp, targets = targets, startY = startY, position = totalRect, wasBoldDefaultFont = EditorGUIUtility.GetBoldDefaultFont() }; data.Init(); s_PropertyStack.Add(data); if (data.isOverriden) EditorGUIUtility.SetBoldDefaultFont(true); if (data.isLockedByAncestor) EditorGUI.BeginDisabledGroup(true); EditorGUI.showMixedValue = data.hasMixedValue; } internal static void EndProperty() { if (s_PropertyStack.Count == 0) { Debug.LogError("MaterialProperty stack is empty"); return; } var data = s_PropertyStack[s_PropertyStack.Count - 1]; if (data.targets == null) { s_PropertyStack.RemoveAt(s_PropertyStack.Count - 1); return; } Rect position = data.position; if (data.startY != -1) { position = GUILayoutUtility.GetLastRect(); position.yMin = data.startY; position.x = 1; position.width = EditorGUIUtility.labelWidth; } bool mouseOnLock = false; if (position != Rect.zero) { // Display override rect if (data.isOverriden) EditorGUI.DrawMarginLineForRect(position, Styles.overrideLineColor); Rect lockRegion = position; lockRegion.width = 14; lockRegion.height = 14; lockRegion.x = 11; lockRegion.y += (position.height - lockRegion.height) * 0.5f; mouseOnLock = lockRegion.Contains(Event.current.mousePosition); // Display lock icon Rect lockRect = position; lockRect.width = 32; lockRect.height = Mathf.Max(lockRect.height, 20.0f); lockRect.x = 8; lockRect.y += (position.height - lockRect.height) * 0.5f; if (data.isLockedByAncestor) { // Make sure we draw the lock only once bool isLastLockInStack = true; for (int i = 0; i < s_PropertyStack.Count - 1; i++) { if (s_PropertyStack[i].isLockedByAncestor) { isLastLockInStack = false; break; } } if (isLastLockInStack) GUI.Label(lockRect, Styles.lockedByAncestorContent, Styles.centered); } else if (data.isLockedInChildren) GUI.Label(lockRect, Styles.lockInChildrenContent, Styles.centered); else if (GUI.enabled && data.allowLocking) { GUIView.current?.MarkHotRegion(GUIClip.UnclipToWindow(lockRegion)); if (mouseOnLock) { EditorGUI.BeginDisabledGroup(true); GUI.Label(lockRect, Styles.lockInChildrenContent, Styles.centered); EditorGUI.EndDisabledGroup(); } } } // Restore state EditorGUI.showMixedValue = false; EditorGUIUtility.SetBoldDefaultFont(data.wasBoldDefaultFont); if (data.isLockedByAncestor) EditorGUI.EndDisabledGroup(); // Context menu if (Event.current.rawType == EventType.ContextClick && (position.Contains(Event.current.mousePosition) || mouseOnLock)) PropertyData.DoPropertyContextMenu(mouseOnLock, data.targets, data.allowLocking); else if (Event.current.type == EventType.MouseUp && Event.current.button == 0 && mouseOnLock && data.allowLocking) PropertyData.DoLockAction(data.targets); s_PropertyStack.RemoveAt(s_PropertyStack.Count - 1); } static bool IsRegistered(MaterialProperty prop, MaterialSerializedProperty serializedProp) { // [PerRendererData] material properties are read-only as they are meant to be set in code on a per-renderer basis. // Don't show override UI for them if (prop != null && (prop.flags & PropFlags.PerRendererData) != 0) return true; for (int i = 0; i < s_PropertyStack.Count; i++) { if (s_PropertyStack[i].property == prop && s_PropertyStack[i].serializedProperty == serializedProp) return true; } return false; } } } // namespace UnityEngine.Rendering
UnityCsReference/Editor/Mono/MaterialProperty.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/MaterialProperty.cs", "repo_id": "UnityCsReference", "token_count": 17543 }
316
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using UnityEditor.Scripting.ScriptCompilation; using UnityEngine; namespace UnityEditor.Modules { internal class DefaultPluginImporterExtension : IPluginImporterExtension { protected bool hasModified = false; protected Property[] properties = null; protected const string cpuKey = "CPU"; internal class Property { internal GUIContent name { get; set; } internal string key { get; set; } internal object defaultValue { get; set; } internal Type type { get; set; } internal string platformName { get; set; } internal object value { get; set; } internal Property(string name, string key, object defaultValue, string platformName) : this(new GUIContent(name), key, defaultValue, platformName) { } internal Property(GUIContent name, string key, object defaultValue, string platformName) { this.name = name; this.key = key; this.defaultValue = defaultValue; this.type = defaultValue.GetType(); this.platformName = platformName; } internal virtual void Reset(PluginImporterInspector inspector) { string valueString = inspector.importer.GetPlatformData(platformName, key); ParseStringValue(inspector, valueString); } protected void ParseStringValue(PluginImporterInspector inspector, string valueString, bool muteWarnings = false) { try { value = TypeDescriptor.GetConverter(type).ConvertFromString(valueString); } catch { value = defaultValue; if (!muteWarnings && !string.IsNullOrEmpty(valueString)) { // We mute warnings for properties that are on disabled platforms to avoid unnecessary spam for deprecated values, case 909247 if (inspector.importer.GetCompatibleWithPlatform(platformName)) Debug.LogWarning("Failed to parse value ('" + valueString + "') for " + key + ", platform: " + platformName + ", type: " + type + ". Default value will be set '" + defaultValue + "'"); } } } internal virtual void Apply(PluginImporterInspector inspector) { string valueString = type == typeof(bool) ? value.ToString().ToLower() : value.ToString(); inspector.importer.SetPlatformData(platformName, key, valueString); } internal virtual void OnGUI(PluginImporterInspector inspector) { if (type == typeof(bool)) value = EditorGUILayout.Toggle(name, (bool)value); else if (type.IsEnum) { if (type.GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0) value = EditorGUILayout.EnumFlagsField(name, (Enum)value); else value = EditorGUILayout.EnumPopup(name, (Enum)value); } else if (type == typeof(string)) value = EditorGUILayout.TextField(name, (string)value); else throw new NotImplementedException("Don't know how to display value."); } } internal bool propertiesRefreshed = false; public DefaultPluginImporterExtension(Property[] properties) { this.properties = properties; } protected virtual Property[] GetPropertiesForInspector(PluginImporterInspector inspector) { return properties; } public virtual void ResetValues(PluginImporterInspector inspector) { hasModified = false; RefreshProperties(inspector); } public virtual bool HasModified(PluginImporterInspector inspector) { return hasModified; } public virtual void Apply(PluginImporterInspector inspector) { if (!propertiesRefreshed) return; foreach (var p in GetPropertiesForInspector(inspector)) { p.Apply(inspector); } hasModified = false; } public virtual void OnEnable(PluginImporterInspector inspector) { RefreshProperties(inspector); } public virtual void OnDisable(PluginImporterInspector inspector) { } public virtual void OnPlatformSettingsGUI(PluginImporterInspector inspector) { if (!propertiesRefreshed) RefreshProperties(inspector); EditorGUI.BeginChangeCheck(); foreach (var p in GetPropertiesForInspector(inspector)) { // skip CPU property for things that aren't native libs if (p.key == cpuKey && !inspector.importer.isNativePlugin) continue; p.OnGUI(inspector); } if (EditorGUI.EndChangeCheck()) hasModified = true; } protected virtual void RefreshProperties(PluginImporterInspector inspector) { foreach (var p in GetPropertiesForInspector(inspector)) { p.Reset(inspector); } propertiesRefreshed = true; } public virtual string CalculateFinalPluginPath(string platformName, PluginImporter imp) { string cpu = imp.GetPlatformData(platformName, cpuKey); if (!string.IsNullOrEmpty(cpu) && (string.Compare(cpu, "AnyCPU", true) != 0) && (string.Compare(cpu, "None", true) != 0)) return Path.Combine(cpu, Path.GetFileName(imp.assetPath)); return Path.GetFileName(imp.assetPath); } private static bool IsPluginDefinesCompatible(PluginImporter pluginImporter, string buildTargetName, string[] defines) { var defineConstraints = pluginImporter.DefineConstraints; return DefineConstraintsHelper.IsDefineConstraintsCompatible(defines, defineConstraints); } protected Dictionary<string, List<PluginImporter>> GetCompatiblePlugins(string buildTargetName, string[] defines) { var pluginImporters = PluginImporter.GetImporters(buildTargetName); var plugins = pluginImporters .Where(pluginImporter => IsPluginDefinesCompatible(pluginImporter, buildTargetName, defines)); plugins = PluginImporter.FilterAssembliesByAssemblyVersion(plugins); var matchingPlugins = new Dictionary<string, List<PluginImporter>>(); foreach (var plugin in plugins) { string finalPluginPath = CalculateFinalPluginPath(buildTargetName, plugin); if (string.IsNullOrEmpty(finalPluginPath)) continue; if (!matchingPlugins.TryGetValue(finalPluginPath, out var pluginsList)) { pluginsList = new List<PluginImporter>(); matchingPlugins[finalPluginPath] = pluginsList; } pluginsList.Add(plugin); } return matchingPlugins; } public virtual bool CheckFileCollisions(string buildTargetName, string[] defineConstraints) { Dictionary<string, List<PluginImporter>> matchingPlugins = GetCompatiblePlugins(buildTargetName, defineConstraints); bool foundCollisions = false; StringBuilder errorMessage = new StringBuilder(); foreach (KeyValuePair<string, List<PluginImporter>> pair in matchingPlugins) { List<PluginImporter> plugins = pair.Value; // If we have only one plugin with specified final path, that means everything is ok, and no overwrite will occur if (plugins.Count == 1) continue; // Project plugins are those found inside of the User's project folder. int projectPluginCount = 0; foreach (PluginImporter importer in plugins) { if (!importer.GetIsOverridable()) { projectPluginCount++; } } // If we have a single user project plugin, it will take precedence and overwrite the others. // Anything else should throw errors if there are multiple. if (projectPluginCount == 1) continue; foundCollisions = true; // Two or more plugins are being copied to the same path, create an error message errorMessage.AppendLine(string.Format("Plugin '{0}' is used from several locations:", Path.GetFileName(pair.Key))); foreach (PluginImporter importer in plugins) { errorMessage.AppendLine(" " + importer.assetPath + " would be copied to <PluginPath>/" + pair.Key.Replace("\\", "/")); } } if (foundCollisions) { errorMessage.AppendLine("Please fix plugin settings and try again."); Debug.LogError(errorMessage.ToString()); } return foundCollisions; } } }
UnityCsReference/Editor/Mono/Modules/DefaultPluginImporterExtension.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Modules/DefaultPluginImporterExtension.cs", "repo_id": "UnityCsReference", "token_count": 4428 }
317
// 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 Math = System.Math; namespace UnityEditor { internal partial class ObjectListArea { /* Abstract base class for each group of assets (e.g. Local, AssetStore) used in the ObjectListArea */ protected abstract class Group { readonly protected float kGroupSeparatorHeight = EditorStyles.toolbar.fixedHeight; protected string m_GroupSeparatorTitle; protected static int[] s_Empty; public ObjectListArea m_Owner; public VerticalGrid m_Grid = new VerticalGrid(); public float m_Height; public float Height { get { return m_Height; } } abstract public int ItemCount { get; } abstract public bool ListMode { get; set; } abstract public bool NeedsRepaint { get; protected set; } public bool Visible = true; // Visibility toggled in GUI public int ItemsAvailable = 0; // Calculated from total asset count public int ItemsWantedShown = 0; // Rows requested to be displayed protected bool m_Collapsable = true; public double m_LastClickedDrawTime = 0; public Group(ObjectListArea owner, string groupTitle) { m_GroupSeparatorTitle = groupTitle; if (s_Empty == null) s_Empty = new int[0]; m_Owner = owner; Visible = visiblePreference; } public bool visiblePreference { get { if (string.IsNullOrEmpty(m_GroupSeparatorTitle)) return true; return EditorPrefs.GetBool(m_GroupSeparatorTitle, true); } set { if (string.IsNullOrEmpty(m_GroupSeparatorTitle)) return; EditorPrefs.SetBool(m_GroupSeparatorTitle, value); } } // Called before repaints in order to prepare internal assets for rendering abstract public void UpdateAssets(); // Called when height of this group should be recalculated abstract public void UpdateHeight(); abstract protected void DrawInternal(int itemIdx, int endItem, float yOffset); // Called when the filter has changed abstract public void UpdateFilter(HierarchyType hierarchyType, SearchFilter searchFilter, bool showFoldersFirst, SearchService.SearchSessionOptions searchSessionOptions); public void UpdateFilter(HierarchyType hierarchyType, SearchFilter searchFilter, bool showFoldersFirst) { UpdateFilter(hierarchyType, searchFilter, showFoldersFirst, SearchService.SearchSessionOptions.Default); } protected virtual float GetHeaderHeight() { return kGroupSeparatorHeight; } protected virtual void HandleUnusedDragEvents(float yOffset) {} int FirstVisibleRow(float yOffset, Vector2 scrollPos) { if (!Visible) return -1; // Skip rows that is outside the offset rect float yRelOffset = scrollPos.y - (yOffset + GetHeaderHeight()); int invisibleRows = 0; if (yRelOffset > 0f) { // Initial rows hidden float itemHeight = m_Grid.itemSize.y + m_Grid.verticalSpacing; invisibleRows = (int)Mathf.Max(0, Mathf.Floor(yRelOffset / itemHeight)); } return invisibleRows; } bool IsInView(float yOffset, Vector2 scrollPos, float scrollViewHeight) { if ((scrollPos.y + scrollViewHeight) < yOffset) return false; // after visible area if ((yOffset + Height) < scrollPos.y) return false; // before visible area return true; } // Main draw method of a group that is called from outside public void Draw(float yOffset, Vector2 scrollPos, ref int rowsInUse) { NeedsRepaint = false; // We need to always draw the header as it uses controlIDs (and we cannot cull gui elements using controlID) bool isRepaint = Event.current.type == EventType.Repaint || Event.current.type == EventType.Layout; if (!isRepaint) DrawHeader(yOffset, m_Collapsable); // logic here, draw on top below if (!IsInView(yOffset, scrollPos, m_Owner.m_VisibleRect.height)) return; int invisibleRows = FirstVisibleRow(yOffset, scrollPos); int beginItem = invisibleRows * m_Grid.columns; int totalItemCount = ItemCount; if (beginItem >= 0 && beginItem < totalItemCount) { int itemIdx = beginItem; // Limit by items avail and max items to show // (plus an extra row to allow half a row in top and bottom at the same time) int endItem = Math.Min(totalItemCount, m_Grid.rows * m_Grid.columns); // Also limit to what can possible be in view in order to limit draws float itemHeight = m_Grid.itemSize.y + m_Grid.verticalSpacing; int rowsInVisibleRect = (int)Math.Ceiling(m_Owner.m_VisibleRect.height / itemHeight); //When a row is hidden behind the header, it is still counted as visible, therefore to avoid //weird popping in and out for the icons, we make sure that a new row will be rendered even if one //is considered visible, even though it cannot be seen in the window rowsInVisibleRect += 1; int rowsNotInUse = rowsInVisibleRect - rowsInUse; if (rowsNotInUse < 0) rowsNotInUse = 0; rowsInUse = Math.Min(rowsInVisibleRect, Mathf.CeilToInt((endItem - beginItem) / (float)m_Grid.columns)); endItem = rowsNotInUse * m_Grid.columns + beginItem; if (endItem > totalItemCount) endItem = totalItemCount; DrawInternal(itemIdx, endItem, yOffset); } if (isRepaint) DrawHeader(yOffset, m_Collapsable); // Always handle drag events in the case where we have no items we still want to be able to drag into the group. HandleUnusedDragEvents(yOffset); } protected void DrawObjectIcon(Rect position, Texture icon) { if (icon == null) return; int size = icon.width; FilterMode temp = icon.filterMode; icon.filterMode = FilterMode.Point; GUI.DrawTexture(new Rect(position.x + ((int)position.width - size) / 2, position.y + ((int)position.height - size) / 2, size, size), icon, ScaleMode.ScaleToFit); icon.filterMode = temp; } protected void DrawDropShadowOverlay(Rect position, bool selected, bool isDropTarget, bool isRenaming) { // Draw dropshadow overlay float fraction = position.width / 128f; Rect dropShadowRect = new Rect(position.x - 4 * fraction, position.y - 2 * fraction, position.width + 8 * fraction, position.height + 12 * fraction - 0.5f); Styles.iconDropShadow.Draw(dropShadowRect, GUIContent.none, false, false, selected || isDropTarget, m_Owner.HasFocus() || isRenaming || isDropTarget); } protected void DrawHeaderBackground(Rect rect, bool firstHeader, bool expanded) { if (Event.current.type != EventType.Repaint) return; // Draw the group bar background (firstHeader ? Styles.groupHeaderTop : Styles.groupHeaderMiddle)?.Draw(rect, GUIContent.none, rect.Contains(Event.current.mousePosition), false, expanded, false); } protected float GetHeaderYPosInScrollArea(float yOffset) { float y = yOffset; float yScrollPos = m_Owner.m_State.m_ScrollPosition.y; if (yScrollPos > yOffset) { y = Mathf.Min(yScrollPos, yOffset + Height - kGroupSeparatorHeight); } return y; } virtual protected void DrawHeader(float yOffset, bool collapsable) { const int foldoutSpacing = 3; Rect rect = new Rect(0, GetHeaderYPosInScrollArea(yOffset), m_Owner.GetVisibleWidth(), kGroupSeparatorHeight - 1); DrawHeaderBackground(rect, yOffset == 0, Visible); // Draw the group toggle rect.x += 7; if (collapsable) { bool oldVisible = Visible; Visible = GUI.Toggle(rect, Visible, GUIContent.none, Styles.groupFoldout); if (oldVisible ^ Visible) visiblePreference = Visible; } // Draw title GUIStyle textStyle = Styles.groupHeaderLabel; if (collapsable) rect.x += Styles.groupFoldout.fixedWidth + foldoutSpacing; rect.y += 1; if (!string.IsNullOrEmpty(m_GroupSeparatorTitle)) GUI.Label(rect, m_GroupSeparatorTitle, textStyle); rect.y -= 1; // Only draw counts if we have room for it if (m_Owner.GetVisibleWidth() > 150) DrawItemCount(rect); } protected void DrawItemCount(Rect rect) { // Draw item count in group const float rightMargin = 4f; string label = ItemsAvailable + " Total"; Vector2 labelDims = Styles.groupHeaderLabelCount.CalcSize(new GUIContent(label)); if (labelDims.x < rect.width) rect.x = m_Owner.GetVisibleWidth() - labelDims.x - rightMargin; // right align if room rect.width = labelDims.x; rect.y += 2; // better y pos for minilabel GUI.Label(rect, label, Styles.groupHeaderLabelCount); } } } } // namespace UnityEditor
UnityCsReference/Editor/Mono/ObjectListGroup.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/ObjectListGroup.cs", "repo_id": "UnityCsReference", "token_count": 5231 }
318
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.Overlays { sealed class OverlayDragger : MouseManipulator { sealed class DockingOperation : IDisposable { static readonly Type[] s_PickingPriority = { typeof(ToolbarDropZone), typeof(OverlayGhostDropZone), typeof(OverlayDropZone), typeof(OverlayContainerInsertDropZone), typeof(OverlayContainerDropZone), }; const string k_OverlayDraggedState = "unity-overlay--dragged"; readonly OverlayInsertIndicator m_InsertIndicator; readonly List<OverlayDropZoneBase> m_DropZones = new(32); readonly List<VisualElement> m_PickingBuffer = new(); readonly List<OverlayDropZoneBase> m_DropZoneBuffer = new(); readonly Overlay m_TargetOverlay; readonly OverlayContainer m_OriginContainer; readonly OverlayGhostDropZone m_OriginGhostDropZone; readonly VisualElement m_CanvasRoot; OverlayDropZoneBase m_Hovered; public DockingOperation(OverlayCanvas canvas, Overlay targetOverlay) { m_InsertIndicator = new OverlayInsertIndicator(); m_OriginContainer = targetOverlay.container; m_OriginContainer.GetOverlayIndex(targetOverlay, out var section, out var index); m_TargetOverlay = targetOverlay; m_CanvasRoot = canvas.rootVisualElement; targetOverlay.rootVisualElement.AddToClassList(k_OverlayDraggedState); if (!targetOverlay.floating) { m_OriginGhostDropZone = OverlayGhostDropZone.Create(targetOverlay); m_DropZones.Add(m_OriginGhostDropZone); } //Collect dropzones m_DropZones.AddRange(canvas.dockArea.GetDropZones()); foreach (var overlay in canvas.overlays) { m_DropZones.Add(overlay.insertBeforeDropZone); m_DropZones.Add(overlay.insertAfterDropZone); } foreach (var container in canvas.containers) m_DropZones.AddRange(container.GetDropZones()); foreach (var dropZone in m_DropZones) { dropZone.Setup(m_InsertIndicator, m_OriginContainer, section); dropZone.Activate(m_TargetOverlay); } } public void UpdateHover(OverlayDropZoneBase hovered) { if (m_Hovered == hovered) return; if (m_Hovered != null) m_Hovered.EndHover(); m_Hovered = hovered; //Remove dropzone f we have a different container if (m_Hovered == null || m_Hovered.targetContainer != m_OriginContainer) m_OriginGhostDropZone?.RemoveFromHierarchy(); if (m_Hovered != null) m_Hovered.BeginHover(); foreach (var dropZone in m_DropZones) dropZone.UpdateHover(hovered); } public OverlayDropZoneBase GetOverlayDropZoneAtPosition(Vector2 mousePosition) { //get list of items under mouse m_PickingBuffer.Clear(); m_DropZoneBuffer.Clear(); m_CanvasRoot.panel.PickAll(mousePosition, m_PickingBuffer); foreach (var element in m_PickingBuffer) if (element is OverlayDropZoneBase dropZone && dropZone.CanAcceptTarget(m_TargetOverlay)) m_DropZoneBuffer.Add(dropZone); if (m_DropZoneBuffer.Count == 0) return null; //Sort by priority m_DropZoneBuffer.Sort((a, b) => Array.IndexOf(s_PickingPriority, a.GetType()).CompareTo(Array.IndexOf(s_PickingPriority, b.GetType()))); return m_DropZoneBuffer[0]; } public void Dispose() { m_TargetOverlay.rootVisualElement.RemoveFromClassList(k_OverlayDraggedState); m_Hovered?.EndHover(); foreach (var dropZone in m_DropZones) { dropZone.Deactivate(m_TargetOverlay); dropZone.Cleanup(); } m_OriginGhostDropZone?.RemoveFromHierarchy(); m_InsertIndicator.RemoveFromHierarchy(); } } bool m_Active; bool m_WasFloating; bool m_WasCollapsed; OverlayContainer m_StartContainer; Vector2 m_InitialLayoutPosition; Vector2 m_StartLeftCornerPosition; Vector2 m_StartMousePosition; readonly Overlay m_Overlay; int m_InitialIndex; OverlayContainerSection m_InitialSection; DockingOperation m_DockOperation; OverlayCanvas canvas => m_Overlay.canvas; FloatingOverlayContainer floatingContainer => canvas.floatingContainer; public OverlayDragger(Overlay overlay) { m_Overlay = overlay; activators.Add(new ManipulatorActivationFilter {button = MouseButton.LeftMouse}); activators.Add(new ManipulatorActivationFilter {button = MouseButton.LeftMouse, modifiers = EventModifiers.Control}); m_Active = false; } protected override void RegisterCallbacksOnTarget() { target.RegisterCallback<MouseDownEvent>(OnMouseDown); target.RegisterCallback<MouseUpEvent>(OnMouseUp); target.RegisterCallback<KeyDownEvent>(OnKeyDown); target.RegisterCallback<PointerCaptureOutEvent>(OnPointerCaptureOut); } protected override void UnregisterCallbacksFromTarget() { target.UnregisterCallback<MouseDownEvent>(OnMouseDown); target.UnregisterCallback<MouseMoveEvent>(OnMouseMove); target.UnregisterCallback<MouseUpEvent>(OnMouseUp); target.UnregisterCallback<KeyDownEvent>(OnKeyDown); target.UnregisterCallback<PointerCaptureOutEvent>(OnPointerCaptureOut); } bool IsInDraggableArea(Vector2 mousePosition) { return target.worldBound.Contains(mousePosition); } void OnMouseDown(MouseDownEvent e) { if (m_Active) { e.StopImmediatePropagation(); return; } if (!IsInDraggableArea(e.mousePosition) || !CanStartManipulation(e)) return; m_WasFloating = m_Overlay.floating; m_WasCollapsed = m_Overlay.collapsed; m_StartContainer = m_Overlay.container; m_DockOperation = new DockingOperation(canvas, m_Overlay); m_StartMousePosition = OverlayUtilities.ClampPositionToRect(e.mousePosition, canvas.rootVisualElement.worldBound); m_StartLeftCornerPosition = m_Overlay.rootVisualElement.Q(Overlay.draggerName).worldBound.position; m_InitialLayoutPosition = floatingContainer.WorldToLocal(m_Overlay.rootVisualElement.worldBound.position); //if docked, convert to floating if (!m_Overlay.floating) { m_Overlay.container.GetOverlayIndex(m_Overlay, out m_InitialSection, out m_InitialIndex); m_Overlay.Undock(); m_Overlay.floatingPosition = m_InitialLayoutPosition; m_Overlay.UpdateAbsolutePosition(); } m_Overlay.BringToFront(); m_Active = true; target.RegisterCallback<MouseMoveEvent>(OnMouseMove, TrickleDown.TrickleDown); target.CaptureMouse(); e.StopPropagation(); } void OnMouseMove(MouseMoveEvent e) { if (!m_Active) return; var constrainedMousePosition = OverlayUtilities.ClampPositionToRect(e.mousePosition, canvas.rootVisualElement.worldBound); var dropZone = m_DockOperation.GetOverlayDropZoneAtPosition(constrainedMousePosition); var targetContainer = dropZone != null ? dropZone.targetContainer : null; bool delayPositionUpdate = false; if (m_Overlay.tempTargetContainer != targetContainer) { var prevLayout = m_Overlay.activeLayout; m_Overlay.tempTargetContainer = targetContainer; m_Overlay.RebuildContent(); if (m_Overlay.activeLayout != prevLayout) delayPositionUpdate = true; } var diff = (constrainedMousePosition - (!m_WasCollapsed && m_Overlay.collapsed ? m_StartLeftCornerPosition : m_StartMousePosition)); var targetPosition = m_InitialLayoutPosition + diff; var targetRect = new Rect(targetPosition, m_Overlay.rootVisualElement.layout.size); if (delayPositionUpdate) m_Overlay.rootVisualElement.RegisterCallback<GeometryChangedEvent, Rect>(DelayedPositionUpdate, targetRect); else m_Overlay.rootVisualElement.transform.position = OverlayUtilities.ClampRectToRect(targetRect, floatingContainer.rect).position; m_DockOperation.UpdateHover(dropZone); e.StopPropagation(); } void DelayedPositionUpdate(GeometryChangedEvent evt, Rect targetRect) { m_Overlay.rootVisualElement.transform.position = OverlayUtilities.ClampRectToRect(targetRect, floatingContainer.rect).position; m_Overlay.rootVisualElement.UnregisterCallback<GeometryChangedEvent, Rect>(DelayedPositionUpdate); } void OnMouseUp(MouseUpEvent e) { if (!m_Active) return; if (e.button != (int)MouseButton.RightMouse && !CanStopManipulation(e)) return; e.StopPropagation(); var dropZone = m_DockOperation.GetOverlayDropZoneAtPosition(OverlayUtilities.ClampPositionToRect(e.mousePosition, canvas.rootVisualElement.worldBound)); if (dropZone != null) { if (dropZone is OverlayGhostDropZone) { CancelDrag(); return; } m_Overlay.container?.RemoveOverlay(m_Overlay); m_Overlay.rootVisualElement.transform.position = Vector2.zero; dropZone.DropOverlay(m_Overlay); } if (m_Overlay.floating) { var pos = m_Overlay.rootVisualElement.transform.position; m_Overlay.floatingPosition = new Vector2(pos.x, pos.y); } OnDragEnd(); } void OnPointerCaptureOut(PointerCaptureOutEvent evt) { if (!m_Active) return; CancelDrag(); } void OnKeyDown(KeyDownEvent evt) { if (m_Active && evt.keyCode == KeyCode.Escape) { CancelDrag(); evt.StopPropagation(); } } void CancelDrag() { if (m_WasFloating) { m_Overlay.rootVisualElement.transform.position = m_InitialLayoutPosition; } else { m_Overlay.DockAt(m_StartContainer, m_InitialSection, m_InitialIndex); } OnDragEnd(); m_Overlay.RebuildContent(); } void OnDragEnd() { m_Active = false; target.ReleaseMouse(); target.UnregisterCallback<MouseMoveEvent>(OnMouseMove); m_Overlay.rootVisualElement.UnregisterCallback<GeometryChangedEvent, Rect>(DelayedPositionUpdate); //Ensure we kill any delayed position update that was still in process m_Overlay.tempTargetContainer = null; m_DockOperation.Dispose(); m_DockOperation = null; } } }
UnityCsReference/Editor/Mono/Overlays/OverlayDragger.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Overlays/OverlayDragger.cs", "repo_id": "UnityCsReference", "token_count": 5953 }
319
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using UnityEditor.Toolbars; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.Overlays { public abstract class ToolbarOverlay : Overlay, ICreateToolbar { readonly string[] m_ToolbarElementIds; public virtual IEnumerable<string> toolbarElements => m_ToolbarElementIds; protected ToolbarOverlay(params string[] toolbarElementIds) { m_ToolbarElementIds = toolbarElementIds ?? Array.Empty<string>(); } [Obsolete("Use Overlay.CreateContent(Layout.Horizontal)")] public VisualElement CreateHorizontalToolbarContent() => CreatePanelContent(); [Obsolete("Use Overlay.CreateContent(Layout.Vertical)")] public VisualElement CreateVerticalToolbarContent() => CreatePanelContent(); public override VisualElement CreatePanelContent() { return new EditorToolbar(toolbarElements, containerWindow).rootVisualElement; } } }
UnityCsReference/Editor/Mono/Overlays/ToolbarOverlay.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Overlays/ToolbarOverlay.cs", "repo_id": "UnityCsReference", "token_count": 405 }
320
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Linq; using System.Collections.Generic; using UnityEngine.Bindings; using UnityEngine; using UnityEditor; using UnityEditor.Build; namespace UnityEditor { internal struct PlatformIconStruct { [NativeName("m_Width")] public int Width; [NativeName("m_Height")] public int Height; [NativeName("m_Kind")] public int Kind; [NativeName("m_SubKind")] public string SubKind; [NativeName("m_Textures")] public Texture2D[] Textures; } internal struct LegacyPlatformIcon { [NativeName("m_Icon")] public Texture2D Icon; [NativeName("m_Width")] public int Width; [NativeName("m_Height")] public int Height; [NativeName("m_Kind")] public IconKind Kind; } internal struct LegacyBuildTargetIcons { [NativeName("m_BuildTarget")] public string BuildTarget; [NativeName("m_Icons")] public LegacyPlatformIcon[] Icons; } internal struct BuildTargetIcons { [NativeName("m_BuildTarget")] public string BuildTarget; [NativeName("m_Icons")] public PlatformIconStruct[] Icons; } public class PlatformIcon { internal List<Texture2D> m_Textures; private Texture2D[] m_PreviewTextures; public int layerCount { get { return m_Textures.Count; } set { value = Math.Clamp(value, minLayerCount, maxLayerCount); if (value < m_Textures.Count) m_Textures.RemoveRange(value, m_Textures.Count - 1); else if (value > m_Textures.Count) m_Textures.AddRange(new Texture2D[value - m_Textures.Count]); } } public int maxLayerCount { get; private set; } public int minLayerCount { get; private set; } internal string description { get; private set; } public int width { get; private set; } public int height { get; private set; } internal bool draggable { get; set; } public PlatformIconKind kind { get; private set; } internal string iconSubKind { get; private set; } internal PlatformIconStruct GetPlatformIconStruct() { PlatformIconStruct platformIconStruct = new PlatformIconStruct(); platformIconStruct.Textures = m_Textures.ToArray(); platformIconStruct.Width = width; platformIconStruct.Height = height; platformIconStruct.Kind = kind.kind; platformIconStruct.SubKind = iconSubKind; return platformIconStruct; } internal bool IsEmpty() { return m_Textures.Count(t => t != null) == 0; } internal static PlatformIcon[] GetRequiredPlatformIconsByType(PlatformIconKind kind, IReadOnlyDictionary<PlatformIconKind, PlatformIcon[]> requiredIcons) { if (kind != PlatformIconKind.Any) return requiredIcons[kind]; return requiredIcons.Values.SelectMany(i => i).ToArray(); } internal PlatformIcon(int width, int height, int minLayerCount, int maxLayerCount, string iconSubKind, string description, PlatformIconKind kind, bool draggable = true) { this.width = width; this.height = height; this.iconSubKind = iconSubKind; this.description = description; this.minLayerCount = minLayerCount; this.maxLayerCount = maxLayerCount; this.kind = kind; this.draggable = draggable; m_Textures = new List<Texture2D>(); } public Texture2D GetTexture(int layer = 0) { if (layer < 0 || layer >= maxLayerCount) throw new ArgumentOutOfRangeException($"Attempting to retrieve icon layer {layer}, while the icon only contains {layerCount} layers!"); return layer < layerCount ? m_Textures[layer] : null; } public Texture2D[] GetTextures() { return m_Textures.ToArray(); } internal void SetPreviewTextures(Texture2D[] textures) { m_PreviewTextures = textures; } internal Texture2D[] GetPreviewTextures() { return m_PreviewTextures; } public void SetTexture(Texture2D texture, int layer = 0) { if (layer < 0 || layer >= maxLayerCount) { throw new ArgumentOutOfRangeException($"Attempting to set icon layer {layer}, while icon only supports {maxLayerCount} layers!"); } if (layer > m_Textures.Count - 1) { for (int i = m_Textures.Count; i <= layer; i++) m_Textures.Add(null); } m_Textures[layer] = texture; } public void SetTextures(params Texture2D[] textures) { if (textures == null || textures.Length == 0 || textures.Count(t => t != null) == 0) { m_Textures.Clear(); return; } else if (textures.Length > maxLayerCount || textures.Length < minLayerCount) { throw new InvalidOperationException($"Attempting to assign an incorrect amount of layers to an PlatformIcon, trying to assign {textures.Length} textures while the Icon requires atleast {minLayerCount} but no more than {maxLayerCount} layers"); } m_Textures = textures.ToList(); } internal int GetValidLayerCount() { var validLayerCount = m_Textures.Count(t => t != null); var previewTexturesCount = GetPreviewTextures().Count(t => t != null); return Math.Max(previewTexturesCount, validLayerCount); } public override string ToString() { return UnityString.Format("({0}x{1}) {2}", width, height, description); } } public class PlatformIconKind { internal static readonly PlatformIconKind Any = new PlatformIconKind(-1, "Any", "", NamedBuildTarget.Unknown); internal int kind { get; private set; } internal string platform { get; private set; } internal string[] customLayerLabels { get; private set; } internal string description { get; set; } private string kindString { get; set; } internal PlatformIconKind(int kind, string kindString, string description, NamedBuildTarget platform, string[] customLayerLabels = null) { this.kind = kind; this.platform = platform.TargetName; this.kindString = kindString; this.customLayerLabels = customLayerLabels; this.description = description; } public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) return false; return kind == ((PlatformIconKind)obj).kind && platform == ((PlatformIconKind)obj).platform; } public override int GetHashCode() { return kind.GetHashCode(); } public override string ToString() { return kindString; } } [NativeHeader("Runtime/Misc/PlayerSettings.h")] public partial class PlayerSettings : UnityEngine.Object { // TODO: once we move the icon stuff to a common editor plugin, move it there as well internal static void InitIconsStructs(NamedBuildTarget buildTarget) { // This forces icon structures to be initialized in PlayerSettings on Editor start if needed // If we don't do this, the following might happen: // * Create new project // * ProjectSettings.asset will have its m_BuildTargetPlatformIcons structure empty // * But once you build to Android/iOS/tvOS or any platform which uses IIconPlatformProperties, it will initialize m_BuildTargetPlatformIcons // * Causing ProjectSettings.asset to change after you clicked build // * This is bad for incremental builds, at least for the 2nd/sequential build, it will see that ProjectSettings.asset has changed and will start rebuilding resources if (!BuildTargetDiscovery.TryGetBuildTarget(BuildPipeline.GetBuildTargetByName(buildTarget.TargetName), out var iBuildTarget)) return; var requiredIcons = iBuildTarget.IconPlatformProperties?.GetRequiredPlatformIcons(); if (requiredIcons == null) return; foreach(var icon in requiredIcons.Keys) { // Init the internal structures with empty icons GetPlatformIcons(buildTarget, icon); } } internal static PlatformIcon[] GetPlatformIconsFromStruct(PlatformIcon[] icons, PlatformIconKind kind, PlatformIconStruct[] serializedIcons) { foreach (var icon in icons) { foreach (var serializedIcon in serializedIcons) { var requiredKind = kind.Equals(PlatformIconKind.Any) ? (int)serializedIcon.Kind : kind.kind; if (icon.kind.kind != requiredKind || icon.iconSubKind != serializedIcon.SubKind) continue; if (icon.width != serializedIcon.Width || icon.height != serializedIcon.Height) continue; var serializedTextures = serializedIcon.Textures.Take(icon.maxLayerCount).ToArray(); var textures = new Texture2D[serializedTextures.Length > icon.minLayerCount ? serializedTextures.Length : icon.minLayerCount]; for (int i = 0; i < serializedTextures.Length; i++) textures[i] = serializedTextures[i]; icon.SetTextures(textures); break; } } return icons; } [Obsolete("Use GetPlatformIcons(NamedBuildTarget , PlatformIconKind) instead")] public static PlatformIcon[] GetPlatformIcons(BuildTargetGroup platform, PlatformIconKind kind) => GetPlatformIcons(NamedBuildTarget.FromBuildTargetGroup(platform), kind); // Loops through 'requiredIconSlots' and fills it with icons that are already serialized. public static PlatformIcon[] GetPlatformIcons(NamedBuildTarget buildTarget, PlatformIconKind kind) { if (!BuildTargetDiscovery.TryGetBuildTarget(BuildPipeline.GetBuildTargetByName(buildTarget.TargetName), out var iBuildTarget)) return Array.Empty<PlatformIcon>(); var requiredIcons = iBuildTarget.IconPlatformProperties?.GetRequiredPlatformIcons(); if (requiredIcons == null) return Array.Empty<PlatformIcon>(); var icons = PlatformIcon.GetRequiredPlatformIconsByType(kind, requiredIcons); var serializedIcons = GetPlatformIconsInternal(buildTarget.TargetName, kind.kind); if (serializedIcons.Length <= 0) { ImportLegacyIcons(buildTarget.TargetName, kind, icons); SetPlatformIcons(buildTarget, kind, icons); foreach (var icon in icons) if (icon.IsEmpty()) icon.SetTextures(null); } else { icons = GetPlatformIconsFromStruct(icons, kind, serializedIcons); } return icons; } [Obsolete("Use SetPlatformIcons(NamedBuildTarget , PlatformIconKind) instead")] public static void SetPlatformIcons(BuildTargetGroup platform, PlatformIconKind kind, PlatformIcon[] icons) => SetPlatformIcons(NamedBuildTarget.FromBuildTargetGroup(platform), kind, icons); public static void SetPlatformIcons(NamedBuildTarget buildTarget, PlatformIconKind kind, PlatformIcon[] icons) { if (!BuildTargetDiscovery.TryGetBuildTarget(BuildPipeline.GetBuildTargetByName(buildTarget.TargetName), out var iBuildTarget)) return; var requiredIcons = iBuildTarget.IconPlatformProperties?.GetRequiredPlatformIcons(); if (requiredIcons == null) return; var requiredIconCount = PlatformIcon.GetRequiredPlatformIconsByType(kind, requiredIcons).Length; PlatformIconStruct[] iconStructs; if (icons == null) iconStructs = new PlatformIconStruct[0]; else if (requiredIconCount != icons.Length) { throw new InvalidOperationException($"Attempting to set an incorrect number of icons for {buildTarget.TargetName} {kind} kind, it requires {requiredIconCount} icons but trying to assign {icons.Length}."); } else { iconStructs = icons.Select( i => i.GetPlatformIconStruct() ).ToArray(); } SetPlatformIconsInternal(buildTarget.TargetName, iconStructs, kind.kind); } [Obsolete("Use GetSupportedIconKinds(NamedBuildTarget) instead")] public static PlatformIconKind[] GetSupportedIconKindsForPlatform(BuildTargetGroup platform) => GetSupportedIconKinds(NamedBuildTarget.FromBuildTargetGroup(platform)); public static PlatformIconKind[] GetSupportedIconKinds(NamedBuildTarget buildTarget) { if (BuildTargetDiscovery.TryGetBuildTarget(BuildPipeline.GetBuildTargetByName(buildTarget.TargetName), out var iBuildTarget)) { var requiredIcons = iBuildTarget.IconPlatformProperties?.GetRequiredPlatformIcons(); if (requiredIcons != null) return requiredIcons.Keys.ToArray(); } return new PlatformIconKind[] { }; } internal static int GetNonEmptyPlatformIconCount(PlatformIcon[] icons) { return icons.Count(i => !i.IsEmpty()); } internal static int GetValidPlatformIconCount(PlatformIcon[] icons) { return icons.Count( i => i.GetTextures().Count(t => t != null) >= i.minLayerCount && i.layerCount <= i.maxLayerCount ); } [StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)] [NativeMethod(Name = "SetIconsForPlatform")] extern internal static void SetPlatformIconsInternal(string platform, PlatformIconStruct[] icons, int kind); [StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)] extern internal static LegacyBuildTargetIcons[] SetPlatformIconsForTargetIcons(string platform, Texture2D[] icons, IconKind kind, LegacyBuildTargetIcons[] allIcons); [StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)] extern internal static BuildTargetIcons[] SetIconsForPlatformForTargetIcons(string platform, PlatformIconStruct[] icons, int kind, BuildTargetIcons[] allIcons); [StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)] [NativeMethod(Name = "GetIconsForPlatform")] extern internal static PlatformIconStruct[] GetPlatformIconsInternal(string platform, int kind); [StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)] extern internal static Texture2D[] GetPlatformIconsForTargetIcons(string platform, IconKind kind, LegacyBuildTargetIcons[] allIcons); [StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)] [NativeMethod(Name = "GetIconsForPlatformFromTargetIcons")] extern internal static PlatformIconStruct[] GetPlatformIconsFromTargetIcons(string platform, int kind, BuildTargetIcons[] allIcons); extern internal static Texture2D GetPlatformIconForSize(string platform, int width, int height, IconKind kind = IconKind.Application); // Get the texture that will be used as the display icon at a specified size for the specified platform. internal static extern Texture2D GetPlatformIconForSizeForTargetIcons(string platform, int width, int height, IconKind kind, LegacyBuildTargetIcons[] allIcons); // Get the texture that will be used as the display icon at a specified size for the specified platform. [StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)] extern internal static Texture2D GetPlatformIconAtSize(string platform, int width, int height, int kind, string subKind = "", int layer = 0); // Get the texture that will be used as the display icon at a specified size for the specified platform. [StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)] extern internal static Texture2D GetPlatformIconAtSizeForTargetIcons(string platform, int width, int height, BuildTargetIcons[] allIcons, int kind, string subKind = "", int layer = 0); internal static void ClearSetIconsForPlatform(NamedBuildTarget buildTarget) { SetPlatformIcons(buildTarget, PlatformIconKind.Any, null); } // Old API methods, will be made obsolete when the new API is implemented for all platforms, // currently it functions as a wrapper for the new API for all platforms that support it (iOS, Android & tvOS). [Obsolete("Use SetIcons(NamedBuildTarget, Texture2D[], IconKind) instead")] public static void SetIconsForTargetGroup(BuildTargetGroup platform, Texture2D[] icons, IconKind kind) => SetIcons(NamedBuildTarget.FromBuildTargetGroup(platform), icons, kind); public static void SetIcons(NamedBuildTarget buildTarget, Texture2D[] icons, IconKind kind) { if (BuildTargetDiscovery.TryGetBuildTarget(BuildPipeline.GetBuildTargetByName(buildTarget.TargetName), out var iBuildTarget)) { var platformIconKind = iBuildTarget.IconPlatformProperties?.GetPlatformIconKindFromEnumValue(kind); if (platformIconKind != null) { PlatformIcon[] platformIcons = GetPlatformIcons(buildTarget, platformIconKind); for (var i = 0; i < icons.Length; i++) platformIcons[i].SetTexture(icons[i], 0); SetPlatformIcons(buildTarget, platformIconKind, platformIcons); } } else SetIconsForPlatform(buildTarget.TargetName, icons, kind); } [Obsolete("Use SetIcons(NamedBuildTarget, Texture2D[], IconKind) instead")] // Assign a list of icons for the specified platform. public static void SetIconsForTargetGroup(BuildTargetGroup platform, Texture2D[] icons) => SetIcons(NamedBuildTarget.FromBuildTargetGroup(platform), icons, IconKind.Any); // Returns the list of assigned icons for the specified platform of a specific kind. [Obsolete("Use GetIcons(NamedBuildTarget, IconKind) instead")] public static Texture2D[] GetIconsForTargetGroup(BuildTargetGroup platform, IconKind kind) => GetIcons(NamedBuildTarget.FromBuildTargetGroup(platform), kind); public static Texture2D[] GetIcons(NamedBuildTarget buildTarget, IconKind kind) { if (BuildTargetDiscovery.TryGetBuildTarget(BuildPipeline.GetBuildTargetByName(buildTarget.TargetName), out var iBuildTarget)) { var platformIconKind = iBuildTarget.IconPlatformProperties?.GetPlatformIconKindFromEnumValue(kind); return platformIconKind == null ? GetIconsForPlatform(iBuildTarget.TargetName, kind) : GetPlatformIcons(buildTarget, platformIconKind).Select(t => t.GetTexture(0)).ToArray(); } return PlayerSettings.GetIconsForPlatform(buildTarget.TargetName, kind); } internal static void ImportLegacyIcons(string platform, PlatformIconKind kind, PlatformIcon[] platformIcons) { if (!Enum.IsDefined(typeof(IconKind), kind.kind)) return; IconKind iconKind = (IconKind)kind.kind; Texture2D[] legacyIcons = GetIconsForPlatform(platform, iconKind); int[] legacyIconWidths = GetIconWidthsForPlatform(platform, iconKind); int[] legacyIconHeights = GetIconHeightsForPlatform(platform, iconKind); for (var i = 0; i < legacyIcons.Length; i++) { foreach (var icon in platformIcons) { if (icon.width == legacyIconWidths[i] && icon.height == legacyIconHeights[i]) { icon.SetTextures(legacyIcons[i]); } } } } internal static void ImportLegacyIcons(BuildTargetGroup platform, PlatformIconKind kind, PlatformIcon[] platformIcons) { ImportLegacyIcons(GetPlatformName(platform), kind, platformIcons); } // Returns the list of assigned icons for the specified platform. [Obsolete("Use GetIcons(NamedBuildTarget, IconKind) instead")] public static Texture2D[] GetIconsForTargetGroup(BuildTargetGroup platform) => GetIcons(NamedBuildTarget.FromBuildTargetGroup(platform), IconKind.Any); // Returns a list of icon sizes for the specified platform of a specific kind. [Obsolete("Use GetIconSizes(NamedBuildTarget, IconKind) instead")] public static int[] GetIconSizesForTargetGroup(BuildTargetGroup platform, IconKind kind) => GetIconSizes(NamedBuildTarget.FromBuildTargetGroup(platform), kind); public static int[] GetIconSizes(NamedBuildTarget buildTarget, IconKind kind) { if (BuildTargetDiscovery.TryGetBuildTarget(BuildPipeline.GetBuildTargetByName(buildTarget.TargetName), out var iBuildTarget)) { var platformIconKind = iBuildTarget.IconPlatformProperties?.GetPlatformIconKindFromEnumValue(kind); return platformIconKind == null ? GetIconWidthsForPlatform(iBuildTarget.TargetName, kind) : GetPlatformIcons(buildTarget, platformIconKind).Select(s => s.width).ToArray(); } return GetIconWidthsForPlatform(buildTarget.TargetName, kind); } // Returns a list of icon sizes for the specified platform. [Obsolete("Use GetIconSizes(NamedBuildTarget) instead")] public static int[] GetIconSizesForTargetGroup(BuildTargetGroup platform) => GetIconSizes(NamedBuildTarget.FromBuildTargetGroup(platform), IconKind.Any); } }
UnityCsReference/Editor/Mono/PlatformSupport/PlayerSettingsPlatformIcons.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/PlatformSupport/PlayerSettingsPlatformIcons.bindings.cs", "repo_id": "UnityCsReference", "token_count": 9374 }
321
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Collections; using UnityEngine.Bindings; namespace UnityEditor { public partial class PlayerSettings : UnityEngine.Object { [Obsolete("Facebook support was removed in 2019.3", true)] public partial class Facebook { public static string sdkVersion { get { throw new NotImplementedException("Facebook support was removed in 2019.3"); } set { throw new NotImplementedException("Facebook support was removed in 2019.3"); } } public static string appId { get { throw new NotImplementedException("Facebook support was removed in 2019.3"); } set { throw new NotImplementedException("Facebook support was removed in 2019.3"); } } public static bool useCookies { get { throw new NotImplementedException("Facebook support was removed in 2019.3"); } set { throw new NotImplementedException("Facebook support was removed in 2019.3"); } } internal static bool useLogging { get { throw new NotImplementedException("Facebook support was removed in 2019.3"); } set { throw new NotImplementedException("Facebook support was removed in 2019.3"); } } public static bool useStatus { get { throw new NotImplementedException("Facebook support was removed in 2019.3"); } set { throw new NotImplementedException("Facebook support was removed in 2019.3"); } } internal static bool useXfbml { get { throw new NotImplementedException("Facebook support was removed in 2019.3"); } set { throw new NotImplementedException("Facebook support was removed in 2019.3"); } } public static bool useFrictionlessRequests { get { throw new NotImplementedException("Facebook support was removed in 2019.3"); } set { throw new NotImplementedException("Facebook support was removed in 2019.3"); } } } } }
UnityCsReference/Editor/Mono/PlayerSettingsFacebook.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/PlayerSettingsFacebook.bindings.cs", "repo_id": "UnityCsReference", "token_count": 985 }
322
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEditor; namespace UnityEditorInternal { internal struct PluginDesc { public string pluginPath; public CPUArch architecture; } internal enum CPUArch { Any, x86, ARMv7 } }
UnityCsReference/Editor/Mono/PluginDesc.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/PluginDesc.cs", "repo_id": "UnityCsReference", "token_count": 160 }
323
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using System; using System.IO; using UnityEditor.Utils; using UnityEngine.Bindings; using Object = UnityEngine.Object; using UnityEngine.SceneManagement; namespace UnityEditor { [NativeHeader("Editor/Src/Prefabs/Prefab.h")] [NativeHeader("Editor/Src/Prefabs/PrefabCreation.h")] [NativeHeader("Editor/Src/Prefabs/PrefabConnection.h")] [NativeHeader("Editor/Src/Prefabs/PrefabInstance.h")] [NativeHeader("Editor/Src/Prefabs/ReplacePrefabInstance.h")] [NativeHeader("Editor/Mono/Prefabs/PrefabUtility.bindings.h")] public sealed partial class PrefabUtility { [StaticAccessor("PrefabInstance", StaticAccessorType.DoubleColon)] extern internal static int defaultOverridesCount { get; } [StaticAccessor("PrefabInstance", StaticAccessorType.DoubleColon)] extern internal static int defaultOverridesCountUsingRectTransform { get; } // Returns the corresponding GameObject/Component from /source/, or null if it can't be found. [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern private static Object GetCorrespondingObjectFromSource_internal([NotNull] Object obj); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern private static Object GetCorrespondingObjectFromSourceInAsset_internal([NotNull] Object obj, [NotNull] Object prefabAssetHandle); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern private static Object GetCorrespondingObjectFromSourceAtPath_internal([NotNull] Object obj, string prefabAssetPath); // Retrieves the prefab object representation. [Obsolete("Use GetPrefabInstanceHandle for Prefab instances. Handles for Prefab Assets has been discontinued.")] [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern public static Object GetPrefabObject(Object targetObject); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern public static Object GetPrefabInstanceHandle(Object instanceComponentOrGameObject); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern internal static string GetAssetPathOfSourcePrefab(Object targetObject); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern internal static Object GetPrefabAssetHandle(Object assetComponentOrGameObject); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] extern public static bool HasManagedReferencesWithMissingTypes(Object assetComponentOrGameObject); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern internal static GameObject GetPrefabInstanceRootGameObject(Object instanceComponentOrGameObject); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern internal static GameObject GetPrefabAssetRootGameObject(Object assetComponentOrGameObject); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern internal static bool HasObjectOverride(Object componentOrGameObject, bool includeDefaultOverrides = false); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern internal static bool HasPrefabInstanceUnusedOverrides_Internal(GameObject gameObject); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern internal static int GetPrefabInstanceUnusedRemovedComponentCount_Internal(GameObject gameObject); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern internal static int GetPrefabInstanceUnusedRemovedGameObjectCount_Internal([NotNull] GameObject gameObject); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern internal static string TryGetCurrentPropertyPathFromOldPropertyPath_Internal(GameObject gameObject, Object target, string propertyPath); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern internal static bool HasPrefabInstanceNonDefaultOverrides_CachedForUI_Internal(GameObject gameObject); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern internal static bool HasPrefabInstanceUnusedOverrides_CachedForUI_Internal(GameObject gameObject); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern internal static void ClearPrefabInstanceNonDefaultOverridesCache_Internal(GameObject gameObject); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern internal static void ClearPrefabInstanceUnusedOverridesCache_Internal(GameObject gameObject); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern internal static InstanceOverridesInfo GetPrefabInstanceOverridesInfo_Internal(GameObject gameObject); // Extract all modifications that are applied to the prefab instance compared to the parent prefab. [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern public static PropertyModification[] GetPropertyModifications(Object targetPrefab); // Assigns all modifications that are applied to the prefab instance compared to the parent prefab. [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern public static void SetPropertyModifications(Object targetPrefab, PropertyModification[] modifications); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] extern internal static bool HasApplicableObjectOverridesForTarget([NotNull] Object targetPrefab, [NotNull] Object applyTarget, bool includeDefaultOverrides); [NativeMethod("PrefabUtilityBindings::FindNearestInstanceOfAsset", IsFreeFunction = true)] extern internal static GameObject FindNearestInstanceOfAsset(Object componentOrGameObjectInstance, Object prefab); [FreeFunction] extern public static bool HasPrefabInstanceAnyOverrides(GameObject instanceRoot, bool includeDefaultOverrides); // Instantiate an asset that is referenced by a prefab and use it on the prefab instance. [Obsolete("InstantiateAttachedAsset is deprecated")] public static Object InstantiateAttachedAsset(Object targetObject) { return null; } // Force record property modifications by comparing against the parent prefab. [FreeFunction] extern public static void RecordPrefabInstancePropertyModifications([NotNull] Object targetObject); // Force re-merging all prefab instances of this prefab. [Obsolete("MergeAllPrefabInstances is deprecated. Prefabs are merged automatically. There is no need to call this method.")] [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] extern public static void MergeAllPrefabInstances(Object targetObject); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] extern private static void MergePrefabInstance_internal([NotNull] Object gameObjectOrComponent); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] extern private static MergeStatus GetMergeStatus(GameObject componentOrGameObject); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] extern private static GameObject[] FindAllInstancesOfPrefab_internal([NotNull] GameObject prefabRoot, int sceneHandle); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] extern private static GameObject[] UnpackPrefabInstanceAndReturnNewOutermostRoots_internal(GameObject instanceRoot, PrefabUnpackMode unpackMode); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] extern static private Object InstantiatePrefab_internal(Object target, Scene destinationScene, Transform parent); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] extern static private bool ReplacePrefabAssetOfPrefabInstance_Internal([NotNull] GameObject instanceRoot, [NotNull] GameObject assetRootRoot, PrefabReplacingSettings settings); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] extern static private bool ConvertToPrefabInstance_Internal([NotNull] GameObject plainGameObject, [NotNull] GameObject assetRootRoot, ConvertToPrefabInstanceSettings settings); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] extern static private bool InstantiateDraggedPrefabUpon_Internal([NotNull] GameObject draggedUponGameObject, [NotNull] GameObject assetRootRoot); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] extern public static void LoadPrefabContentsIntoPreviewScene(string prefabPath, Scene scene); [Obsolete("Use ConvertToPrefabInstance() or ReplacePrefabAssetOfPrefabInstance() which has settings for better control.")] public static GameObject ConnectGameObjectToPrefab(GameObject go, GameObject sourcePrefab) { if (GetPrefabInstanceStatus(go) == PrefabInstanceStatus.NotAPrefab) { var settings = new ConvertToPrefabInstanceSettings(); ConvertToPrefabInstance(go, sourcePrefab, settings, InteractionMode.AutomatedAction); } else if (IsOutermostPrefabInstanceRoot(go)) { var settings = new PrefabReplacingSettings(); ReplacePrefabAssetOfPrefabInstance(go, sourcePrefab, settings, InteractionMode.AutomatedAction); } return go; } // Returns the topmost game object that has the same prefab parent as /target/ [FreeFunction] [Obsolete("FindRootGameObjectWithSameParentPrefab is deprecated, please use GetOutermostPrefabInstanceRoot instead.")] extern public static GameObject FindRootGameObjectWithSameParentPrefab([NotNull] GameObject target); // Returns root game object of the prefab instance. Given an instance object the function finds the prefab // and uses the prefab root game object to find the matching instance root game object [NativeMethod("FindInstanceRootGameObject", IsFreeFunction = true)] [Obsolete("FindValidUploadPrefabInstanceRoot is deprecated, please use GetOutermostPrefabInstanceRoot instead.")] extern public static GameObject FindValidUploadPrefabInstanceRoot([NotNull] GameObject target); // Resets the properties of the component or game object to the parent prefab state [Obsolete("Use RevertObjectOverride.")] [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern public static bool ResetToPrefabState(Object obj); // Resets the properties of the component or game object to the parent prefab state [NativeMethod("PrefabUtilityBindings::ResetToPrefabState", IsFreeFunction = true)] extern private static bool RevertObjectOverride_Internal(Object obj); [FreeFunction] extern public static bool IsAddedComponentOverride([NotNull] Object component); // Resets the properties of all objects in the prefab, including child game objects and components that were added to the prefab instance [Obsolete("Use the overload that takes an InteractionMode parameter.")] [FreeFunction] extern public static bool RevertPrefabInstance([NotNull] GameObject go); // Resets the properties of all objects in the prefab, including child game objects and components that were added to the prefab instance [NativeMethod("RevertPrefabInstance", IsFreeFunction = true)] extern private static bool RevertPrefabInstance_Internal([NotNull] GameObject go); // Helper function to find the prefab root of an object [FreeFunction] [Obsolete("Use GetOutermostPrefabInstanceRoot if source is a Prefab instance or source.transform.root.gameObject if source is a Prefab Asset object.")] extern public static GameObject FindPrefabRoot([NotNull] GameObject source); internal static GameObject CreateVariant(GameObject assetRoot, string path) { if (assetRoot == null) throw new ArgumentNullException("The inputObject is null"); if (!IsPartOfPrefabAsset(assetRoot)) throw new ArgumentException("Given input object is not a prefab asset"); if (assetRoot.transform.root.gameObject != assetRoot) throw new ArgumentException("Object to create variant from has to be a Prefab root"); if (path == null) throw new ArgumentNullException("The path is null"); var assetRootObjectPath = AssetDatabase.GetAssetPath(assetRoot); if (Paths.AreEqual(path, assetRootObjectPath, true)) throw new ArgumentException("Creating a variant of an object into the source file of the input object is not allowed"); if (!Paths.IsValidAssetPath(path, ".prefab")) throw new ArgumentException("Given path is not valid: '" + path + "'"); return CreateVariant_Internal(assetRoot, path); } [NativeMethod("CreateVariant", IsFreeFunction = true)] extern private static GameObject CreateVariant_Internal([NotNull] GameObject original, string path); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] extern private static GameObject SavePrefab_Internal([NotNull] GameObject root, string path, bool connectToInstance, out bool success); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern private static GameObject ApplyPrefabInstance_Internal([NotNull] GameObject root); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] extern private static GameObject SaveAsPrefabAsset_Internal([NotNull] GameObject root, string path, out bool success); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] extern private static GameObject SaveAsPrefabAssetAndConnect_Internal([NotNull] GameObject root, string path, out bool success); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] extern private static GameObject SavePrefabAsset_Internal([NotNull] GameObject root, out bool success); internal static void AddGameObjectsToPrefabAndConnect(GameObject[] gameObjects, Object targetPrefab) { if (gameObjects == null) throw new ArgumentNullException("gameObjects"); if (gameObjects.Length == 0) throw new ArgumentException("gameObjects array is empty"); if (targetPrefab == null) throw new ArgumentNullException("targetPrefab"); if (!PrefabUtility.IsPartOfPrefabAsset(targetPrefab)) throw new ArgumentException("Target Prefab has to be a Prefab Asset"); Object targetPrefabInstance = null; var targetPrefabObject = PrefabUtility.GetPrefabAssetHandle(targetPrefab); foreach (GameObject go in gameObjects) { if (go == null) throw new ArgumentException("GameObject in input 'gameObjects' array is null"); if (EditorUtility.IsPersistent(go)) // Prefab asset throw new ArgumentException("Game object is part of a prefab"); var parentPrefabInstance = GetParentPrefabInstance(go); if (parentPrefabInstance == null) throw new ArgumentException("GameObject is not (directly) parented under a target Prefab instance."); if (targetPrefabInstance == null) { targetPrefabInstance = parentPrefabInstance; if (!IsPrefabInstanceObjectOf(go.transform.parent, targetPrefabObject)) throw new ArgumentException("GameObject is not parented under a target Prefab instance."); } else { if (parentPrefabInstance != targetPrefabInstance) { throw new ArgumentException("GameObjects must be parented under the same Prefab instance."); } } if (PrefabUtility.IsPartOfNonAssetPrefabInstance(go)) { var correspondingGO = PrefabUtility.GetCorrespondingObjectFromSource(go); var correspondingGOPrefabObject = PrefabUtility.GetPrefabAssetHandle(correspondingGO); if (targetPrefabObject == correspondingGOPrefabObject) throw new ArgumentException("GameObject is already part of target prefab"); } } string prefabGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(targetPrefab)); if (!VerifyNestingFromScript(gameObjects, prefabGUID, null)) throw new ArgumentException("Cyclic nesting detected"); AddGameObjectsToPrefabAndConnect_Internal(gameObjects, targetPrefab); } [NativeMethod("AddGameObjectsToPrefabAndConnect", IsFreeFunction = true)] extern private static void AddGameObjectsToPrefabAndConnect_Internal([NotNull] GameObject[] gameObjects, [NotNull] Object prefab); [NativeMethod("VerifyNestingFromScript", IsFreeFunction = true)] extern private static bool VerifyNestingFromScript([NotNull] GameObject[] gameObjects, [NotNull] string targetPrefabGUID, Object prefabInstance); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] extern internal static Component[] GetRemovedComponents([NotNull] Object prefabInstance); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] extern static void SetRemovedComponents([NotNull] Object prefabInstance, [NotNull] Component[] removedComponents); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] extern internal static GameObject[] GetRemovedGameObjects([NotNull] Object prefabInstance); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] extern static void SetRemovedGameObjects([NotNull] Object prefabInstance, [NotNull] GameObject[] removedGameObjects); // Returns true if the object is part of a any type of prefab, asset or instance [FreeFunction] extern public static bool IsPartOfAnyPrefab([NotNull] Object componentOrGameObject); [FreeFunction] extern internal static void SetHasSubscribersToAllowRecordingPrefabPropertyOverrides(bool hasSubscribers); // Returns true if the object is an asset, // does not matter if the asset is a regular prefab, a variant or Model // Is false for all non-persistent objects [FreeFunction] extern public static bool IsPartOfPrefabAsset([NotNull] Object componentOrGameObject); // Returns true if the object is an instance of a prefab, // regardless of whether the instance is a regular prefab, a variant or model. // Also returns if the asset is missing. // Is also true for prefab instances inside persistent prefab assets - // use IsPartOfNonAssetPrefabInstance to exclude those. [FreeFunction] extern public static bool IsPartOfPrefabInstance([NotNull] Object componentOrGameObject); // Returns true if the object is an instance of a prefab, // regardless of whether the instance is a regular prefab, a variant or model. // Also returns true if the asset is missing. // Is false for prefab instances inside persistent prefab assets - // use IsPartOfPrefabInstance to include those. // Note that prefab instances in prefab mode are not assets/persistent since technically, // the object edited in Prefab Mode is not the persistent prefab asset itself. [FreeFunction] extern public static bool IsPartOfNonAssetPrefabInstance([NotNull] Object componentOrGameObject); // We need a version of IsPartOfNonAssetPrefabInstance that uses an instanceID in order to handle missing monobehaviors // which leads to managed null references (unity null) even though we have a native object. See handling for missing // scripts for Prefab instances in GenericInspector.cs [FreeFunction] extern internal static bool IsInstanceIDPartOfNonAssetPrefabInstance(int componentOrGameObjectInstanceID); // Returns true if the object is from a regular prefab or instance of regular prefab [FreeFunction] extern public static bool IsPartOfRegularPrefab([NotNull] Object componentOrGameObject); // Returns true if the object is from a model prefab or instance of model prefab [FreeFunction] extern public static bool IsPartOfModelPrefab([NotNull] Object componentOrGameObject); // Return true if the object is part of a Variant no matter if the object is an instance or asset object [FreeFunction] extern public static bool IsPartOfVariantPrefab([NotNull] Object componentOrGameObject); // Returns true if the object is from a Prefab Asset which is not editable, or an instance of such a Prefab // Examples are Model Prefabs and Prefabs in read-only folders. [FreeFunction] extern public static bool IsPartOfImmutablePrefab([NotNull] Object componentOrGameObject); [FreeFunction] extern public static bool IsPrefabAssetMissing([NotNull] Object instanceComponentOrGameObject); [FreeFunction] extern public static GameObject GetOutermostPrefabInstanceRoot([NotNull] Object componentOrGameObject); [FreeFunction] extern public static GameObject GetNearestPrefabInstanceRoot([NotNull] Object componentOrGameObject); [FreeFunction] extern internal static GameObject GetOriginalSourceOrVariantRoot([NotNull] Object instanceOrAsset); [FreeFunction] extern public static GameObject GetOriginalSourceRootWhereGameObjectIsAdded([NotNull] GameObject gameObject); [NativeMethod("PrefabUtilityBindings::ApplyPrefabAddedComponent", IsFreeFunction = true, ThrowsException = true)] extern private static void ApplyAddedComponent([NotNull] Component addedComponent, [NotNull] Object applyTargetPrefabObject); [NativeMethod("PrefabUtilityBindings::IsDefaultOverride", IsFreeFunction = true)] extern public static bool IsDefaultOverride(PropertyModification modification); [NativeMethod("PrefabUtilityBindings::IsDefaultOverridePropertyPath", IsFreeFunction = true)] extern internal static bool IsDefaultOverridePropertyPath(string propertyPath); [FreeFunction] extern internal static bool CheckIfAddingPrefabWouldResultInCyclicNesting(Object prefabAssetThatIsAddedTo, Object prefabAssetThatWillBeAdded); [FreeFunction] extern internal static bool WasCreatedAsPrefabInstancePlaceholderObject(Object componentOrGameObject); [FreeFunction] extern internal static void ShowCyclicNestingWarningDialog(); [NativeMethod("PrefabUtilityBindings::GetVariantParentGUID_Internal", IsFreeFunction = true, ThrowsException = true)] extern internal static string GetVariantParentGUID(int prefabAssetInstanceID); internal static string GetVariantParentGUID(GameObject prefabAsset) { if (prefabAsset == null) throw new ArgumentNullException(nameof(prefabAsset)); return GetVariantParentGUID(prefabAsset.GetInstanceID()); } [FreeFunction] extern internal static bool IsPathInStreamingAssets(string path); } }
UnityCsReference/Editor/Mono/Prefabs/PrefabUtility.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Prefabs/PrefabUtility.bindings.cs", "repo_id": "UnityCsReference", "token_count": 8424 }
324
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.IO; using UnityEngine; using UnityEditorInternal; using System.Collections.Generic; namespace UnityEditor { internal partial class PresetLibraryEditor<T> where T : PresetLibrary { class SettingsMenu { static PresetLibraryEditor<T> s_Owner; class ViewModeData { public GUIContent text; public int itemHeight; public PresetLibraryEditorState.ItemViewMode viewmode; } public static void Show(Rect activatorRect, PresetLibraryEditor<T> owner) { s_Owner = owner; GenericMenu menu = new GenericMenu(); // View modes int minItemHeight = (int)s_Owner.minMaxPreviewHeight.x; int maxItemHeight = (int)s_Owner.minMaxPreviewHeight.y; List<ViewModeData> viewModeData; if (minItemHeight == maxItemHeight) { viewModeData = new List<ViewModeData> { new ViewModeData {text = EditorGUIUtility.TrTextContent("Grid"), itemHeight = minItemHeight, viewmode = PresetLibraryEditorState.ItemViewMode.Grid}, new ViewModeData {text = EditorGUIUtility.TrTextContent("List"), itemHeight = minItemHeight, viewmode = PresetLibraryEditorState.ItemViewMode.List}, }; } else { viewModeData = new List<ViewModeData> { new ViewModeData {text = EditorGUIUtility.TrTextContent("Small Grid"), itemHeight = minItemHeight, viewmode = PresetLibraryEditorState.ItemViewMode.Grid}, new ViewModeData {text = EditorGUIUtility.TrTextContent("Large Grid"), itemHeight = maxItemHeight, viewmode = PresetLibraryEditorState.ItemViewMode.Grid}, new ViewModeData {text = EditorGUIUtility.TrTextContent("Small List"), itemHeight = minItemHeight, viewmode = PresetLibraryEditorState.ItemViewMode.List}, new ViewModeData {text = EditorGUIUtility.TrTextContent("Large List"), itemHeight = maxItemHeight, viewmode = PresetLibraryEditorState.ItemViewMode.List} }; } for (int i = 0; i < viewModeData.Count; ++i) { bool currentSelected = s_Owner.itemViewMode == viewModeData[i].viewmode && (int)s_Owner.previewHeight == viewModeData[i].itemHeight; menu.AddItem(viewModeData[i].text, currentSelected, ViewModeChange, viewModeData[i]); } menu.AddSeparator(""); // Available libraries (show user libraries first then project libraries) List<string> preferencesLibs; List<string> projectLibs; PresetLibraryManager.instance.GetAvailableLibraries(s_Owner.m_SaveLoadHelper, out preferencesLibs, out projectLibs); preferencesLibs.Sort(); projectLibs.Sort(); string currentLibWithExtension = s_Owner.currentLibraryWithoutExtension + "." + s_Owner.m_SaveLoadHelper.fileExtensionWithoutDot; string projectFolderTag = " (Project)"; foreach (string libPath in preferencesLibs) { string libName = Path.GetFileNameWithoutExtension(libPath); menu.AddItem(new GUIContent(libName), currentLibWithExtension == libPath, LibraryModeChange, libPath); } foreach (string libPath in projectLibs) { string libName = Path.GetFileNameWithoutExtension(libPath); menu.AddItem(new GUIContent(libName + projectFolderTag), currentLibWithExtension == libPath, LibraryModeChange, libPath); } menu.AddSeparator(""); menu.AddItem(EditorGUIUtility.TrTextContent("Create New Library..."), false, CreateLibrary, 0); if (HasDefaultPresets()) { menu.AddSeparator(""); menu.AddItem(EditorGUIUtility.TrTextContent("Add Factory Presets To Current Library"), false, AddDefaultPresetsToCurrentLibrary, 0); } menu.AddSeparator(""); menu.AddItem(EditorGUIUtility.TrTextContent("Reveal Current Library Location"), false, RevealCurrentLibrary, 0); menu.DropDown(activatorRect); } static void ViewModeChange(object userData) { ViewModeData viewModeData = (ViewModeData)userData; s_Owner.itemViewMode = viewModeData.viewmode; s_Owner.previewHeight = viewModeData.itemHeight; } static void LibraryModeChange(object userData) { string libPath = (string)userData; s_Owner.currentLibraryWithoutExtension = libPath; } static void CreateLibrary(object userData) { s_Owner.wantsToCreateLibrary = true; } static void RevealCurrentLibrary(object userData) { s_Owner.RevealCurrentLibrary(); } static bool HasDefaultPresets() { return s_Owner.addDefaultPresets != null; } static void AddDefaultPresetsToCurrentLibrary(object userData) { if (s_Owner.addDefaultPresets != null) s_Owner.addDefaultPresets(s_Owner.GetCurrentLib()); s_Owner.SaveCurrentLib(); } } } } // UnityEditor
UnityCsReference/Editor/Mono/PresetLibraries/PresetLibraryEditorMenu.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/PresetLibraries/PresetLibraryEditorMenu.cs", "repo_id": "UnityCsReference", "token_count": 2797 }
325
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.IO; using System.Collections.Generic; using UnityEngine; using UnityEditorInternal; namespace UnityEditor { internal class ProjectTemplateWindow : EditorWindow { string m_Path; string m_Name; string m_DisplayName; string m_Description; string m_DefaultScene; string m_Version; [MenuItem("internal:Project/Save As Template...")] internal static void SaveAsTemplate() { var window = EditorWindow.GetWindow<ProjectTemplateWindow>(); window.Show(); } void OnEnable() { titleContent = EditorGUIUtility.TrTextContent("Save Template"); } string ReadJsonString(JSONValue json, string key) { if (json.ContainsKey(key) && !json[key].IsNull()) { return json[key].AsString(); } return null; } void OnGUI() { if (GUILayout.Button("Select Folder", GUILayout.Width(100))) { m_Path = EditorUtility.SaveFolderPanel("Choose target folder", "", ""); var packageJsonPath = Path.Combine(m_Path, "package.json"); if (File.Exists(packageJsonPath)) { var packageJson = File.ReadAllText(packageJsonPath); var json = new JSONParser(packageJson).Parse(); m_Name = ReadJsonString(json, "name"); m_DisplayName = ReadJsonString(json, "displayName"); m_Description = ReadJsonString(json, "description"); m_DefaultScene = ReadJsonString(json, "defaultScene"); m_Version = ReadJsonString(json, "version"); } } EditorGUILayout.TextField("Path:", m_Path); m_Name = EditorGUILayout.TextField("Name:", m_Name); m_DisplayName = EditorGUILayout.TextField("Display name:", m_DisplayName); m_Description = EditorGUILayout.TextField("Description:", m_Description); m_DefaultScene = EditorGUILayout.TextField("Default scene:", m_DefaultScene); m_Version = EditorGUILayout.TextField("Version:", m_Version); if (GUILayout.Button("Save", GUILayout.Width(100))) { if (String.IsNullOrEmpty(m_Path)) { m_Path = EditorUtility.SaveFolderPanel("Save template to folder", "", ""); } AssetDatabase.SaveAssets(); EditorUtility.SaveProjectAsTemplate(m_Path, m_Name, m_DisplayName, m_Description, m_DefaultScene, m_Version); } } } }
UnityCsReference/Editor/Mono/ProjectTemplateWindow.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/ProjectTemplateWindow.cs", "repo_id": "UnityCsReference", "token_count": 1372 }
326
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using UnityEngine; namespace UnityEditor { internal class SceneHierarchySortingWindow : EditorWindow { public delegate void OnSelectCallback(InputData element); private class Styles { public GUIStyle background = "grey_border"; public GUIStyle menuItem = "MenuToggleItem"; } public class InputData { public string m_TypeName; public string m_Name; public bool m_Selected; } private static SceneHierarchySortingWindow s_SceneHierarchySortingWindow; private static long s_LastClosedTime; private static Styles s_Styles; private List<InputData> m_Data; private OnSelectCallback m_Callback; const float kFrameWidth = 1f; private float GetHeight() { return EditorGUI.kSingleLineHeight * m_Data.Count; } private float GetWidth() { float width = 0f; foreach (InputData item in m_Data) { float itemWidth = 0; itemWidth = s_Styles.menuItem.CalcSize(GUIContent.Temp(item.m_Name)).x; if (itemWidth > width) width = itemWidth; } return width; } private void OnEnable() { AssemblyReloadEvents.beforeAssemblyReload += Close; hideFlags = HideFlags.DontSave; wantsMouseMove = true; } private void OnDisable() { AssemblyReloadEvents.beforeAssemblyReload -= Close; s_LastClosedTime = System.DateTime.Now.Ticks / System.TimeSpan.TicksPerMillisecond; } internal static bool ShowAtPosition(Vector2 pos, List<InputData> data, OnSelectCallback callback) { // We could not use realtimeSinceStartUp since it is set to 0 when entering/exitting playmode, we assume an increasing time when comparing time. long nowMilliSeconds = System.DateTime.Now.Ticks / System.TimeSpan.TicksPerMillisecond; bool justClosed = nowMilliSeconds < s_LastClosedTime + 50; if (!justClosed) { Event.current.Use(); if (s_SceneHierarchySortingWindow == null) s_SceneHierarchySortingWindow = CreateInstance<SceneHierarchySortingWindow>(); s_SceneHierarchySortingWindow.Init(pos, data, callback); return true; } return false; } private void Init(Vector2 pos, List<InputData> data, OnSelectCallback callback) { // Has to be done before calling Show / ShowWithMode //pos = GUIUtility.GUIToScreenPoint(pos); Rect buttonRect = new Rect(pos.x, pos.y - 16, 16, 16); // fake a button: we know we are showing it below the bottonRect if possible buttonRect = GUIUtility.GUIToScreenRect(buttonRect); data.Sort( delegate(InputData lhs, InputData rhs) { return lhs.m_Name.CompareTo(rhs.m_Name); }); m_Data = data; m_Callback = callback; if (s_Styles == null) s_Styles = new Styles(); var windowHeight = 2f * kFrameWidth + GetHeight(); var windowWidth = 2f * kFrameWidth + GetWidth(); var windowSize = new Vector2(windowWidth, windowHeight); ShowAsDropDown(buttonRect, windowSize); } internal void OnGUI() { // We do not use the layout event if (Event.current.type == EventType.Layout) return; if (Event.current.type == EventType.MouseMove) Event.current.Use(); // Content Draw(); // Background with 1 pixel border GUI.Label(new Rect(0, 0, position.width, position.height), GUIContent.none, s_Styles.background); } private void Draw() { var drawPos = new Rect(kFrameWidth, kFrameWidth, position.width - 2 * kFrameWidth, EditorGUI.kSingleLineHeight); foreach (InputData data in m_Data) { DrawListElement(drawPos, data); drawPos.y += EditorGUI.kSingleLineHeight; } } void DrawListElement(Rect rect, InputData data) { EditorGUI.BeginChangeCheck(); GUI.Toggle(rect, data.m_Selected, EditorGUIUtility.TempContent(data.m_Name), s_Styles.menuItem); if (EditorGUI.EndChangeCheck()) { m_Callback(data); Close(); } } } }
UnityCsReference/Editor/Mono/SceneHierarchySortingWindow.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/SceneHierarchySortingWindow.cs", "repo_id": "UnityCsReference", "token_count": 2324 }
327
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using UnityEditor.IMGUI.Controls; using UnityEngine; using UnityEngine.SceneManagement; namespace UnityEditor.SceneManagement { public abstract class Stage : ScriptableObject { static List<Stage> s_AllStages = new List<Stage>(); internal static ReadOnlyCollection<Stage> allStages { get { return s_AllStages.AsReadOnly(); } } // Stage interface // Called when the user have accepted to switch away from previous stage. This method should load stage contents. // Should return 'true' if the stage was opened succesfully otherwise 'false'. protected internal abstract bool OnOpenStage(); // Called when the stage is destroyed (when OnDestroy() is called). Should unload the contents of the stage. // Only called if OnOpenStage was called. protected abstract void OnCloseStage(); // Called when returning to a previous open stage (e.g by clicking a non-current breadcrumb) protected internal virtual void OnReturnToStage() {} internal bool opened { get; set; } internal virtual bool isValid { get { return true; } } internal virtual bool isAssetMissing { get { return false; } } public virtual string assetPath { get { return string.Empty; } } internal virtual bool showOptionsButton { get { return false; } } internal abstract int sceneCount { get; } internal abstract Scene GetSceneAt(int index); internal virtual bool SupportsSaving() { return false; } internal virtual bool hasUnsavedChanges { get { return false; } } internal virtual bool Save() { if (!SupportsSaving() || !hasUnsavedChanges) return true; throw new System.NotImplementedException("This Stage returns true for SupportsSaving() but has not implemented an override for the Save() method."); } internal virtual void DiscardChanges() { if (!SupportsSaving() || !hasUnsavedChanges) return; throw new System.NotImplementedException("This Stage returns true for SupportsSaving() but has not implemented an override for the DiscardChanges() method."); } static internal void ShowDiscardChangesDialog(Stage stage) { string title = LocalizationDatabase.GetLocalizedString("Discard Changes"); string message = LocalizationDatabase.GetLocalizedString("Are you sure you want to discard the changes to:\n\n {0}\n\nYour changes will be lost."); message = string.Format(message, System.IO.Path.GetFileName(stage.assetPath)); if (EditorUtility.DisplayDialog(title, message, LocalizationDatabase.GetLocalizedString("OK"), LocalizationDatabase.GetLocalizedString("Cancel"))) stage.DiscardChanges(); } internal virtual void BuildContextMenuForStageHeader(GenericMenu menu) { if (SupportsSaving()) { var saveText = EditorGUIUtility.TrTextContent("Save"); var discardText = EditorGUIUtility.TrTextContent("Discard changes"); // Save if (hasUnsavedChanges) { menu.AddItem(saveText, false, () => { Save(); }); } else { menu.AddDisabledItem(saveText); } menu.AddSeparator(""); // Discard changes if (hasUnsavedChanges && !isAssetMissing) { menu.AddItem(discardText, false, () => { ShowDiscardChangesDialog(this); }); } else { menu.AddDisabledItem(discardText); } } } internal virtual bool SaveAsNew() { if (!SupportsSaving()) return true; throw new System.NotImplementedException("This Stage returns true for SupportsSaving() but has not implemented an override for the SaveAsNew() method."); } // Transient state since it is set every time we switch stage internal bool setSelectionAndScrollWhenBecomingCurrentStage { get; set; } = true; internal virtual string GetErrorMessage() { return null; } protected internal abstract GUIContent CreateHeaderContent(); internal virtual BreadcrumbBar.Item CreateBreadcrumbItem() { var history = StageNavigationManager.instance.stageHistory; bool isLastCrumb = this == history.Last(); var style = isLastCrumb ? BreadcrumbBar.DefaultStyles.labelBold : BreadcrumbBar.DefaultStyles.label; return new BreadcrumbBar.Item { content = CreateHeaderContent(), guistyle = style, userdata = this, separatorstyle = BreadcrumbBar.SeparatorStyle.Line }; } internal virtual ulong GetSceneCullingMask() { return EditorSceneManager.DefaultSceneCullingMask; } public virtual StageHandle stageHandle { get { return StageHandle.GetMainStageHandle(); } } public virtual ulong GetCombinedSceneCullingMaskForCamera() { return GetSceneCullingMask(); } internal virtual Stage GetContextStage() { return this; } internal virtual Color GetBackgroundColor() { // Case 1255995 - Workaround for OSX 10.15 driver issue with Intel 630 cards Color opaqueBackground = SceneView.kSceneViewBackground.Color; opaqueBackground.a = 1; return opaqueBackground; } // Called before and after the Scene view renders. internal virtual void OnPreSceneViewRender(SceneView sceneView) {} internal virtual void OnPostSceneViewRender(SceneView sceneView) {} // Called when new stage is created, after script reloads, and possibly at other times by the stage itself. internal abstract void SyncSceneViewToStage(SceneView sceneView); internal abstract void SyncSceneHierarchyToStage(SceneHierarchyWindow sceneHierarchyWindow); internal virtual void SaveHierarchyState(SceneHierarchyWindow hierarchyWindow) {} internal virtual void LoadHierarchyState(SceneHierarchyWindow hierarchyWindow) {} // Called after respective sync methods first time this stage is opened in this window. protected internal virtual void OnFirstTimeOpenStageInSceneView(SceneView sceneView) {} internal virtual void OnFirstTimeOpenStageInSceneHierachyWindow(SceneHierarchyWindow sceneHierarchyWindow) {} internal virtual void OnControlsGUI(SceneView sceneView) {} internal virtual void Tick() { } // Called on the the current stage when trying to switch to new stage. Should return true if it OK to continue to switch away // from current stage. False if not ok to continue. internal virtual bool AskUserToSaveModifiedStageBeforeSwitchingStage() { return true; } internal abstract void PlaceGameObjectInStage(GameObject rootGameObject); // Used for writing state files to HDD // Should typically be a persistent unique hash per content shown. // For stages that use the assetPath property, the hash is by default based on the asset GUID. protected internal virtual Hash128 GetHashForStateStorage() { if (!string.IsNullOrEmpty(assetPath)) return Hash128.Compute(AssetDatabase.AssetPathToGUID(assetPath)); // If no assetPath is specified, the default behavior is that // every stage of the same type will reuse the same state files. return new Hash128(); } // Lifetime callbacks from ScriptableObject private void Awake() { } private void OnDestroy() { if (opened) { OnCloseStage(); opened = false; } } protected virtual void OnEnable() { hideFlags = HideFlags.HideAndDontSave; s_AllStages.Add(this); } protected virtual void OnDisable() { s_AllStages.Remove(this); } public T FindComponentOfType<T>() where T : Component { return stageHandle.FindComponentOfType<T>(); } public T[] FindComponentsOfType<T>() where T : Component { return stageHandle.FindComponentsOfType<T>(); } } public struct StageHandle : System.IEquatable<StageHandle> { private bool m_IsMainStage; private Scene m_CustomScene; internal bool isMainStage { get { return m_IsMainStage; } } internal Scene customScene { get { return m_CustomScene; } } public bool Contains(GameObject gameObject) { if (!IsValid()) throw new System.Exception("Stage is not valid."); Scene goScene = gameObject.scene; if (goScene.IsValid() && EditorSceneManager.IsPreviewScene(goScene)) return goScene == customScene; else return isMainStage; } public T FindComponentOfType<T>() where T : Component { if (!IsValid()) throw new System.Exception("Stage is not valid."); T[] components = Resources.FindObjectsOfTypeAll<T>(); if (isMainStage) { for (int i = 0; i < components.Length; i++) { T obj = components[i]; if (!EditorUtility.IsPersistent(obj) && !EditorSceneManager.IsPreviewScene(obj.gameObject.scene)) return obj; } } else { for (int i = 0; i < components.Length; i++) { T obj = components[i]; if (obj.gameObject.scene == customScene) return obj; } } return null; } public T[] FindComponentsOfType<T>() where T : Component { if (!IsValid()) throw new System.Exception("Stage is not valid."); T[] components = Resources.FindObjectsOfTypeAll<T>(); List<T> componentList = new List<T>(); if (isMainStage) { for (int i = 0; i < components.Length; i++) { T obj = components[i]; if (!EditorUtility.IsPersistent(obj) && !EditorSceneManager.IsPreviewScene(obj.gameObject.scene)) componentList.Add(obj); } } else { for (int i = 0; i < components.Length; i++) { T obj = components[i]; if (obj.gameObject.scene == customScene) componentList.Add(obj); } } return componentList.ToArray(); } // Use public API StageUtility.GetMainStage internal static StageHandle GetMainStageHandle() { return new StageHandle() { m_IsMainStage = true }; } // Use public API StageUtility.GetCurrentStage internal static StageHandle GetCurrentStageHandle() { if (StageNavigationManager.instance != null && StageNavigationManager.instance.currentStage != null) return StageNavigationManager.instance.currentStage.stageHandle; return new StageHandle() { m_IsMainStage = true }; } // Use public API StageUtility.GetStage internal static StageHandle GetStageHandle(Scene scene) { if (scene.IsValid() && EditorSceneManager.IsPreviewScene(scene)) return new StageHandle() { m_CustomScene = scene }; else return new StageHandle() { m_IsMainStage = true }; } public bool IsValid() { return m_IsMainStage ^ m_CustomScene.IsValid(); } public static bool operator==(StageHandle s1, StageHandle s2) { return s1.Equals(s2); } public static bool operator!=(StageHandle s1, StageHandle s2) { return !s1.Equals(s2); } public override bool Equals(object other) { if (!(other is StageHandle)) return false; StageHandle rhs = (StageHandle)other; return m_IsMainStage == rhs.m_IsMainStage && m_CustomScene == rhs.m_CustomScene; } public bool Equals(StageHandle other) { return m_IsMainStage == other.m_IsMainStage && m_CustomScene == other.m_CustomScene; } public override int GetHashCode() { if (m_IsMainStage) return 1; return m_CustomScene.GetHashCode(); } } }
UnityCsReference/Editor/Mono/SceneManagement/StageManager/Stage.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/SceneManagement/StageManager/Stage.cs", "repo_id": "UnityCsReference", "token_count": 5917 }
328
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using UnityEditor; using UnityEditorInternal; using UnityEngine; using System.IO; using UnityEditor.Overlays; using UnityEngine.SceneManagement; using Object = UnityEngine.Object; namespace UnityEditor { [EditorWindowTitle(title = "Occlusion", icon = "Occlusion")] internal class OcclusionCullingWindow : EditorWindow { static bool s_IsVisible = false; private bool m_PreVis; private bool m_ClearCacheData = true; private bool m_ClearBakeData = true; private string m_Warning; static OcclusionCullingWindow ms_OcclusionCullingWindow; Vector2 m_ScrollPosition = Vector2.zero; Mode m_Mode = Mode.AreaSettings; static Styles s_Styles; class Styles { public GUIContent[] ModeToggles = { EditorGUIUtility.TrTextContent("Object"), EditorGUIUtility.TrTextContent("Bake"), EditorGUIUtility.TrTextContent("Visualization") }; public GUIStyle labelStyle = EditorStyles.wordWrappedMiniLabel; public GUIContent emptyAreaSelection = EditorGUIUtility.TrTextContent("Select a Mesh Renderer or an Occlusion Area from the scene."); public GUIContent emptyCameraSelection = EditorGUIUtility.TrTextContent("Select a Camera from the scene."); public GUIContent visualizationNote = EditorGUIUtility.TrTextContent("The visualization may not correspond to current bake settings and Occlusion Area placements if they have been changed since last bake."); public GUIContent seeVisualizationInScene = EditorGUIUtility.TrTextContent("See the occlusion culling visualization in the Scene View based on the selected Camera."); public GUIContent noOcclusionData = EditorGUIUtility.TrTextContent("No occlusion data has been baked."); public GUIContent smallestHole = EditorGUIUtility.TrTextContent("Smallest Hole", "Smallest hole in the geometry through which the camera is supposed to see. The single float value of the parameter represents the diameter of the imaginary smallest hole, i.e. the maximum extent of a 3D object that fits through the hole."); public GUIContent backfaceThreshold = EditorGUIUtility.TrTextContent("Backface Threshold", "The backface threshold is a size optimization that reduces unnecessary details by testing backfaces. A value of 100 is robust and never removes any backfaces. A value of 5 aggressively reduces the data based on locations with visible backfaces. The idea is that typically valid camera positions cannot see many backfaces. For example, geometry under terrain and inside solid objects can be removed."); public GUIContent farClipPlane = EditorGUIUtility.TrTextContent("Far Clip Plane", "Far Clip Plane used during baking. This should match the largest far clip plane used by any camera in the scene. A value of 0.0 sets the far plane to Infinity."); public GUIContent smallestOccluder = EditorGUIUtility.TrTextContent("Smallest Occluder", "The size of the smallest object that will be used to hide other objects when doing occlusion culling. For example, if a value of 4 is chosen, then all the objects that are higher or wider than 4 meters will block visibility and the objects that are smaller than that will not. This value is a tradeoff between occlusion accuracy and storage size."); public GUIContent defaultParameterText = EditorGUIUtility.TrTextContent("Default Parameters", "The default parameters guarantee that any given scene computes fast and the occlusion culling results are good. As the parameters are always scene specific, better results will be achieved when fine tuning the parameters on a scene to scene basis. All the parameters are dependent on the unit scale of the scene and it is imperative that the unit scale parameter is set correctly before setting the default values."); } enum Mode { AreaSettings = 0, BakeSettings = 1, Visualization = 2 } internal static bool isVisible { get { return (ms_OcclusionCullingWindow != null) ? s_IsVisible : false; } } void OnBecameVisible() { if (s_IsVisible == true) return; s_IsVisible = true; StaticOcclusionCullingVisualization.showOcclusionCulling = true; SceneView.RepaintAll(); } void OnBecameInvisible() { s_IsVisible = false; StaticOcclusionCullingVisualization.showOcclusionCulling = false; SceneView.RepaintAll(); } void OnSelectionChange() { if (m_Mode == Mode.AreaSettings || m_Mode == Mode.Visualization) Repaint(); } void OnEnable() { titleContent = GetLocalizedTitleContent(); ms_OcclusionCullingWindow = this; autoRepaintOnSceneChange = true; EditorApplication.searchChanged += Repaint; Repaint(); } void OnDisable() { ms_OcclusionCullingWindow = null; EditorApplication.searchChanged -= Repaint; } static void BackgroundTaskStatusChanged() { if (ms_OcclusionCullingWindow) ms_OcclusionCullingWindow.Repaint(); } [MenuItem("Window/Rendering/Occlusion Culling", false, 101)] static void GenerateWindow() { var window = GetWindow<OcclusionCullingWindow>(typeof(InspectorWindow)); window.minSize = new Vector2(300, 250); } void SummaryGUI() { GUILayout.BeginVertical(EditorStyles.helpBox); if (StaticOcclusionCulling.umbraDataSize == 0) { GUILayout.Label(s_Styles.noOcclusionData, s_Styles.labelStyle); } else { GUILayout.Label("Last bake:", s_Styles.labelStyle); GUILayout.BeginHorizontal(); GUILayout.BeginVertical(); GUILayout.Label("Occlusion data size ", s_Styles.labelStyle); GUILayout.EndVertical(); GUILayout.BeginVertical(); GUILayout.Label(EditorUtility.FormatBytes(StaticOcclusionCulling.umbraDataSize), s_Styles.labelStyle); GUILayout.EndVertical(); GUILayout.EndHorizontal(); } GUILayout.EndVertical(); } OcclusionArea CreateNewArea() { GameObject go = new GameObject("Occlusion Area"); OcclusionArea oa = go.AddComponent<OcclusionArea>(); Selection.activeGameObject = go; return oa; } void AreaSelectionGUI() { bool emptySelection = true; GameObject[] gos; Type focusType = SceneModeUtility.SearchBar(typeof(Renderer), typeof(OcclusionArea)); EditorGUILayout.Space(); // Occlusion Areas OcclusionArea[] oas = SceneModeUtility.GetSelectedObjectsOfType<OcclusionArea>(out gos); if (gos.Length > 0) { emptySelection = false; EditorGUILayout.MultiSelectionObjectTitleBar(oas); using (var so = new SerializedObject(oas)) { EditorGUILayout.PropertyField(so.FindProperty("m_IsViewVolume")); so.ApplyModifiedProperties(); } } // Renderers Renderer[] renderers = SceneModeUtility.GetSelectedObjectsOfType<Renderer>(out gos, typeof(MeshRenderer), typeof(SkinnedMeshRenderer)); if (gos.Length > 0) { emptySelection = false; EditorGUILayout.MultiSelectionObjectTitleBar(renderers); using (var goso = new SerializedObject(gos)) { SceneModeUtility.StaticFlagField("Occluder Static", goso.FindProperty("m_StaticEditorFlags"), (int)StaticEditorFlags.OccluderStatic); SceneModeUtility.StaticFlagField("Occludee Static", goso.FindProperty("m_StaticEditorFlags"), (int)StaticEditorFlags.OccludeeStatic); goso.ApplyModifiedProperties(); } } if (emptySelection) { GUILayout.Label(s_Styles.emptyAreaSelection, EditorStyles.helpBox); if (focusType == typeof(OcclusionArea)) { EditorGUIUtility.labelWidth = 80; EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Create New"); if (GUILayout.Button("Occlusion Area", EditorStyles.miniButton, GUILayout.ExpandWidth(false))) CreateNewArea(); EditorGUILayout.EndHorizontal(); } } } void CameraSelectionGUI() { SceneModeUtility.SearchBar(typeof(Camera)); EditorGUILayout.Space(); Camera cam = null; if (Selection.activeGameObject) cam = Selection.activeGameObject.GetComponent<Camera>(); // Camera if (cam) { Camera[] cameras = new Camera[] { cam }; EditorGUILayout.MultiSelectionObjectTitleBar(cameras); EditorGUILayout.HelpBox(s_Styles.seeVisualizationInScene.text, MessageType.Info); } else { GUILayout.Label(s_Styles.emptyCameraSelection, EditorStyles.helpBox); } } void BakeSettings() { // Button for setting default values float buttonWidth = 150; if (GUILayout.Button("Set default parameters", GUILayout.Width(buttonWidth))) { Undo.RegisterCompleteObjectUndo(StaticOcclusionCulling.occlusionCullingSettings, "Set Default Parameters"); GUIUtility.keyboardControl = 0; // Force focus out from potentially selected field for default parameters setting StaticOcclusionCulling.SetDefaultOcclusionBakeSettings(); } // Label for default parameter setting GUILayout.Label(s_Styles.defaultParameterText.tooltip, EditorStyles.helpBox); // Edit Smallest Occluder EditorGUI.BeginChangeCheck(); float smallestOccluder = EditorGUILayout.FloatField(s_Styles.smallestOccluder, StaticOcclusionCulling.smallestOccluder); if (EditorGUI.EndChangeCheck()) { Undo.RegisterCompleteObjectUndo(StaticOcclusionCulling.occlusionCullingSettings, "Change Smallest Occluder"); StaticOcclusionCulling.smallestOccluder = smallestOccluder; } // Edit smallest hole EditorGUI.BeginChangeCheck(); float smallestHole = EditorGUILayout.FloatField(s_Styles.smallestHole, StaticOcclusionCulling.smallestHole); if (EditorGUI.EndChangeCheck()) { Undo.RegisterCompleteObjectUndo(StaticOcclusionCulling.occlusionCullingSettings, "Change Smallest Hole"); StaticOcclusionCulling.smallestHole = smallestHole; } // Edit backface threshold EditorGUI.BeginChangeCheck(); float backfaceThreshold = EditorGUILayout.Slider(s_Styles.backfaceThreshold, StaticOcclusionCulling.backfaceThreshold, 5.0F, 100.0F); if (EditorGUI.EndChangeCheck()) { Undo.RegisterCompleteObjectUndo(StaticOcclusionCulling.occlusionCullingSettings, "Change Backface Threshold"); StaticOcclusionCulling.backfaceThreshold = backfaceThreshold; } } void BakeButtons() { float buttonWidth = 95; GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); bool allowBaking = !EditorApplication.isPlayingOrWillChangePlaymode; bool bakeRunning = StaticOcclusionCulling.isRunning; GUI.enabled = !bakeRunning && allowBaking; if (CustomDropdownButton("Clear", buttonWidth)) { if (m_ClearBakeData) { StaticOcclusionCulling.Clear(); } if (m_ClearCacheData) { StaticOcclusionCulling.RemoveCacheFolder(); } } GUI.enabled = allowBaking; if (bakeRunning) { if (GUILayout.Button("Cancel", GUILayout.Width(buttonWidth))) StaticOcclusionCulling.Cancel(); } else { if (GUILayout.Button("Bake", GUILayout.Width(buttonWidth))) { StaticOcclusionCulling.GenerateInBackground(); } } GUILayout.EndHorizontal(); GUI.enabled = true; } private bool CustomDropdownButton(string name, float width, params GUILayoutOption[] options) { var content = EditorGUIUtility.TrTextContent(name); var rect = GUILayoutUtility.GetRect(content, EditorStyles.dropDownList, options); var halfDiff = (width - rect.width) / 2f; rect.xMin -= halfDiff; rect.xMax += halfDiff; var currPos = rect.position; currPos.x -= halfDiff; rect.position = currPos; var dropDownRect = rect; const float kDropDownButtonWidth = 20f; dropDownRect.xMin = dropDownRect.xMax - kDropDownButtonWidth; string[] names = { "Bake Data", "Cache Data" }; bool[] values = { m_ClearBakeData, m_ClearCacheData }; if (Event.current.type == EventType.MouseDown && dropDownRect.Contains(Event.current.mousePosition)) { var menu = new GenericMenu(); for (int i = 0; i != names.Length; i++) menu.AddItem(new GUIContent(names[i]), values[i], CustomDropdownCallback, i); menu.DropDown(rect); Event.current.Use(); return false; } return GUI.Button(rect, content, EditorStyles.dropDownList); } private void CustomDropdownCallback(object userData) { int index = (int)userData; if (index == 0) { m_ClearBakeData = !m_ClearBakeData; } else if (index == 1) { m_ClearCacheData = !m_ClearCacheData; } } void ModeToggle() { EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); using (var check = new EditorGUI.ChangeCheckScope()) { m_Mode = (Mode)GUILayout.Toolbar((int)m_Mode, s_Styles.ModeToggles, "LargeButton", GUI.ToolbarButtonSize.FitToContents); if (check.changed) { if (m_Mode == Mode.Visualization && StaticOcclusionCulling.umbraDataSize > 0) StaticOcclusionCullingVisualization.showPreVisualization = false; else StaticOcclusionCullingVisualization.showPreVisualization = true; SceneView.RepaintAll(); } } GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); } void OnGUI() { if (s_Styles == null) s_Styles = new Styles(); // Make sure the tab jumps to visualization if we're in visualize mode. // (Don't do the reverse. Since tabs can't be marked disabled, the user // will be confused if the visualization tab can't be clicked, and that // would be the result if we changed the tab away from visualization // whenever showPreVisualization is false.) if (m_Mode != Mode.Visualization && StaticOcclusionCullingVisualization.showPreVisualization == false) m_Mode = Mode.Visualization; EditorGUILayout.Space(); ModeToggle(); EditorGUILayout.Space(); m_ScrollPosition = EditorGUILayout.BeginScrollView(m_ScrollPosition); switch (m_Mode) { case Mode.AreaSettings: AreaSelectionGUI(); break; case Mode.BakeSettings: BakeSettings(); break; case Mode.Visualization: if (StaticOcclusionCulling.umbraDataSize > 0) { CameraSelectionGUI(); GUILayout.FlexibleSpace(); GUILayout.Label(s_Styles.visualizationNote, EditorStyles.helpBox); } else { GUILayout.Label(s_Styles.noOcclusionData, EditorStyles.helpBox); } break; } EditorGUILayout.EndScrollView(); EditorGUILayout.Space(); BakeButtons(); EditorGUILayout.Space(); // Info GUI SummaryGUI(); } void OnDidOpenScene() { StaticOcclusionCulling.InvalidatePrevisualisationData(); Repaint(); } void SetShowVolumePreVis() { StaticOcclusionCullingVisualization.showPreVisualization = true; if (m_Mode == Mode.Visualization) m_Mode = Mode.AreaSettings; if (ms_OcclusionCullingWindow) ms_OcclusionCullingWindow.Repaint(); SceneView.RepaintAll(); } void SetShowVolumeCulling() { StaticOcclusionCullingVisualization.showPreVisualization = false; m_Mode = Mode.Visualization; if (ms_OcclusionCullingWindow) ms_OcclusionCullingWindow.Repaint(); SceneView.RepaintAll(); } bool ShowModePopup(Rect popupRect) { // Visualization mode popup int tomeSize = StaticOcclusionCulling.umbraDataSize; // We can only change the preVis state during layout mode. However, the Tome data could be emptied at anytime, which will immediately disable preVis. // We need to detect this and force a repaint, so we can change the state. if (m_PreVis != StaticOcclusionCullingVisualization.showPreVisualization) SceneView.RepaintAll(); if (Event.current.type == EventType.Layout) m_PreVis = StaticOcclusionCullingVisualization.showPreVisualization; string[] options = new string[] { "Edit", "Visualize" }; int selected = m_PreVis ? 0 : 1; if (EditorGUI.DropdownButton(popupRect, new GUIContent(options[selected]), FocusType.Passive, EditorStyles.popup)) { GenericMenu menu = new GenericMenu(); menu.AddItem(new GUIContent(options[0]), selected == 0, SetShowVolumePreVis); if (tomeSize > 0) menu.AddItem(new GUIContent(options[1]), selected == 1, SetShowVolumeCulling); else menu.AddDisabledItem(new GUIContent(options[1])); menu.Popup(popupRect, selected); } return m_PreVis; } void DisplayControls() { if (!s_IsVisible) return; bool temp; // See if pre-vis is set to true. // If we don't have any Tome data, act as if pvs is true, but don't actually set it to true // - that way it will act like it switches to false (the default value) by itself as soon as pvs data has been build, // which better leads to discovery of this feature. bool preVis = ShowModePopup(GUILayoutUtility.GetRect(170, EditorGUIUtility.singleLineHeight)); if (Event.current.type == EventType.Layout) { m_Warning = ""; if (!preVis) { if (StaticOcclusionCullingVisualization.previewOcclucionCamera == null) m_Warning = "No camera selected for occlusion preview."; else if (!StaticOcclusionCullingVisualization.isPreviewOcclusionCullingCameraInPVS) m_Warning = "Camera is not inside an Occlusion View Area."; } } int legendHeight = 12; if (!string.IsNullOrEmpty(m_Warning)) { Rect warningRect = GUILayoutUtility.GetRect(100, legendHeight + 19); warningRect.x += EditorGUI.indent; warningRect.width -= EditorGUI.indent; GUI.Label(warningRect, m_Warning, EditorStyles.helpBox); } else { // Show legend / volume toggles Rect legendRect = GUILayoutUtility.GetRect(200, legendHeight); legendRect.x += EditorGUI.indent; legendRect.width -= EditorGUI.indent; Rect viewLegendRect = new Rect(legendRect.x, legendRect.y, legendRect.width, legendRect.height); if (preVis) EditorGUI.DrawLegend(viewLegendRect, Color.white, "View Volumes", StaticOcclusionCullingVisualization.showViewVolumes); else EditorGUI.DrawLegend(viewLegendRect, Color.white, "Camera Volumes", StaticOcclusionCullingVisualization.showViewVolumes); temp = GUI.Toggle(viewLegendRect, StaticOcclusionCullingVisualization.showViewVolumes, "", GUIStyle.none); if (temp != StaticOcclusionCullingVisualization.showViewVolumes) { StaticOcclusionCullingVisualization.showViewVolumes = temp; SceneView.RepaintAll(); } if (!preVis) { // TODO: FORE REALS cleanup this bad code BUG: 496650 legendRect = GUILayoutUtility.GetRect(100, legendHeight); legendRect.x += EditorGUI.indent; legendRect.width -= EditorGUI.indent; viewLegendRect = new Rect(legendRect.x, legendRect.y, legendRect.width, legendRect.height); EditorGUI.DrawLegend(viewLegendRect, Color.green, "Visibility Lines", StaticOcclusionCullingVisualization.showVisibilityLines); temp = GUI.Toggle(viewLegendRect, StaticOcclusionCullingVisualization.showVisibilityLines, "", GUIStyle.none); if (temp != StaticOcclusionCullingVisualization.showVisibilityLines) { StaticOcclusionCullingVisualization.showVisibilityLines = temp; SceneView.RepaintAll(); } legendRect = GUILayoutUtility.GetRect(100, legendHeight); legendRect.x += EditorGUI.indent; legendRect.width -= EditorGUI.indent; viewLegendRect = new Rect(legendRect.x, legendRect.y, legendRect.width, legendRect.height); EditorGUI.DrawLegend(viewLegendRect, Color.grey, "Portals", StaticOcclusionCullingVisualization.showPortals); temp = GUI.Toggle(viewLegendRect, StaticOcclusionCullingVisualization.showPortals, "", GUIStyle.none); if (temp != StaticOcclusionCullingVisualization.showPortals) { StaticOcclusionCullingVisualization.showPortals = temp; SceneView.RepaintAll(); } } // Geometry culling toggle if (!preVis) { temp = GUILayout.Toggle(StaticOcclusionCullingVisualization.showGeometryCulling, "Occlusion culling"); if (temp != StaticOcclusionCullingVisualization.showGeometryCulling) { StaticOcclusionCullingVisualization.showGeometryCulling = temp; SceneView.RepaintAll(); } } } } [Overlay(typeof(SceneView), k_OverlayId, k_DisplayName)] class SceneViewOcclusionCullingOverlay : TransientSceneViewOverlay { const string k_OverlayId = "Scene View/Occlusion Culling"; const string k_DisplayName = "Occlusion Culling"; OcclusionCullingWindow m_Window; public override bool visible { get { return s_IsVisible && StaticOcclusionCullingVisualization.showOcclusionCulling; } } public override void OnGUI() { if (m_Window == null) { var wins = Resources.FindObjectsOfTypeAll(typeof(OcclusionCullingWindow)) as OcclusionCullingWindow[]; m_Window = wins.Length > 0 ? wins[0] : null; } if (m_Window != null) { m_Window.DisplayControls(); } } } } }
UnityCsReference/Editor/Mono/SceneModeWindows/OcclusionCullingWindow.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/SceneModeWindows/OcclusionCullingWindow.cs", "repo_id": "UnityCsReference", "token_count": 12277 }
329
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using UnityEditor.EditorTools; using UnityEditor.Overlays; using UnityEditor.Toolbars; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor { // See also // - UIServiceEditor/SceneView/SceneViewToolbarElements.cs // - UIServiceEditor/EditorToolbar/ToolbarElements/BuiltinTools.cs [Overlay(typeof(SceneView), k_Id, "Tools", true, priority = (int)OverlayPriority.Tools)] [Icon("Icons/Overlays/ToolsToggle.png")] class TransformToolsOverlayToolBar : ToolbarOverlay { const string k_Id = "unity-transform-toolbar"; public TransformToolsOverlayToolBar() : base("Tools/Builtin Tools") {} public override void OnCreated() { base.OnCreated(); ToolManager.activeToolChanged += UpdateActiveToolIcon; SceneViewMotion.viewToolActiveChanged += UpdateActiveToolIcon; Tools.viewToolChanged += UpdateViewToolIcon; UpdateActiveToolIcon(); } public override void OnWillBeDestroyed() { ToolManager.activeToolChanged -= UpdateActiveToolIcon; SceneViewMotion.viewToolActiveChanged -= UpdateActiveToolIcon; Tools.viewToolChanged -= UpdateViewToolIcon; base.OnWillBeDestroyed(); } void UpdateActiveToolIcon() { if(Tools.viewToolActive) UpdateViewToolIcon(); else collapsedIcon = EditorToolUtility.IsManipulationTool(Tools.current) ? EditorToolUtility.GetToolbarIcon(EditorToolManager.activeTool)?.image as Texture2D : null; } void UpdateViewToolIcon() { if(!Tools.viewToolActive) return; switch (Tools.viewTool) { case ViewTool.Orbit: case ViewTool.FPS: collapsedIcon = EditorGUIUtility.LoadIconRequired("ViewToolOrbit"); break; case ViewTool.Pan: collapsedIcon = EditorGUIUtility.LoadIconRequired("ViewToolMove"); break; case ViewTool.Zoom: collapsedIcon = EditorGUIUtility.LoadIconRequired("ViewToolZoom"); break; } } } [Overlay(typeof(SceneView), k_Id, "View Options", true, priority = (int)OverlayPriority.ViewOptions)] [Icon("Icons/Overlays/ViewOptions.png")] class SceneViewToolBar : ToolbarOverlay { const string k_Id = "unity-scene-view-toolbar"; public SceneViewToolBar() : base( "SceneView/2D", "SceneView/Audio", "SceneView/Fx", "SceneView/Scene Visibility", "SceneView/Render Doc", "SceneView/Metal Capture", "SceneView/Scene Camera", "SceneView/Gizmos") {} } [Overlay(typeof(SceneView), k_Id, "Draw Modes", true, priority = (int)OverlayPriority.DrawModes, defaultDockIndex = 1, defaultDockPosition = DockPosition.Bottom, defaultLayout = Layout.HorizontalToolbar, defaultDockZone = DockZone.TopToolbar)] [Icon("Icons/Overlays/ViewOptions.png")] class SceneViewCameraModeToolbar : ToolbarOverlay { const string k_Id = "unity-scene-view-camera-mode-toolbar"; public SceneViewCameraModeToolbar() : base( "SceneView/Common Camera Mode", "SceneView/Camera Mode") {} private SceneView m_SceneView; public override void OnCreated() { m_SceneView = containerWindow as SceneView; m_SceneView.onCameraModeChanged += UpdateIcon; UpdateIcon(m_SceneView.cameraMode); } public override void OnWillBeDestroyed() { m_SceneView.onCameraModeChanged -= UpdateIcon; } internal void UpdateIcon(SceneView.CameraMode cameraMode) { switch (cameraMode.drawMode) { case DrawCameraMode.Wireframe: collapsedIcon = EditorGUIUtility.LoadIconRequired("Toolbars/wireframe"); break; case DrawCameraMode.TexturedWire: collapsedIcon = EditorGUIUtility.LoadIconRequired("Toolbars/ShadedWireframe"); break; case DrawCameraMode.Textured when !m_SceneView.sceneLighting: collapsedIcon = EditorGUIUtility.LoadIconRequired("Toolbars/UnlitMode"); break; case DrawCameraMode.Textured: collapsedIcon = EditorGUIUtility.LoadIconRequired("Toolbars/Shaded"); break; default: collapsedIcon = EditorGUIUtility.LoadIconRequired("Toolbars/debug"); break; } } } [Overlay(typeof(SceneView), k_Id, "Search", true, priority = (int)OverlayPriority.Search)] [Icon("Icons/Overlays/SearchOverlay.png")] class SearchToolBar : Overlay, ICreateHorizontalToolbar { const string k_Id = "unity-search-toolbar"; public OverlayToolbar CreateHorizontalToolbarContent() { return EditorToolbar.CreateOverlay(toolbarElements, containerWindow); } public override VisualElement CreatePanelContent() { return CreateHorizontalToolbarContent(); } public IEnumerable<string> toolbarElements { get { yield return "SceneView/Search"; } } } [Overlay(typeof(SceneView), k_Id, "Grid and Snap", true, priority = (int)OverlayPriority.GridAndSnap)] [Icon("Icons/Overlays/GridAndSnap.png")] class GridAndSnapToolBar : ToolbarOverlay { const string k_Id = "unity-grid-and-snap-toolbar"; public GridAndSnapToolBar() : base( "Tools/Snap Size", "SceneView/Grids", "Tools/Snap Settings", "SceneView/Snap Increment") {} } } // namespace
UnityCsReference/Editor/Mono/SceneView/SceneViewToolbars.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/SceneView/SceneViewToolbars.cs", "repo_id": "UnityCsReference", "token_count": 2828 }
330
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine.Bindings; using UnityEngine.Scripting; using UnityEditor; using UnityEditor.Scripting; using UnityEditor.Scripting.APIUpdater; using UnityEditor.Scripting.ScriptCompilation; using UnityEditor.Utils; using UnityEditor.VersionControl; using UnityEditor.PackageManager; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using Mono.Cecil; using System.Text; namespace UnityEditorInternal.APIUpdating { //TODO: ADRIANO: // // 1. If an error happen (in updater) during package adding/updating we may not update assemblies. We need to report to user. // Ex: PA (1.0) -> PB (1.0); Add PB, PA; Update PB (to 1.1) and introduce update config; if an error happen when processing PB (1.1) // we may not apply updates to PA. //*undocumented* [NativeHeader("Editor/Src/Scripting/APIUpdater/APIUpdaterManager.h")] [StaticAccessor("APIUpdaterManager::GetInstance()", StaticAccessorType.Dot)] internal static class APIUpdaterManager { [RequiredByNativeCode] public static string[] GetDefinedSymbolsFor(string assemblyName) { return UnityEditor.Compilation.CompilationPipeline.GetDefinesFromAssemblyName(Path.GetFileNameWithoutExtension(assemblyName)); } private const string k_AssemblyDependencyGraphFilePath = "Library/APIUpdater/project-dependencies.graph"; private static HashSet<AssemblyUpdateCandidate> s_AssembliesToUpdate; internal static extern bool WaitForVCSServerConnection(); [NativeName("NumberOfTimesAsked")] public static extern int numberOfTimesAsked { get; set; } public static extern bool DoesCommandLineIndicateAPIUpdatingShouldHappenWithoutConsent(); public static extern bool DoesCommandLineIndicateAPIUpdatingShouldBeDeclined(); public static extern void ResetNumberOfTimesAsked(); internal static extern bool isInProjectCreation { [NativeName("IsInProjectCreation")] get; } // Used by tests only public static extern void MakeNextAPIUpdateOfferReturn(bool value); public static extern void ResetNextAPIUpdateOfferReturn(); // Sets/gets a regular expression used to filter configuration sources assemblies // by name. public static extern string ConfigurationSourcesFilter { get; set; } internal static extern bool AskForConsent(string[] assemblyPaths); // These methods are used to persist the list of assemblies to be updated in the native side in order to preserve this list across domain reloads. static extern void ResetListOfAssembliesToBeUpdateInNativeSide(); static extern void AddAssemblyToBeUpdatedInNativeSide(string assemblyName, string assemblyPath, string[] assemblyUpdateConfigSources); static extern bool GetAndRemoveAssemblyToBeUpdatedFromNative(out string outAssemblyName, out string outAssemblyPath, List<string> outUpdateConfigSources); [RequiredByNativeCode] internal static void UpdateAssemblies() { var assembliesToUpdate = GetAssembliesToBeUpdated(); if (assembliesToUpdate.Count == 0) return; var assemblyPaths = assembliesToUpdate.Select(c => c.Path); var anyAssemblyInAssetsFolder = assemblyPaths.Any(path => path.IndexOf("Assets/", StringComparison.OrdinalIgnoreCase) != -1); var sw = Stopwatch.StartNew(); var updatedCount = 0; var assembliesToCheckCount = assembliesToUpdate.Count; var tasks = assembliesToUpdate.Select(a => new AssemblyUpdaterUpdateTask(a)).ToArray(); foreach (var task in tasks) ThreadPool.QueueUserWorkItem(RunAssemblyUpdaterTask, task); var finishOk = false; var waitEvents = tasks.Select(t => t.Event).ToArray(); var timeout = TimeSpan.FromSeconds(30); if (WaitOnManyEvents(waitEvents, timeout)) { if (!HandleAssemblyUpdaterErrors(tasks)) { updatedCount = ProcessSuccessfulUpdates(tasks); finishOk = updatedCount >= 0; } } else { LogTimeoutError(tasks); } sw.Stop(); APIUpdaterLogger.WriteToFile(L10n.Tr("Update finished with {0} in {1} ms ({2}/{3} assembly(ies) updated)."), finishOk ? L10n.Tr("success") : L10n.Tr("error"), sw.ElapsedMilliseconds, updatedCount >= 0 ? updatedCount : 0, assembliesToCheckCount); PersistListOfAssembliesToUpdate(); } internal static bool WaitOnManyEvents(IEnumerable<WaitHandle> waitEvents, TimeSpan timeout) { var timeBomb = DateTime.Now + timeout; foreach (var batch in BatchWaitHandles(waitEvents)) { if (!WaitHandle.WaitAll(batch, timeBomb - DateTime.Now)) { return false; } } return true; } private static IEnumerable<WaitHandle[]> BatchWaitHandles(IEnumerable<WaitHandle> handles) { // According to documentation (https://docs.microsoft.com/en-us/dotnet/api/system.threading.waithandle.waitall?view=net-5.0#System_Threading_WaitHandle_WaitAll_System_Threading_WaitHandle___System_Int32) // WaitAll accepts a maximum of 64 handles. So the max size of the returned batch will be 64 const int batchMaxSize = 64; var currentBatch = new List<WaitHandle>(batchMaxSize); foreach (var handle in handles) { currentBatch.Add(handle); if (currentBatch.Count == batchMaxSize) { yield return currentBatch.ToArray(); currentBatch = new List<WaitHandle>(batchMaxSize); } } if (currentBatch.Count > 0) { yield return currentBatch.ToArray(); } } /* * We store this list at native side so it don't get lost at domain reloads * Code should call `GetAssembliesToBeUpdated()` instead of using `assembliesToUpdate` direclty. */ private static void PersistListOfAssembliesToUpdate() { ResetListOfAssembliesToBeUpdateInNativeSide(); foreach (var assembly in GetAssembliesToBeUpdated()) { // no need to persist the dependency graph. See comment in RestoreFromNative() method. AddAssemblyToBeUpdatedInNativeSide(assembly.Name, assembly.Path, assembly.UpdateConfigSources.ToArray()); } } private static HashSet<AssemblyUpdateCandidate> GetAssembliesToBeUpdated() { if (s_AssembliesToUpdate == null) { s_AssembliesToUpdate = new HashSet<AssemblyUpdateCandidate>(); RestoreFromNative(); } return s_AssembliesToUpdate; } private static void RestoreFromNative() { string assemblyName; string assemblyPath; List<string> updateConfigSources = new List<string>(); while (GetAndRemoveAssemblyToBeUpdatedFromNative(out assemblyName, out assemblyPath, updateConfigSources)) { s_AssembliesToUpdate.Add(new AssemblyUpdateCandidate { Name = assemblyName, Path = assemblyPath, DependencyGraph = null, // No need to restore the dependency graph. It is only used during the collection phase (i.e, to figure out the list of // potential candidates for updating which happens before this step. UpdateConfigSources = updateConfigSources }); updateConfigSources = new List<string>(); } } private static void LogTimeoutError(AssemblyUpdaterCheckAssemblyPublishConfigsTask[] tasks, TimeSpan waitedTime) { var timedOut = tasks.Where(t => !t.Event.WaitOne(0)); var sb = new StringBuilder(L10n.Tr("Timeout while checking assemblies:")); foreach (var task in timedOut) { sb.AppendFormat("{1}{0}", Environment.NewLine, task.Candidate.Path); } sb.AppendFormat(L10n.Tr("{0}Timeout: {1} ms"), Environment.NewLine, waitedTime.Milliseconds); sb.AppendFormat(L10n.Tr("{0}Update configurations from those assemblies may have not been applied."), Environment.NewLine); APIUpdaterLogger.WriteErrorToConsole(sb.ToString()); } private static void LogTimeoutError(AssemblyUpdaterUpdateTask[] tasks) { var completedSuccessfully = tasks.Where(t => t.Event.WaitOne(0)).ToArray(); var timedOutTasks = tasks.Where(t => !t.Event.WaitOne(0)); var sb = new StringBuilder(L10n.Tr("Timeout while updating assemblies:")); foreach (var updaterTask in timedOutTasks) { sb.AppendFormat("{1} (Output: {2}){0}", Environment.NewLine, updaterTask.Candidate.Path, updaterTask.OutputPath); } ReportIgnoredAssembliesDueToPreviousErrors(sb, completedSuccessfully); APIUpdaterLogger.WriteErrorToConsole(sb.ToString()); } private static bool HandleAssemblyUpdaterErrors(IList<AssemblyUpdaterUpdateTask> allTasks) { var tasksWithErrors = allTasks.Where(t => APIUpdaterAssemblyHelper.IsError(t.Result) || APIUpdaterAssemblyHelper.IsUnknown(t.Result) || t.Exception != null).ToArray(); if (tasksWithErrors.Length == 0) return false; var sb = new StringBuilder(L10n.Tr("Unable to update following assemblies:")); foreach (var updaterTask in tasksWithErrors) { sb.Append(FormatErrorFromTask(updaterTask)); } ReportIgnoredAssembliesDueToPreviousErrors(sb, allTasks.Except(tasksWithErrors).ToArray()); APIUpdaterLogger.WriteErrorToConsole(sb.ToString()); return true; } static string FormatErrorFromTask(AssemblyUpdaterUpdateTask updaterTask) { // this may happen if mono.exe (which we use to run AssemblyUpdater.exe) cannot run the executable // and reports an error (for example, *file not found*) var unknownStatusMessage = APIUpdaterAssemblyHelper.IsUnknown(updaterTask.Result) ? L10n.Tr(" does not match any return code from AssemblyUpdater.exe") : string.Empty; var exceptionMessage = updaterTask.Exception != null ? $"{Environment.NewLine}\tException: {updaterTask.Exception}" : string.Empty; return string.Format("{1} (Name = {2}, Error = {3}{7}) (Output: {4}){0}{5}{0}{6}{0}{8}", Environment.NewLine, updaterTask.Candidate.Path, updaterTask.Candidate.Name, updaterTask.Result, updaterTask.OutputPath, updaterTask.StdOut, updaterTask.StdErr, unknownStatusMessage, exceptionMessage); } private static void ReportIgnoredAssembliesDueToPreviousErrors(StringBuilder sb, IList<AssemblyUpdaterUpdateTask> completedSuccessfully) { if (completedSuccessfully.Count == 0) return; sb.AppendFormat(L10n.Tr("Following assemblies were successfully updated but due to the failed ones above they were ignored (not copied to the destination folder):")); foreach (var updaterTask in completedSuccessfully) { sb.AppendFormat("{1}\t(Result = {2}) (Output: {3}){0}{4}{0}", Environment.NewLine, updaterTask.Candidate.Path, updaterTask.Result, updaterTask.OutputPath, updaterTask.StdOut); } } private static int ProcessSuccessfulUpdates(AssemblyUpdaterUpdateTask[] tasks) { var assembliesToUpdate = GetAssembliesToBeUpdated(); var noUpdatesRequiredAssemblies = tasks.Where(t => t.Result == APIUpdaterAssemblyHelper.Success); // Assemblies checked which does not requires updates. if (noUpdatesRequiredAssemblies.Any()) { APIUpdaterLogger.WriteToFile("Assemblies not requiring updates:"); foreach (var noUpdateRequired in noUpdatesRequiredAssemblies) { APIUpdaterLogger.WriteToFile($"{noUpdateRequired.Candidate.Path}{FormattedStoutFrom(noUpdateRequired)}"); } } var succeededUpdates = tasks.Where(t => t.Result == APIUpdaterAssemblyHelper.UpdatesApplied); if (!succeededUpdates.Any()) { assembliesToUpdate.Clear(); return 0; } var assembliesRequiringConsent = FilterOutLocalAndEmbeddedPackagesWhenAskingForConsent(assembliesToUpdate.Select(a => a.Path)).ToArray(); if (assembliesRequiringConsent.Length > 0 && !AskForConsent(assembliesRequiringConsent)) { APIUpdaterLogger.WriteToFile(L10n.Tr("User declined to run APIUpdater")); return 0; } var updatedAssemblyPaths = succeededUpdates.Select(u => u.Candidate.Path).ToArray(); if (!CheckoutFromVCSIfNeeded(updatedAssemblyPaths)) return -1; APIUpdaterHelper.HandlePackageFilePaths(updatedAssemblyPaths); if (!APIUpdaterHelper.CheckReadOnlyFiles(updatedAssemblyPaths)) return 0; foreach (var succeed in succeededUpdates) { APIUpdaterLogger.WriteToFile("{0}{1}", Environment.NewLine, succeed.StdOut); FileUtil.MoveFileIfExists(succeed.OutputPath, succeed.Candidate.Path); } assembliesToUpdate.Clear(); return succeededUpdates.Count(); bool CheckoutFromVCSIfNeeded(string[] assemblyPathsToCheck) { // Only try to connect to VCS if there are files under VCS that need to be updated var assembliesInAssetsFolder = assemblyPathsToCheck.Where(path => path.IndexOf("Assets/", StringComparison.OrdinalIgnoreCase) != -1).ToArray(); if (!assembliesInAssetsFolder.Any()) return true; if (!WaitForVCSServerConnection()) { return false; } var failedToCheckoutFiles = !APIUpdaterHelper.MakeEditable(assembliesInAssetsFolder); if (failedToCheckoutFiles) { assembliesToUpdate.Clear(); return false; } return true; } IEnumerable<string> FilterOutLocalAndEmbeddedPackagesWhenAskingForConsent(IEnumerable<string> ass) { foreach (var path in ass.Select(path => path.Replace("\\", "/"))) // package manager paths are always separated by / { var packageInfo = UnityEditor.PackageManager.PackageInfo.FindForAssetPath(path); if (packageInfo == null || packageInfo.source == PackageSource.Local || packageInfo.source == PackageSource.Embedded) yield return path; } } static string FormattedStoutFrom(AssemblyUpdaterUpdateTask task) { if (task.StdOut.Length == 0) return string.Empty; return $" (stdout below):{Environment.NewLine}{task.StdOut}{Environment.NewLine}"; } } private static void RunAssemblyUpdaterTask(object o) { var task = (AssemblyUpdaterTask)o; string stdOut = string.Empty; string stdErr = string.Empty; try { task.Result = APIUpdaterAssemblyHelper.Run(task.Arguments, AssemblyUpdaterTask.WorkingDirectory, out stdOut, out stdErr); } catch (Exception ex) { task.Exception = ex; } finally { task.StdErr = stdErr; task.StdOut = stdOut; task.Event.Set(); } } internal static bool HasPrecompiledAssembliesToUpdate() { return GetAssembliesToBeUpdated().Count > 0; } [RequiredByNativeCode] internal static void ProcessImportedAssemblies(string[] assemblies) { var sw = Stopwatch.StartNew(); var depGraph = UpdateDependencyGraph(assemblies); var sortedCandidatesForUpdating = FindCandidatesForUpdatingSortedByDependency(assemblies, depGraph); var assembliesToUpdate = GetAssembliesToBeUpdated(); CollectImportedAssembliesToBeUpdated(assembliesToUpdate, sortedCandidatesForUpdating); UpdatePublishUpdaterConfigStatusAndAddDependents(assembliesToUpdate, sortedCandidatesForUpdating, depGraph); SaveDependencyGraph(depGraph, k_AssemblyDependencyGraphFilePath); sw.Stop(); APIUpdaterLogger.WriteToFile(L10n.Tr("Processing imported assemblies took {0} ms ({1}/{2} assembly(ies))."), sw.ElapsedMilliseconds, assembliesToUpdate.Count, sortedCandidatesForUpdating.Count()); UpdateAssemblies(); } private static void CollectImportedAssembliesToBeUpdated(HashSet<AssemblyUpdateCandidate> assembliesToUpdate, IEnumerable<AssemblyUpdateCandidate> candidatesForUpdating) { foreach (var importedCandidate in candidatesForUpdating) { if (importedCandidate.MayRequireUpdating) assembliesToUpdate.Add(importedCandidate); } } private static void UpdatePublishUpdaterConfigStatusAndAddDependents(HashSet<AssemblyUpdateCandidate> assembliesToUpdate, IEnumerable<AssemblyUpdateCandidate> candidatesForUpdating, AssemblyDependencyGraph depGraph) { var tasks = candidatesForUpdating .Where(a => AssemblyHelper.IsManagedAssembly(a.Path) && IsAssemblyInPackageFolder(a)) .Select(a => new AssemblyUpdaterCheckAssemblyPublishConfigsTask(a)).ToArray(); if (tasks.Length == 0) return; foreach (var task in tasks) { ThreadPool.QueueUserWorkItem(RunAssemblyUpdaterTask, task); } var waitEvents = tasks.Select(t => t.Event).ToArray(); var timeout = TimeSpan.FromSeconds(30); if (!WaitHandle.WaitAll(waitEvents, timeout)) { LogTimeoutError(tasks, timeout); } var nonTimedOutTasks = tasks.Where(t => t.Event.WaitOne(0)).ToArray(); if (HandleCheckAssemblyPublishUpdaterConfigErrors(nonTimedOutTasks)) return; foreach (var task in nonTimedOutTasks) { if ((task.Result & APIUpdaterAssemblyHelper.ContainsUpdaterConfigurations) == APIUpdaterAssemblyHelper.ContainsUpdaterConfigurations) { var importedCandidate = task.Candidate; importedCandidate.DependencyGraph.Status |= AssemblyStatus.PublishesUpdaterConfigurations; AddDependentAssembliesToUpdateList(assembliesToUpdate, depGraph, importedCandidate); } } } private static bool HandleCheckAssemblyPublishUpdaterConfigErrors(AssemblyUpdaterCheckAssemblyPublishConfigsTask[] nonTimedOutTasks) { var withErrors = nonTimedOutTasks.Where(t => APIUpdaterAssemblyHelper.IsError(t.Result) || t.Exception != null).ToArray(); if (withErrors.Length == 0) return false; var sb = new StringBuilder(L10n.Tr("Failed to check following assemblies for updater configurations:\r\n")); foreach (var failedAssemblyInfo in withErrors) { sb.AppendFormat(L10n.Tr("{0} (ret = {1}):\r\n{2}{3}{4}"), failedAssemblyInfo.Candidate.Path, failedAssemblyInfo.Result, HumanMessage("StdOut", failedAssemblyInfo.StdOut), HumanMessage("StdErr", failedAssemblyInfo.StdErr), HumanMessage("Exception", failedAssemblyInfo.Exception?.ToString())); } sb.Append("\r\n--------------"); APIUpdaterLogger.WriteErrorToConsole(sb.ToString()); return true; } private static string HumanMessage(string header, string msg) { if (string.IsNullOrEmpty(msg)) return string.Empty; return $"{header}:\r\n{msg}\r\n"; } private static void AddDependentAssembliesToUpdateList(HashSet<AssemblyUpdateCandidate> assembliesToUpdate, AssemblyDependencyGraph depGraph, AssemblyUpdateCandidate imported) { var dependents = depGraph.GetDependentsOf(imported.Name); var candidatesToUpdate = dependents.Select(assemblyName => CandidateForUpdatingFrom(assemblyName, depGraph)); foreach (var candidate in candidatesToUpdate.Where(c => c != null)) assembliesToUpdate.Add(candidate); } private static bool IsAssemblyInPackageFolder(AssemblyUpdateCandidate candidate) { return candidate.Path.IsInPackage(); } /* * Given a list of assemblies, returns those that references assemblies contributing updater configurations * sorted by dependency (i.e, given assemblies, A, B & C such A -> B -> C, should return in C, B, A order) */ private static IEnumerable<AssemblyUpdateCandidate> FindCandidatesForUpdatingSortedByDependency(IEnumerable<string> assemblyPaths, AssemblyDependencyGraph depGraph) { var candidates = new HashSet<AssemblyUpdateCandidate>(); foreach (var assemblyPath in assemblyPaths) { var assemblyName = Path.GetFileNameWithoutExtension(assemblyPath); var depInfo = depGraph.FindAssembly(assemblyName); Debug.Assert(depInfo != null); // Any referenced assemblies contains updater configs? var referencedAssembliesWithUpdaterConfigs = depInfo.Dependencies.Where(a => (depGraph.FindAssembly(a.Name)?.Status & AssemblyStatus.PublishesUpdaterConfigurations) == AssemblyStatus.PublishesUpdaterConfigurations); if (referencedAssembliesWithUpdaterConfigs.Any()) { IEnumerable<string> updateConfigSources = ResolvePathOfAssembliesWithUpdaterConfigurations(referencedAssembliesWithUpdaterConfigs); candidates.Add(new AssemblyUpdateCandidate { Name = assemblyName, Path = assemblyPath, DependencyGraph = depInfo, UpdateConfigSources = updateConfigSources }); } } // add the candidates sorted based on the dependency graph... var result = new List<AssemblyUpdateCandidate>(); foreach (var assemblyName in depGraph.SortedDependents()) { // We may have assemblies with the same name in different folders // (for example GUISystem/Standalone/UnityEngine.UI.dll & GUISystem/UnityEngine.UI.dll) var filteredCandidates = candidates.Where(c => CompareIgnoreCase(c.Name, assemblyName)); result.AddRange(filteredCandidates); } return result; } // We only resolve Unity assemblies and assemblies coming from packages. // We may want to change this to support *any assembly* to contribute with updater configurations private static IEnumerable<string> ResolvePathOfAssembliesWithUpdaterConfigurations(IEnumerable<AssemblyDependencyGraph.DependencyEntry> assemblies) { foreach (var assemblyName in assemblies) { var resolved = ResolveAssemblyPath(assemblyName.Name); if (resolved != null) yield return Path.GetFullPath(resolved); } } private static string ResolveAssemblyPath(string assemblyName) { //find the assembly in Data/Managed or Data/Managed/UnityEngine var assemblyFileName = assemblyName + ".dll"; var managedPath = GetUnityEditorManagedPath(); var pathInManagedFolder = Path.Combine(managedPath, assemblyFileName); if (File.Exists(pathInManagedFolder)) return pathInManagedFolder; var pathInUnityEngineFolder = Path.Combine(Path.Combine(managedPath, "UnityEngine"), assemblyFileName); if (File.Exists(pathInUnityEngineFolder)) return pathInUnityEngineFolder; var assetsAssemblies = new HashSet<string>(AssetDatabase.GetAllAssetPaths().Where(assetPath => Path.GetExtension(assetPath) == ".dll").ToArray()); // If the same assembly exist in multiple folders, choose the shortest path one. var resolvedList = assetsAssemblies.Where(a => CompareIgnoreCase(AssemblyNameFromPath(a), assemblyName)).ToArray(); var assemblyPathInAssetsFolder = resolvedList.OrderBy(path => path.Length).FirstOrDefault(); if (resolvedList.Length > 1) { APIUpdaterLogger.WriteToFile(L10n.Tr("Warning : Multiple matches found for assembly name '{0}'. Shortest path one ({1}) chosen as the source of updates. Full list: {2}"), assemblyName, assemblyPathInAssetsFolder, string.Join(Environment.NewLine, resolvedList)); } if (assemblyPathInAssetsFolder != null && (assemblyPathInAssetsFolder.IsInPackage() || assemblyPathInAssetsFolder.IsInAssetsFolder())) { return assemblyPathInAssetsFolder; } return null; } private static bool CompareIgnoreCase(string lhs, string rhs) { return string.Compare(lhs, rhs, StringComparison.InvariantCultureIgnoreCase) == 0; } private static AssemblyUpdateCandidate CandidateForUpdatingFrom(string candidateAssemblyName, AssemblyDependencyGraph rootDepGraph) { string resolvedAssemblyPath = ResolveAssemblyPath(candidateAssemblyName); // this may happen if, for instance, after setting the dependency A -> B, *B* gets removed and *A* gets updated to a new version (we don't remove // the dependency from the graph. if (string.IsNullOrEmpty(resolvedAssemblyPath)) return null; var depGraph = rootDepGraph.FindAssembly(candidateAssemblyName); var referencesAssemblyWithUpdaterConfigs = depGraph.Dependencies.Where(depAssembly => (rootDepGraph.FindAssembly(depAssembly.Name)?.Status & AssemblyStatus.PublishesUpdaterConfigurations) == AssemblyStatus.PublishesUpdaterConfigurations); var updaterConfigSources = ResolvePathOfAssembliesWithUpdaterConfigurations(referencesAssemblyWithUpdaterConfigs); return new AssemblyUpdateCandidate { Name = candidateAssemblyName, Path = resolvedAssemblyPath, DependencyGraph = depGraph, UpdateConfigSources = updaterConfigSources }; } private static AssemblyDependencyGraph UpdateDependencyGraph(IEnumerable<string> addedAssemblyPaths) { var dependencyGraph = ReadOrCreateAssemblyDependencyGraph(k_AssemblyDependencyGraphFilePath); foreach (var addedAssemblyPath in addedAssemblyPaths) { var assemblyDependencies = AssemblyDependenciesFrom(addedAssemblyPath); dependencyGraph.SetDependencies(AssemblyNameFromPath(addedAssemblyPath), assemblyDependencies); FixUnityAssembliesStatusInDependencyGraph(dependencyGraph, assemblyDependencies); } SaveDependencyGraph(dependencyGraph, k_AssemblyDependencyGraphFilePath); return dependencyGraph; } private static void FixUnityAssembliesStatusInDependencyGraph(AssemblyDependencyGraph dependencyGraph, IEnumerable<string> assemblyNames) { var unityAssemblies = assemblyNames.Where(an => an.StartsWith("UnityEngine") || an.StartsWith("UnityEditor")); foreach (var assemblyName in unityAssemblies) { var dep = dependencyGraph.FindAssembly(assemblyName); dep.Status |= AssemblyStatus.PublishesUpdaterConfigurations; // we know that those assemblies contains update configs } } private static string[] AssemblyDependenciesFrom(string assemblyPath) { using (var a = AssemblyDefinition.ReadAssembly(assemblyPath, new ReaderParameters { ReadSymbols = false })) { return a.MainModule.AssemblyReferences.Select(assemblyReference => assemblyReference.Name).ToArray(); } } private static void SaveDependencyGraph(AssemblyDependencyGraph dependencyGraph, string path) { try { var targetDir = Path.GetDirectoryName(path); if (!Directory.Exists(targetDir)) { Directory.CreateDirectory(targetDir); } using (var file = File.Open(path, System.IO.FileMode.Create)) { dependencyGraph.SaveTo(file); } } catch (UnauthorizedAccessException ex) { APIUpdaterLogger.WriteToFile(string.Format(L10n.Tr("Failed to save assembly dependency graph ({0}). Exception: {1}")), path, ex); } catch (IOException ex) { APIUpdaterLogger.WriteToFile(string.Format(L10n.Tr("Failed to save assembly dependency graph ({0}). Exception: {1}")), path, ex); } } private static AssemblyDependencyGraph ReadOrCreateAssemblyDependencyGraph(string assemblyDependencyGraphFilePath) { try { if (File.Exists(assemblyDependencyGraphFilePath)) { using (var stream = File.OpenRead(assemblyDependencyGraphFilePath)) { return AssemblyDependencyGraph.LoadFrom(stream); } } } catch (IOException e) { APIUpdaterLogger.WriteToFile(string.Format(L10n.Tr("Failed to read assembly dependency graph ({0}). Exception: {1}")), assemblyDependencyGraphFilePath, e); } return new AssemblyDependencyGraph(); } private static string AssemblyNameFromPath(string assemblyPath) { return Path.GetFileNameWithoutExtension(assemblyPath); } private static string GetUnityEditorManagedPath() { return Path.Combine(MonoInstallationFinder.GetFrameWorksFolder(), "Managed"); } } internal class AssemblyUpdateCandidate : IEquatable<AssemblyUpdateCandidate> { public string Name; public string Path; public AssemblyDependencyGraph.DependencyEntry DependencyGraph; public IEnumerable<string> UpdateConfigSources; public bool MayRequireUpdating { get { return UpdateConfigSources.Any(); } } public static implicit operator bool(AssemblyUpdateCandidate a) { return a.Name != null; } public override string ToString() { return string.Format("{0} ({1})", Name, Path); } public override int GetHashCode() { return Path.GetHashCode() * 37 + Name.GetHashCode(); } public override bool Equals(object obj) { var other = obj as AssemblyUpdateCandidate; if (other == null) return false; return Equals(other); } public bool Equals(AssemblyUpdateCandidate other) { return other.Name == Name && other.Path == Path; } } internal class AssemblyUpdaterTask { private AssemblyUpdateCandidate _candidate; public string StdOut { set; get; } public string StdErr { set; get; } static AssemblyUpdaterTask() { WorkingDirectory = UnityEngine.Application.dataPath + "/.."; // We can't access this property in a "non main thread" so we resolve and cache it in the main thread. } public AssemblyUpdaterTask(AssemblyUpdateCandidate a) { _candidate = a; Event = new ManualResetEvent(false); } public string Arguments { get; internal set; } public EventWaitHandle Event { get; internal set; } public int Result { get; internal set; } public AssemblyUpdateCandidate Candidate { get { return _candidate; } } public Exception Exception { get; internal set; } public static string WorkingDirectory { get; internal set; } } internal class AssemblyUpdaterUpdateTask : AssemblyUpdaterTask { public AssemblyUpdaterUpdateTask(AssemblyUpdateCandidate a) : base(a) { OutputPath = Path.GetTempFileName(); Arguments = APIUpdaterAssemblyHelper.ArgumentsForUpdateAssembly(a.Path, OutputPath, a.UpdateConfigSources); } public string OutputPath { get; internal set; } } internal class AssemblyUpdaterCheckAssemblyPublishConfigsTask : AssemblyUpdaterTask { public AssemblyUpdaterCheckAssemblyPublishConfigsTask(AssemblyUpdateCandidate a) : base(a) { Arguments = APIUpdaterAssemblyHelper.ArgumentsForCheckingForUpdaterConfigsOn(a.Path); } } }
UnityCsReference/Editor/Mono/Scripting/APIUpdater/APIUpdaterManager.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Scripting/APIUpdater/APIUpdaterManager.bindings.cs", "repo_id": "UnityCsReference", "token_count": 14992 }
331
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; namespace UnityEditor.Compilation { public class AssemblyDefinitionException : Exception { public string[] filePaths { get; } public AssemblyDefinitionException(string message, params string[] filePaths) : base(message) { this.filePaths = filePaths; } } [Obsolete("PrecompiledAssemblyException is no longer being thrown by Unity and will be removed.")] public class PrecompiledAssemblyException : Exception { public string[] filePaths { get; } public PrecompiledAssemblyException(string message, params string[] filePaths) : base(message) { this.filePaths = filePaths; } } }
UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/AssemblyDefinitionException.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/AssemblyDefinitionException.cs", "repo_id": "UnityCsReference", "token_count": 306 }
332
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; namespace UnityEditor.Scripting.ScriptCompilation { internal static class CompilationPipelineCommonHelper { const string k_UnityAssemblyPrefix = "Unity."; const string k_CompilerClientSuffix = ".Compiler.Client"; public static bool ShouldAdd(string assemblyName) { var name = AssetPath.GetAssemblyNameWithoutExtension(assemblyName); if (name.StartsWith(k_UnityAssemblyPrefix, StringComparison.OrdinalIgnoreCase) && name.EndsWith(k_CompilerClientSuffix, StringComparison.OrdinalIgnoreCase)) return true; return false; } public static void UpdateScriptAssemblyReference(ref ScriptAssembly scriptAssembly) { int referencesLength = scriptAssembly.References.Length; var newReferences = new string[referencesLength + 1]; Array.Copy(scriptAssembly.References, newReferences, referencesLength); newReferences[referencesLength] = AssetPath.Combine(EditorApplication.applicationContentsPath, "Managed", "Unity.CompilationPipeline.Common.dll"); scriptAssembly.References = newReferences; } } }
UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/CompilationPipelineCommonHelper.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/CompilationPipelineCommonHelper.cs", "repo_id": "UnityCsReference", "token_count": 482 }
333
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; namespace UnityEditor.Scripting.ScriptCompilation { internal interface IVersionTypeTraits { bool IsAllowedFirstCharacter(char c, bool strict = false); bool IsAllowedLastCharacter(char c, bool strict = false); bool IsAllowedCharacter(char c); } internal static class VersionTypeTraitsUtils { public static bool IsCharDigit(char c) { return (c >= '0' && c <= '9'); } public static bool IsCharLetter(char c) { return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'; } } internal interface IVersion<TVersion> : IEquatable<TVersion>, IComparable<TVersion>, IComparable where TVersion : struct { bool IsInitialized { get; } TVersion Parse(string version, bool strict = false); IVersionTypeTraits GetVersionTypeTraits(); } internal static class VersionUtils { public static string ConsumeVersionComponentFromString(string value, ref int cursor, Func<char, bool> isEnd) { int length = 0; for (int i = cursor; i < value.Length; i++) { if (isEnd(value[i])) break; length++; } int newIndex = cursor; cursor += length; return value.Substring(newIndex, length); } public static bool TryConsumeIntVersionComponentFromString(string value, ref int cursor, Func<char, bool> isEnd, out int result, bool zeroIfEmpty = false) { var part = ConsumeVersionComponentFromString(value, ref cursor, isEnd); if (zeroIfEmpty && part.Length == 0) { result = 0; return true; } return int.TryParse(part, out result); } } }
UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/IVersion.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/IVersion.cs", "repo_id": "UnityCsReference", "token_count": 882 }
334
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Globalization; using System.Runtime.CompilerServices; using UnityEngine; namespace UnityEditor.Scripting.ScriptCompilation { static class Utility { public static char FastToLower(char c) { // ASCII non-letter characters and // lower case letters. if (c < 'A' || (c > 'Z' && c <= 'z')) { return c; } if (c >= 'A' && c <= 'Z') { return (char)(c + 32); } return Char.ToLower(c, CultureInfo.InvariantCulture); } public static string FastToLower(string str) { int length = str.Length; var chars = new char[length]; for (int i = 0; i < length; ++i) { chars[i] = FastToLower(str[i]); } return new string(chars); } public static bool FastStartsWith(string str, string prefix, string prefixLowercase) { if (str == null || prefix == null) { return false; } int strLength = str.Length; int prefixLength = prefix.Length; if (prefixLength > strLength) return false; int lastPrefixCharIndex = prefixLength - 1; // Check last char in prefix is equal. Since we are comparing // file paths against directory paths, the last char will be '/'. if (str[lastPrefixCharIndex] != prefix[lastPrefixCharIndex]) return false; for (int i = 0; i < prefixLength; ++i) { if (str[i] == prefix[i]) continue; char strC = FastToLower(str[i]); if (strC != prefixLowercase[i]) return false; } return true; } public static bool IsAssetsPath(string path) { const string assetsLowerCase = "assets"; const string assetsUpperCase = "ASSETS"; if (path.Length < 7) return false; if (path[6] != '/') return false; for (int i = 0; i < 6; ++i) { if (path[i] != assetsLowerCase[i] && path[i] != assetsUpperCase[i]) return false; } return true; } public static string ReadTextAsset(string path) { if (IsAssetsPath(path)) { var textAsset = AssetDatabase.LoadAssetAtPath<UnityEngine.TextAsset>(path); if (textAsset != null) return textAsset.text; } // Support out of project reading of files for tests. return System.IO.File.ReadAllText(path); } public static string FileNameWithoutExtension(string path) { if (string.IsNullOrEmpty(path)) { return ""; } var indexOfDot = -1; var indexOfSlash = 0; for (var i = path.Length - 1; i >= 0; i--) { if (indexOfDot == -1 && path[i] == '.') { indexOfDot = i; } if (indexOfSlash == 0 && path[i] == '/' || path[i] == '\\') { indexOfSlash = i + 1; break; } } if (indexOfDot == -1) { indexOfDot = path.Length; } return path.Substring(indexOfSlash, indexOfDot - indexOfSlash); } public static bool IsPathsEqual(ReadOnlySpan<char> left, ReadOnlySpan<char> right) { if (left.Length != right.Length) return false; for (var index = 0; index < left.Length; index++) { var leftCurrentChar = left[index]; var rightCurrentChar = right[index]; if (IsPathSeparator(leftCurrentChar) && IsPathSeparator(rightCurrentChar)) { continue; } if (leftCurrentChar != rightCurrentChar) return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsPathSeparator(char character) { return character == '/' || character == '\\'; } } }
UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/Utility.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/Utility.cs", "repo_id": "UnityCsReference", "token_count": 2521 }
335
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; namespace UnityEditor.SearchService { [AttributeUsage(AttributeTargets.Class)] public class SceneSearchEngineAttribute : Attribute {} public class SceneSearchContext : ISearchContext { public Guid guid { get; } = Guid.NewGuid(); public SearchEngineScope engineScope { get; protected set; } = SceneSearch.EngineScope; public IEnumerable<Type> requiredTypes { get; set; } public IEnumerable<string> requiredTypeNames { get; set; } public HierarchyProperty rootProperty { get; set; } internal SearchFilter searchFilter { get; set; } } public interface ISceneSearchEngine : IFilterEngine<HierarchyProperty> {} [InitializeOnLoad] public static class SceneSearch { static SearchApiBaseImp<SceneSearchEngineAttribute, ISceneSearchEngine> s_EngineImp; static SearchApiBaseImp<SceneSearchEngineAttribute, ISceneSearchEngine> engineImp { get { if (s_EngineImp == null) StaticInit(); return s_EngineImp; } } public const SearchEngineScope EngineScope = SearchEngineScope.Scene; static SceneSearch() { EditorApplication.tick += StaticInit; } private static void StaticInit() { EditorApplication.tick -= StaticInit; s_EngineImp = s_EngineImp ?? new SearchApiBaseImp<SceneSearchEngineAttribute, ISceneSearchEngine>(EngineScope, "Scene"); } internal static bool Filter(string query, HierarchyProperty objectToFilter, SceneSearchContext context) { var activeEngine = engineImp.activeSearchEngine; try { return activeEngine.Filter(context, query, objectToFilter); } catch (Exception ex) { engineImp.HandleUserException(ex); return false; } } internal static bool HasEngineOverride() { return engineImp.HasEngineOverride(); } internal static void BeginSession(SceneSearchContext context) { engineImp.BeginSession(context); } internal static void EndSession(SceneSearchContext context) { engineImp.EndSession(context); } internal static void BeginSearch(string query, SceneSearchContext context) { engineImp.BeginSearch(query, context); } internal static void EndSearch(SceneSearchContext context) { engineImp.EndSearch(context); } internal static ISceneSearchEngine GetActiveSearchEngine() { return engineImp.GetActiveSearchEngine(); } internal static void SetActiveSearchEngine(string searchEngineName) { engineImp.SetActiveSearchEngine(searchEngineName); } public static void RegisterEngine(ISceneSearchEngine engine) { engineImp.RegisterEngine(engine); } public static void UnregisterEngine(ISceneSearchEngine engine) { engineImp.UnregisterEngine(engine); } } class SceneSearchSessionHandler : SearchSessionHandler { public SceneSearchSessionHandler() : base(SearchEngineScope.Scene) {} public bool Filter(string query, HierarchyProperty objectToFilter) { using (new SearchSessionOptionsApplicator(m_Api, m_Options)) return SceneSearch.Filter(query, objectToFilter, (SceneSearchContext)context); } } }
UnityCsReference/Editor/Mono/Search/SceneSearch.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Search/SceneSearch.cs", "repo_id": "UnityCsReference", "token_count": 1591 }
336
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Reflection; using UnityEditor.Inspector.GraphicsSettingsInspectors; using UnityEngine; using UnityEngine.Rendering; namespace UnityEditor.Rendering.Settings { internal static class RenderPipelineGraphicsSettingsManager { internal const string serializationPathToContainer = "m_Settings"; internal const string serializationPathToCollection = serializationPathToContainer + ".m_SettingsList.m_List"; internal const string undoResetName = "Reset IRenderPipelineGraphicsSettings: "; public struct RenderPipelineGraphicsSettingsInfo { public Type type; public bool isSupported; } internal static void PopulateRenderPipelineGraphicsSettings(RenderPipelineGlobalSettings settings) { if (settings == null) return; if (!GraphicsSettingsInspectorUtility.TryExtractSupportedOnRenderPipelineAttribute(settings.GetType(), out var globalSettingsSupportedOn, out var message)) throw new InvalidOperationException(message); var globalSettingsRenderPipelineAssetType = globalSettingsSupportedOn.renderPipelineTypes[0]; bool assetModified = false; List<IRenderPipelineGraphicsSettings> createdSettingsObjects = new(); foreach (var info in FetchRenderPipelineGraphicsSettingInfos(globalSettingsRenderPipelineAssetType, true)) { UpdateRenderPipelineGlobalSettings(info, settings, out var modified, out var createdSetting); assetModified |= modified; if (createdSetting != null) createdSettingsObjects.Add(createdSetting); } foreach (var created in createdSettingsObjects) { created.Reset(); } if (assetModified) { EditorUtility.SetDirty(settings); AssetDatabase.SaveAssetIfDirty(settings); } } internal static IEnumerable<RenderPipelineGraphicsSettingsInfo> FetchRenderPipelineGraphicsSettingInfos(Type globalSettingsRenderPipelineAssetType, bool includeUnsupported = false) { foreach (var renderPipelineGraphicsSettingsType in TypeCache.GetTypesDerivedFrom(typeof(IRenderPipelineGraphicsSettings))) { if (!IsSettingsValid(renderPipelineGraphicsSettingsType)) continue; // The Setting has been completely deprecated or not supported on render pipeline anymore if (!IsSettingsSupported(renderPipelineGraphicsSettingsType, globalSettingsRenderPipelineAssetType, includeUnsupported, out var isSupported)) continue; yield return new RenderPipelineGraphicsSettingsInfo() { type = renderPipelineGraphicsSettingsType, isSupported = isSupported }; } } static void UpdateRenderPipelineGlobalSettings( RenderPipelineGraphicsSettingsInfo renderPipelineGraphicsSettingsType, RenderPipelineGlobalSettings asset, out bool assetModified, out IRenderPipelineGraphicsSettings createdSetting) { assetModified = false; createdSetting = null; var hasSettings = asset.TryGet(renderPipelineGraphicsSettingsType.type, out var renderPipelineGraphicsSettings); if (!renderPipelineGraphicsSettingsType.isSupported) { if (!hasSettings) return; asset.Remove(renderPipelineGraphicsSettings); assetModified = true; return; } if (!hasSettings && TryCreateInstance(renderPipelineGraphicsSettingsType.type, true, out renderPipelineGraphicsSettings)) { assetModified = true; createdSetting = renderPipelineGraphicsSettings; asset.Add(renderPipelineGraphicsSettings); } if (renderPipelineGraphicsSettings is IRenderPipelineResources resource) { var reloadingStatus = RenderPipelineResourcesEditorUtils.TryReloadContainedNullFields(resource); assetModified |= reloadingStatus == RenderPipelineResourcesEditorUtils.ResultStatus.ResourceReloaded; } } static bool TryCreateInstance<T>(Type type, bool nonPublic, out T instance) { try { instance = (T)Activator.CreateInstance(type, nonPublic); return true; } catch (Exception ex) { Debug.LogException(ex); } instance = default; return false; } static bool IsSettingsSupported(Type renderPipelineGraphicsSettingsType, Type globalSettingsRenderPipelineAssetType, bool includeUnsupported, out bool isSupported) { isSupported = !(renderPipelineGraphicsSettingsType.GetCustomAttribute<ObsoleteAttribute>()?.IsError ?? false); isSupported &= SupportedOnRenderPipelineAttribute.IsTypeSupportedOnRenderPipeline(renderPipelineGraphicsSettingsType, globalSettingsRenderPipelineAssetType); return includeUnsupported || isSupported; } static bool IsSettingsValid(Type renderPipelineGraphicsSettingsType) { if (renderPipelineGraphicsSettingsType.IsAbstract || renderPipelineGraphicsSettingsType.IsGenericType || renderPipelineGraphicsSettingsType.IsInterface) return false; if (renderPipelineGraphicsSettingsType.GetCustomAttribute<SerializableAttribute>() == null) { Debug.LogWarning($"{nameof(SerializableAttribute)} must be added to {renderPipelineGraphicsSettingsType}, the setting will be skipped"); return false; } if (renderPipelineGraphicsSettingsType.GetCustomAttribute<SupportedOnRenderPipelineAttribute>() == null) { Debug.LogWarning($"{nameof(SupportedOnRenderPipelineAttribute)} must be added to {renderPipelineGraphicsSettingsType}, the setting will be skipped"); return false; } return true; } internal static void ResetRenderPipelineGraphicsSettings(Type graphicsSettingsType, Type renderPipelineType) { if (graphicsSettingsType == null || renderPipelineType == null) return; var renderPipelineGlobalSettings = EditorGraphicsSettings.GetRenderPipelineGlobalSettingsAsset(renderPipelineType); if (renderPipelineGlobalSettings == null || !renderPipelineGlobalSettings.TryGet(graphicsSettingsType, out var srpGraphicSetting)) return; if (!TryCreateInstance(graphicsSettingsType, true, out srpGraphicSetting)) return; srpGraphicSetting.Reset(); var serializedGlobalSettings = new SerializedObject(renderPipelineGlobalSettings); var settingsIterator = serializedGlobalSettings.FindProperty(serializationPathToCollection); settingsIterator.NextVisible(true); //enter the collection while (settingsIterator.boxedValue?.GetType() != graphicsSettingsType) settingsIterator.NextVisible(false); if (srpGraphicSetting is IRenderPipelineResources resource) RenderPipelineResourcesEditorUtils.TryReloadContainedNullFields(resource); using (var notifier = new Notifier.Scope(settingsIterator)) { settingsIterator.boxedValue = srpGraphicSetting; if (serializedGlobalSettings.ApplyModifiedProperties()) Undo.SetCurrentGroupName($"{undoResetName}{graphicsSettingsType.Name}"); } } } }
UnityCsReference/Editor/Mono/Settings/RenderPipelines/RenderPipelineGraphicsSettingsManager.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Settings/RenderPipelines/RenderPipelineGraphicsSettingsManager.cs", "repo_id": "UnityCsReference", "token_count": 3335 }
337
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using UnityEngine; using UnityEngine.Bindings; using UnityEngine.Rendering; using UnityEngine.Scripting; [assembly: InternalsVisibleTo("Assembly-CSharp-Editor-testable")] namespace UnityEditor.ShaderKeywordFilter { // SettingsVariant represents a leaf node in the settings tree. // The keyword arrays there tell which keywords need to be selected and which removed. // This data is used in the native code to prune the enumeration data, thus reducing // the size of enumerated variant space. [RequiredByNativeCode (GenerateProxy = true)] [StructLayout(LayoutKind.Sequential)] internal struct SettingsVariant { internal SettingsVariant(List<FilterRule> rules) { var selected = new List<string>(); var selectedMessages = new List<string>(); var emptyKwSelectors = new List<int>(); var removed = new List<string>(); var removedMessages = new List<string>(); var emptyKwRemovers = new List<int>(); foreach (var rule in rules) { if (rule.action == FilterAction.Select) { selected.Add(rule.keywordName); if(rule.withEmptyKeyword) emptyKwSelectors.Add(selected.Count - 1); selectedMessages.Add(rule.resolutionMessage); } else if (rule.action == FilterAction.Remove) { removed.Add(rule.keywordName); if (rule.withEmptyKeyword) emptyKwRemovers.Add(removed.Count - 1); removedMessages.Add(rule.resolutionMessage); } } selectKeywords = selected.ToArray(); removeKeywords = removed.ToArray(); emptyKeywordSelectingKeywords = emptyKwSelectors.ToArray(); emptyKeywordRemovingKeywords = emptyKwRemovers.ToArray(); selectReasons = selectedMessages.ToArray(); removeReasons = removedMessages.ToArray(); } readonly internal string[] selectKeywords; // Keywords that have resolved to be selected in the build by a filter rule readonly internal string[] selectReasons; // Human readable message on why the keyword was selected readonly internal int[] emptyKeywordSelectingKeywords; // Indices of keywords that will also retain "empty keyword" case readonly internal string[] removeKeywords; // Keywords that have resolved to be removed from the build by a filter rule readonly internal string[] removeReasons; // Human readable message on why the keyword was removed readonly internal int[] emptyKeywordRemovingKeywords; // Indices of keywords that will also remove "empty keyword" case } // This struct is for passing the constraint state of the currently compiled shader pass from C++ to C#. // It is used for comparing against the filter attribute constraints and this way // we can select only the filter rules that are meeting the constraint requirements. [RequiredByNativeCode (GenerateProxy = true)] internal struct ConstraintState { internal string[] tags; internal GraphicsDeviceType[] graphicsAPIs; } // This is the main class for shader keyword filtering C++/C# interop [RequiredByNativeCode] internal static class ShaderKeywordFilterUtil { internal struct CachedFilterData { public Hash128 dependencyHash; public SettingsNode settingsNode; }; // In memory cache for filter data per renderpipeline asset. // This is to avoid redundant attribute search for each shader/pass/stage. internal static Dictionary<string, CachedFilterData> PerAssetFilterDataCache = new Dictionary<string, CachedFilterData>(); internal static SettingsNode GetFilterDataCached(string nodeName, UnityEngine.Object containerObject) { string assetPath = AssetDatabase.GetAssetPath(containerObject); Hash128 dependencyHash = AssetDatabase.GetAssetDependencyHash(assetPath); CachedFilterData cachedData; if (PerAssetFilterDataCache.TryGetValue(assetPath, out cachedData)) { // Cached data is valid only if dependency hash hasn't changed if (cachedData.dependencyHash == dependencyHash) return cachedData.settingsNode; } // No valid data found in the cache so we need to do the full processing // and then enter the result into the cache. var visited = new HashSet<object>(); cachedData.dependencyHash = dependencyHash; cachedData.settingsNode = SettingsNode.GatherFilterData(nodeName, containerObject, visited); PerAssetFilterDataCache[assetPath] = cachedData; return cachedData.settingsNode; } // For the current build target with given constraint state, gets the list of active filter rule sets. [RequiredByNativeCode] internal static SettingsVariant[] GetKeywordFilterVariants(string buildTargetGroupName, ConstraintState constraintState) { var rpAssets = new List<RenderPipelineAsset>(); QualitySettings.GetAllRenderPipelineAssetsForPlatform(buildTargetGroupName, ref rpAssets); // Gather the settings/attribute tree from the renderpipe assets SettingsNode root = new SettingsNode("root"); foreach(var rpAsset in rpAssets) { if (rpAsset == null) continue; var node = GetFilterDataCached(rpAsset.name, rpAsset); if (node != null) root.Children.Add(node); } // Extract the filter rules for each leaf node in the settings tree and return that in an array form. var variants = new List<SettingsVariant>(); root.GetVariantArray(constraintState, variants); // We need to return at least a blank settings variant, even if there were no rules if (variants.Count == 0) { variants.Add(new SettingsVariant(new List<FilterRule>())); } return variants.ToArray(); } } }
UnityCsReference/Editor/Mono/Shaders/ShaderKeywordFilterUtil.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Shaders/ShaderKeywordFilterUtil.cs", "repo_id": "UnityCsReference", "token_count": 2590 }
338
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Collections.Generic; using UnityEngine; using UnityEngine.UIElements; using UnityObject = UnityEngine.Object; namespace UnityEditor.EditorTools { public interface IDrawSelectedHandles { void OnDrawHandles(); } public abstract class EditorTool : ScriptableObject, IEditor { bool m_Active; [HideInInspector] [SerializeField] internal UnityObject[] m_Targets; [HideInInspector] [SerializeField] internal UnityObject m_Target; public IEnumerable<UnityObject> targets { get { // CustomEditor tools get m_Targets populated on instantiation. Persistent tools always reflect the // current selection, and therefore do not have m_Targets set. When a tool is deserialized, the m_Targets // array is initialized but not populated, hence the `> 0` check (valid because it is not possible to // create a custom editor tool instance with no targets) if (m_Targets != null && m_Targets.Length > 0) return m_Targets; return Selection.objects; } } public UnityObject target { get { return m_Target == null ? Selection.activeObject : m_Target; } } public virtual GUIContent toolbarIcon { get { return null; } } public virtual bool gridSnapEnabled { get { return false; } } internal void Activate() { if(m_Active // Prevent to reenable the tool if this is not the active one anymore // Can happen when entering playmode due to the delayCall in EditorToolManager.OnEnable || this != EditorToolManager.activeTool) return; OnActivated(); m_Active = true; } internal void Deactivate() { if(!m_Active) return; OnWillBeDeactivated(); m_Active = false; } public virtual void OnActivated() {} public virtual void OnWillBeDeactivated() {} public virtual void OnToolGUI(EditorWindow window) {} public virtual void PopulateMenu(DropdownMenu menu) {} public virtual bool IsAvailable() { return true; } void IEditor.SetTarget(UnityObject value) { m_Target = value; } void IEditor.SetTargets(UnityObject[] value) { m_Targets = value; } } }
UnityCsReference/Editor/Mono/Tools/EditorTool.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Tools/EditorTool.cs", "repo_id": "UnityCsReference", "token_count": 1256 }
339
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Linq; using Unity.Profiling; using UnityEditor.ShortcutManagement; using UnityEngine; using UnityEngine.Scripting; using UnityEditorInternal; using UnityEditor.EditorTools; namespace UnityEditor { public enum ViewTool { None = -1, Orbit = 0, Pan = 1, Zoom = 2, FPS = 3 } public enum PivotMode { Center = 0, Pivot = 1 } public enum PivotRotation { Local = 0, Global = 1 } public enum Tool { View = 0, Move = 1, Rotate = 2, Scale = 3, Rect = 4, Transform = 5, Custom = 6, None = -1 } public sealed partial class Tools : ScriptableObject { static Tools get { get { if (!s_Get) { s_Get = ScriptableObject.CreateInstance<Tools>(); s_Get.hideFlags = HideFlags.HideAndDontSave; } return s_Get; } } static Tools s_Get; #pragma warning disable 618 [System.Obsolete("Use EditorTools.activeToolDidChange or EditorTools.activeToolWillChange")] internal delegate void OnToolChangedFunc(Tool from, Tool to); [System.Obsolete("Use EditorTools.activeToolDidChange or EditorTools.activeToolWillChange")] internal static OnToolChangedFunc onToolChanged; #pragma warning restore 618 public static event Action pivotModeChanged; public static event Action pivotRotationChanged; public static event Action viewToolChanged; public static Tool current { get { return EditorToolUtility.GetEnumWithEditorTool(EditorToolManager.GetActiveTool()); } set { var tool = EditorToolUtility.GetEditorToolWithEnum(value); //In case the new tool is leading to an incorrect tool type, return and leave the current tool as it is. if(value != Tool.None && tool is NoneTool) return; EditorToolManager.activeTool = tool; ShortcutManager.RegisterTag(value); } } internal static void SyncToolEnum() { RepaintAllToolViews(); } public static ViewTool viewTool { get { return get.m_ViewTool; } set { if (viewTool == value) return; get.m_ViewTool = value; ShortcutManager.RegisterTag(get.m_ViewTool); viewToolChanged?.Invoke(); } } internal static ViewTool s_LockedViewTool = ViewTool.None; internal static int s_ButtonDown = -1; public static bool viewToolActive => SceneViewMotion.viewToolIsActive; static Vector3 s_HandlePosition; static bool s_HandlePositionComputed; internal static Vector3 cachedHandlePosition { get { if (!s_HandlePositionComputed) { s_HandlePosition = GetHandlePosition(); s_HandlePositionComputed = true; } return s_HandlePosition; } } internal static void InvalidateHandlePosition() { s_HandlePositionComputed = false; } public static Vector3 handlePosition { get { Transform t = Selection.activeTransform; if (!t) return new Vector3(Mathf.Infinity, Mathf.Infinity, Mathf.Infinity); if (s_LockHandlePositionActive) return s_LockHandlePosition; return cachedHandlePosition; } } private static ProfilerMarker s_GetHandlePositionMarker = new ProfilerMarker($"{nameof(Tools)}.{nameof(GetHandlePosition)}"); internal static Vector3 GetHandlePosition() { Transform t = Selection.activeTransform; if (!t) return new Vector3(Mathf.Infinity, Mathf.Infinity, Mathf.Infinity); Vector3 totalOffset = handleOffset + handleRotation * localHandleOffset; using (s_GetHandlePositionMarker.Auto()) { switch (get.m_PivotMode) { case PivotMode.Center: { if (current == Tool.Rect) return handleRotation * InternalEditorUtility .CalculateSelectionBoundsInSpace(Vector3.zero, handleRotation, rectBlueprintMode) .center + totalOffset; else return InternalEditorUtility.CalculateSelectionBounds(true, false).center + totalOffset; } case PivotMode.Pivot: { if (current == Tool.Rect && rectBlueprintMode && InternalEditorUtility.SupportsRectLayout(t)) return t.parent.TransformPoint(new Vector3(t.localPosition.x, t.localPosition.y, 0)) + totalOffset; else return t.position + totalOffset; } default: { return new Vector3(Mathf.Infinity, Mathf.Infinity, Mathf.Infinity); } } } } public static Rect handleRect { get { Bounds bounds = InternalEditorUtility.CalculateSelectionBoundsInSpace(handlePosition, handleRotation, rectBlueprintMode); int axis = GetRectAxisForViewDir(bounds, handleRotation, SceneView.currentDrawingSceneView.camera.transform.forward); return GetRectFromBoundsForAxis(bounds, axis); } } public static Quaternion handleRectRotation { get { Bounds bounds = InternalEditorUtility.CalculateSelectionBoundsInSpace(handlePosition, handleRotation, rectBlueprintMode); int axis = GetRectAxisForViewDir(bounds, handleRotation, SceneView.currentDrawingSceneView.camera.transform.forward); return GetRectRotationForAxis(handleRotation, axis); } } private static int GetRectAxisForViewDir(Bounds bounds, Quaternion rotation, Vector3 viewDir) { if (s_LockHandleRectAxisActive) { return s_LockHandleRectAxis; } if (viewDir == Vector3.zero) { return 2; } else { if (bounds.size == Vector3.zero) bounds.size = Vector3.one; int axis = -1; float bestScore = -1; for (int normalAxis = 0; normalAxis < 3; normalAxis++) { Vector3 edge1 = Vector3.zero; Vector3 edge2 = Vector3.zero; int axis1 = (normalAxis + 1) % 3; int axis2 = (normalAxis + 2) % 3; edge1[axis1] = bounds.size[axis1]; edge2[axis2] = bounds.size[axis2]; float score = Vector3.Cross(Vector3.ProjectOnPlane(rotation * edge1, viewDir), Vector3.ProjectOnPlane(rotation * edge2, viewDir)).magnitude; if (score > bestScore) { bestScore = score; axis = normalAxis; } } return axis; } } private static Rect GetRectFromBoundsForAxis(Bounds bounds, int axis) { switch (axis) { case 0: return new Rect(-bounds.max.z, bounds.min.y, bounds.size.z, bounds.size.y); case 1: return new Rect(bounds.min.x, -bounds.max.z, bounds.size.x, bounds.size.z); case 2: default: return new Rect(bounds.min.x, bounds.min.y, bounds.size.x, bounds.size.y); } } private static Quaternion GetRectRotationForAxis(Quaternion rotation, int axis) { switch (axis) { case 0: return rotation * Quaternion.Euler(0, 90, 0); case 1: return rotation * Quaternion.Euler(-90, 0, 0); case 2: default: return rotation; } } internal static void LockHandleRectRotation() { Bounds bounds = InternalEditorUtility.CalculateSelectionBoundsInSpace(handlePosition, handleRotation, rectBlueprintMode); s_LockHandleRectAxis = GetRectAxisForViewDir(bounds, handleRotation, SceneView.currentDrawingSceneView.camera.transform.forward); s_LockHandleRectAxisActive = true; } internal static void UnlockHandleRectRotation() { s_LockHandleRectAxisActive = false; } public static PivotMode pivotMode { get { return get.m_PivotMode; } set { if (get.m_PivotMode != value) { get.m_PivotMode = value; EditorPrefs.SetInt("PivotMode", (int)pivotMode); InvalidateHandlePosition(); pivotModeChanged?.Invoke(); } } } private PivotMode m_PivotMode; [RequiredByNativeCode] internal static int GetPivotMode() { return (int)pivotMode; } public static bool rectBlueprintMode { get { return get.m_RectBlueprintMode; } set { if (get.m_RectBlueprintMode != value) { get.m_RectBlueprintMode = value; EditorPrefs.SetBool("RectBlueprintMode", rectBlueprintMode); } } } private bool m_RectBlueprintMode; public static Quaternion handleRotation { get { switch (get.m_PivotRotation) { case PivotRotation.Global: return get.m_GlobalHandleRotation; case PivotRotation.Local: return handleLocalRotation; } return Quaternion.identity; } set { if (get.m_PivotRotation == PivotRotation.Global) get.m_GlobalHandleRotation = value; } } public static PivotRotation pivotRotation { get { return get.m_PivotRotation; } set { if (get.m_PivotRotation != value) { get.m_PivotRotation = value; EditorPrefs.SetInt("PivotRotation", (int)pivotRotation); pivotRotationChanged?.Invoke(); } } } private PivotRotation m_PivotRotation; internal static bool s_Hidden = false; public static bool hidden { get { return s_Hidden; } set { s_Hidden = value; } } internal static bool vertexDragging; static Event m_VertexDraggingShortcutEvent; internal static Event vertexDraggingShortcutEvent { get { if(m_VertexDraggingShortcutEvent == null) { var vertexSnappingBinding = ShortcutManager.instance.GetShortcutBinding(VertexSnapping.k_VertexSnappingShortcut); if(Enumerable.Count(vertexSnappingBinding.keyCombinationSequence) == 0) m_VertexDraggingShortcutEvent = new Event(); else m_VertexDraggingShortcutEvent = vertexSnappingBinding.keyCombinationSequence.First().ToKeyboardEvent(); } return m_VertexDraggingShortcutEvent; } set => m_VertexDraggingShortcutEvent = value; } static Vector3 s_LockHandlePosition; static bool s_LockHandlePositionActive = false; static int s_LockHandleRectAxis; static bool s_LockHandleRectAxisActive = false; struct LayerSettings { public int visibleLayersValue; public int lockedLayersValue; public LayerSettings(int visible, int locked) { visibleLayersValue = visible; lockedLayersValue = locked; } } LayerSettings m_LayerSettings = new LayerSettings(-1, -1); static StateCache<LayerSettings> s_LayersStateCache = new StateCache<LayerSettings>("Library/StateCache/LayerSettings/"); static Hash128 m_LayerSettingsKey = Hash128.Compute("LayerSettings"); public static int visibleLayers { get { return get.m_LayerSettings.visibleLayersValue; } set { if (get.m_LayerSettings.visibleLayersValue != value) { get.m_LayerSettings.visibleLayersValue = value; EditorGUIUtility.SetVisibleLayers(value); s_LayersStateCache.SetState(m_LayerSettingsKey, get.m_LayerSettings); } } } public static int lockedLayers { get { return get.m_LayerSettings.lockedLayersValue; } set { if (get.m_LayerSettings.lockedLayersValue != value) { get.m_LayerSettings.lockedLayersValue = value; EditorGUIUtility.SetLockedLayers(value); s_LayersStateCache.SetState(m_LayerSettingsKey, get.m_LayerSettings); } } } void OnEnable() { s_Get = this; pivotMode = (PivotMode)EditorPrefs.GetInt("PivotMode", 0); rectBlueprintMode = EditorPrefs.GetBool("RectBlueprintMode", false); pivotRotation = (PivotRotation)EditorPrefs.GetInt("PivotRotation", 0); var layerSettings = s_LayersStateCache.GetState(m_LayerSettingsKey, new LayerSettings(-1, 0)); visibleLayers = layerSettings.visibleLayersValue; lockedLayers = layerSettings.lockedLayersValue; Selection.selectionChanged += OnSelectionChange; Undo.undoRedoEvent += OnUndoRedo; ShortcutManager.instance.activeProfileChanged += args => vertexDraggingShortcutEvent = null; ShortcutManager.instance.shortcutBindingChanged += args => vertexDraggingShortcutEvent = null; EditorToolManager.activeToolChanged += (previous, active) => { #pragma warning disable 618 if (onToolChanged != null) onToolChanged( EditorToolUtility.GetEnumWithEditorTool(previous), EditorToolUtility.GetEnumWithEditorTool(active)); #pragma warning restore 618 }; } void OnDisable() { Selection.selectionChanged -= OnSelectionChange; Undo.undoRedoEvent -= OnUndoRedo; } internal static void OnSelectionChange() { ResetGlobalHandleRotation(); InvalidateHandlePosition(); localHandleOffset = Vector3.zero; } internal static void OnUndoRedo(in UndoRedoInfo info) { OnSelectionChange(); } internal static void ResetGlobalHandleRotation() { get.m_GlobalHandleRotation = Quaternion.identity; } internal Quaternion m_GlobalHandleRotation = Quaternion.identity; ViewTool m_ViewTool = ViewTool.Pan; static void SetToolMode(Tool toolMode) { current = toolMode; Toolbar.get?.Repaint(); ResetGlobalHandleRotation(); } [Shortcut("Tools/View", KeyCode.Q)] [FormerlyPrefKeyAs("Tools/View", "q")] static void SetToolModeView(ShortcutArguments args) { SetToolMode(Tool.View); } [Shortcut("Tools/Move", KeyCode.W)] [FormerlyPrefKeyAs("Tools/Move", "w")] static void SetToolModeMove(ShortcutArguments args) { SetToolMode(Tool.Move); } [Shortcut("Tools/Rotate", KeyCode.E)] [FormerlyPrefKeyAs("Tools/Rotate", "e")] static void SetToolModeRotate(ShortcutArguments args) { SetToolMode(Tool.Rotate); } [Shortcut("Tools/Scale", KeyCode.R)] [FormerlyPrefKeyAs("Tools/Scale", "r")] static void SetToolModeScale(ShortcutArguments args) { SetToolMode(Tool.Scale); } [Shortcut("Tools/Rect", KeyCode.T)] [FormerlyPrefKeyAs("Tools/Rect Handles", "t")] static void SetToolModeRect(ShortcutArguments args) { SetToolMode(Tool.Rect); } [Shortcut("Tools/Transform", KeyCode.Y)] [FormerlyPrefKeyAs("Tools/Transform Handles", "y")] static void SetToolModeTransform(ShortcutArguments args) { SetToolMode(Tool.Transform); } [Shortcut("Tools/Toggle Pivot Position", KeyCode.Z)] [FormerlyPrefKeyAs("Tools/Pivot Mode", "z")] static void TogglePivotMode(ShortcutArguments args) { pivotMode = pivotMode == PivotMode.Center ? PivotMode.Pivot : PivotMode.Center; ResetGlobalHandleRotation(); RepaintAllToolViews(); } [Shortcut("Tools/Toggle Pivot Orientation", KeyCode.X)] [FormerlyPrefKeyAs("Tools/Pivot Rotation", "x")] static void TogglePivotRotation(ShortcutArguments args) { pivotRotation = pivotRotation == PivotRotation.Global ? PivotRotation.Local : PivotRotation.Global; ResetGlobalHandleRotation(); RepaintAllToolViews(); } internal static void RepaintAllToolViews() { Toolbar.RepaintToolbar(); SceneView.RepaintAll(); InspectorWindow.RepaintAllInspectors(); } internal static void LockHandlePosition(Vector3 pos) { s_LockHandlePosition = pos; s_LockHandlePositionActive = true; } internal static Vector3 handleOffset; internal static Vector3 localHandleOffset; internal static void LockHandlePosition() { LockHandlePosition(handlePosition); } internal static void UnlockHandlePosition() { s_LockHandlePositionActive = false; } internal static Quaternion handleLocalRotation { get { Transform t = Selection.activeTransform; if (!t) return Quaternion.identity; if (rectBlueprintMode && InternalEditorUtility.SupportsRectLayout(t)) return t.parent.rotation; return t.rotation; } } } }
UnityCsReference/Editor/Mono/Tools/Tools.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Tools/Tools.cs", "repo_id": "UnityCsReference", "token_count": 9966 }
340
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Bindings; using UnityEngine.UIElements; namespace UnityEditor.UIElements { /// <summary> /// Makes a dropdown for switching between enum flag values that are marked with the Flags attribute. /// </summary> /// <remarks> /// An option for the value 0 with name "Nothing" and an option for the value ~0 (that is, all bits set) with the /// name "Everything" are always displayed at the top of the menu. The names for the values 0 and ~0 can be /// overriden by defining these values in the enum type. /// /// For more information, refer to [[wiki:UIE-uxml-element-EnumFlagsField|UXML element EnumFlagsField]]. /// </remarks> public class EnumFlagsField : BaseMaskField<Enum> { [UnityEngine.Internal.ExcludeFromDocs, Serializable] public new class UxmlSerializedData : BaseField<Enum>.UxmlSerializedData { #pragma warning disable 649 [UxmlTypeReference(typeof(Enum))] [SerializeField, UxmlAttribute("type")] string typeAsString; [SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags typeAsString_UxmlAttributeFlags; [EnumFlagsFieldValueDecorator] [SerializeField, UxmlAttribute("value")] string valueAsString; [SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags valueAsString_UxmlAttributeFlags; [SerializeField] bool includeObsoleteValues; [SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags includeObsoleteValues_UxmlAttributeFlags; #pragma warning restore 649 public override object CreateInstance() => new EnumFlagsField(); public override void Deserialize(object obj) { base.Deserialize(obj); var e = (EnumFlagsField)obj; if (ShouldWriteAttributeValue(includeObsoleteValues_UxmlAttributeFlags)) e.includeObsoleteValues = includeObsoleteValues; if (ShouldWriteAttributeValue(typeAsString_UxmlAttributeFlags)) e.typeAsString = typeAsString; if (ShouldWriteAttributeValue(valueAsString_UxmlAttributeFlags)) e.valueAsString = valueAsString; } } /// <summary> /// Instantiates a <see cref="EnumFlagsField"/> 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<EnumFlagsField, UxmlTraits> {} /// <summary> /// Defines <see cref="UxmlTraits"/> for the <see cref="EnumFlagsField"/>. /// </summary> [Obsolete("UxmlTraits is deprecated and will be removed. Use UxmlElementAttribute instead.", false)] public new class UxmlTraits : BaseMaskField<Enum>.UxmlTraits { #pragma warning disable 414 private UxmlTypeAttributeDescription<Enum> m_Type = EnumFieldHelpers.type; private UxmlStringAttributeDescription m_Value = EnumFieldHelpers.value; private UxmlBoolAttributeDescription m_IncludeObsoleteValues = EnumFieldHelpers.includeObsoleteValues; #pragma warning restore 414 public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) { base.Init(ve, bag, cc); if (EnumFieldHelpers.ExtractValue(bag, cc, out var resEnumType, out var resEnumValue, out var resIncludeObsoleteValues)) { EnumFlagsField enumField = (EnumFlagsField)ve; enumField.Init(resEnumValue, resIncludeObsoleteValues); } // If we didn't have a valid value, try to set the type. else if (null != resEnumType) { EnumFlagsField enumField = (EnumFlagsField)ve; enumField.m_EnumType = resEnumType; if (enumField.m_EnumType != null) enumField.PopulateDataFromType(enumField.m_EnumType); enumField.value = null; } else { var enumField = (EnumFlagsField)ve; enumField.m_EnumType = null; enumField.value = null; } } } /// <summary> /// USS class name for elements of this type. /// </summary> public new static readonly string ussClassName = "unity-enum-flags-field"; /// <summary> /// USS class name for labels of this type. /// </summary> public new static readonly string labelUssClassName = ussClassName + "__label"; /// <summary> /// USS class name for input elements of this type. /// </summary> public new static readonly string inputUssClassName = ussClassName + "__input"; private Type m_EnumType; private bool m_IncludeObsoleteValues; private EnumData m_EnumData; // These properties exist so that the UIBuilder can read them. internal Type type { [VisibleToOtherModules("UnityEditor.UIBuilderModule")] get => m_EnumType; } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal bool includeObsoleteValues { get => m_IncludeObsoleteValues; set => m_IncludeObsoleteValues = value; } internal string typeAsString { get => UxmlUtility.TypeToString(m_EnumType); [VisibleToOtherModules("UnityEditor.UIBuilderModule")] set { m_EnumType = UxmlUtility.ParseType(value); if (m_EnumType == null) { this.value = null; textElement.text = string.Empty; } } } internal string valueAsString { get => value?.ToString(); [VisibleToOtherModules("UnityEditor.UIBuilderModule")] set { if (type != null) { if (!string.IsNullOrEmpty(value)) { if (Enum.TryParse(type, value, false, out var result) && result is Enum enumValue) { Init(enumValue, includeObsoleteValues); return; } else { // If we didn't have a valid value, try to set the type. PopulateDataFromType(type); this.value = null; } } else { var enumValue = (Enum)Enum.ToObject(type, 0); Init(enumValue, includeObsoleteValues); } } else { this.value = null; } } } /// <summary> /// Constructs an EnumFlagsField with a default value, and initializes its underlying type. /// </summary> /// <param name="defaultValue">Initial value. This also detects the Enum type.</param> public EnumFlagsField(Enum defaultValue) : this(null, defaultValue, false) {} /// <summary> /// Constructs an EnumFlagsField with a default value, and initializes its underlying type. /// </summary> /// <param name="defaultValue">Initial value. This also detects the Enum type.</param> public EnumFlagsField(Enum defaultValue, bool includeObsoleteValues) : this(null, defaultValue, includeObsoleteValues) {} /// <summary> /// Constructs an EnumFlagsField with a default value, and initializes its underlying type. /// </summary> /// <param name="defaultValue">Initial value. This also detects the Enum type.</param> public EnumFlagsField(string label, Enum defaultValue) : this(label, defaultValue, false) { } /// <summary> /// Constructs an EnumFlagsField with a default value, and initializes its underlying type. /// </summary> public EnumFlagsField() : this(null, null, false) {} /// <summary> /// Constructs an EnumFlagsField with a default value, and initializes its underlying type. /// </summary> /// <param name="defaultValue">Initial value. This also detects the Enum type.</param> public EnumFlagsField(string label, Enum defaultValue, bool includeObsoleteValues) : this(label) { if (defaultValue != null) { Init(defaultValue, includeObsoleteValues); } } /// <summary> /// Initializes the EnumFlagsField with a default value, and initializes its underlying type. /// </summary> /// <param name="defaultValue">The typed enum value.</param> /// <param name="includeObsoleteValues">Set to true to display obsolete values as choices.</param> public void Init(Enum defaultValue, bool includeObsoleteValues = false) { if (defaultValue == null) { throw new ArgumentNullException(nameof(defaultValue)); } m_IncludeObsoleteValues = includeObsoleteValues; PopulateDataFromType(defaultValue.GetType()); if (!m_EnumData.flags) Debug.LogWarning("EnumMaskField is not bound to enum type with the [Flags] attribute"); choicesMasks = new List<int>(m_EnumData.flagValues); choices = new List<string>(m_EnumData.displayNames); SetValueWithoutNotify(defaultValue); } /// <summary> /// Constructs an EnumFlagsField with a default value, and initializes its underlying type. /// </summary> public EnumFlagsField(string label) : base(label) { AddToClassList(ussClassName); labelElement.AddToClassList(labelUssClassName); visualInput.AddToClassList(inputUssClassName); } internal override Enum MaskToValue(int newMask) { if (m_EnumType == null) return null; return EnumDataUtility.IntToEnumFlags(m_EnumType, newMask); } internal override int ValueToMask(Enum value) { if (m_EnumType == null) return 0; return EnumDataUtility.EnumFlagsToInt(m_EnumData, value); } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal void PopulateDataFromType(Type enumType) { m_EnumType = enumType; m_EnumData = EnumDataUtility.GetCachedEnumData(m_EnumType, !includeObsoleteValues); } internal override string GetNothingName() { if (m_EnumData.flagValues is not { Length: > 0 }) return base.GetNothingName(); for (var i = 0; i < m_EnumData.flagValues.Length; i++) { if (m_EnumData.flagValues[i] == 0) { return m_EnumData.displayNames[i]; } } return base.GetNothingName(); } internal override string GetEverythingName() { if (m_EnumData.flagValues is not { Length: > 0 }) return base.GetEverythingName(); for (var i = 0; i < m_EnumData.flagValues.Length; i++) { if (m_EnumData.flagValues[i] == ~0) { return m_EnumData.displayNames[i]; } } return base.GetEverythingName(); } } }
UnityCsReference/Editor/Mono/UIElements/Controls/EnumFlagsField.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/UIElements/Controls/EnumFlagsField.cs", "repo_id": "UnityCsReference", "token_count": 5732 }
341
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using Unity.Properties; using UnityEngine.UIElements; namespace UnityEditor.UIElements { /// <summary> /// A toolbar spacer of static size. For more information, refer to [[wiki:UIE-uxml-element-ToolbarSpacer|UXML element ToolbarSpacer]]. /// </summary> public class ToolbarSpacer : VisualElement { internal static readonly BindingId flexProperty = nameof(flex); [UnityEngine.Internal.ExcludeFromDocs, Serializable] public new class UxmlSerializedData : VisualElement.UxmlSerializedData { public override object CreateInstance() => new ToolbarSpacer(); } /// <summary> /// Instantiates a <see cref="ToolbarSpacer"/> 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<ToolbarSpacer> {} /// <summary> /// USS class name of elements of this type. /// </summary> public static readonly string ussClassName = "unity-toolbar-spacer"; /// <summary> /// USS class name of elements of this type, when they are of fixed size. /// </summary> [Obsolete("The `fixedSpacerVariantUssClassName` style has been deprecated as is it now the default style.")] public static readonly string fixedSpacerVariantUssClassName = ussClassName + "--fixed"; /// <summary> /// USS class name of elements of this type, when they are of flexible size. /// </summary> public static readonly string flexibleSpacerVariantUssClassName = ussClassName + "--flexible"; /// <summary> /// Constructor. /// </summary> public ToolbarSpacer() { Toolbar.SetToolbarStyleSheet(this); AddToClassList(ussClassName); } /// <summary> /// Return true if the spacer stretches or shrinks to occupy available space. /// </summary> [CreateProperty] public bool flex { get { return ClassListContains(flexibleSpacerVariantUssClassName); } set { if (flex != value) { EnableInClassList(flexibleSpacerVariantUssClassName, value); NotifyPropertyChanged(flexProperty); } } } } }
UnityCsReference/Editor/Mono/UIElements/Controls/Toolbar/ToolbarSpacer.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/UIElements/Controls/Toolbar/ToolbarSpacer.cs", "repo_id": "UnityCsReference", "token_count": 1052 }
342
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEditor.UIElements.StyleSheets { class StyleSheetImportGlossary { public readonly string internalError = L10n.Tr("Internal import error: {0}"); public readonly string internalErrorWithStackTrace = L10n.Tr("Internal import error: {0}\n{1}"); // Words public readonly string error = L10n.Tr("error"); public readonly string warning = L10n.Tr("warning"); public readonly string line = L10n.Tr("line"); // Errors public readonly string unsupportedUnit = L10n.Tr("Unsupported unit: '{0}'"); public readonly string ussParsingError = L10n.Tr("USS parsing error: {0}"); public readonly string unsupportedTerm = L10n.Tr("Unsupported USS term: {0}"); public readonly string missingFunctionArgument = L10n.Tr("Missing function argument: '{0}'"); public readonly string missingVariableName = L10n.Tr("Missing variable name"); public readonly string emptyVariableName = L10n.Tr("Empty variable name"); public readonly string tooManyFunctionArguments = L10n.Tr("Too many function arguments"); public readonly string emptyFunctionArgument = L10n.Tr("Empty function argument"); public readonly string unexpectedTokenInFunction = L10n.Tr("Expected ',', got '{0}'"); public readonly string missingVariablePrefix = L10n.Tr("Variable '{0}' is missing '--' prefix"); public readonly string invalidHighResAssetType = L10n.Tr("Unsupported type {0} for asset at path '{1}' ; only Texture2D is supported for variants with @2x suffix\nSuggestion: verify the import settings of this asset."); public readonly string invalidSelectorListDelimiter = L10n.Tr("Invalid selector list delimiter: '{0}'"); public readonly string invalidComplexSelectorDelimiter = L10n.Tr("Invalid complex selector delimiter: '{0}'"); public readonly string unsupportedSelectorFormat = L10n.Tr("Unsupported selector format: '{0}'"); // Warnings public readonly string unknownFunction = L10n.Tr("Unknown function '{0}' in declaration '{1}: {0}'"); public readonly string circularImport = L10n.Tr("Circular @import dependencies detected. All @import directives will be ignored for this StyleSheet."); public readonly string invalidUriLocation = L10n.Tr("Invalid URI location: '{0}'"); public readonly string invalidUriScheme = L10n.Tr("Invalid URI scheme: '{0}'"); public readonly string invalidAssetPath = L10n.Tr("Invalid asset path: '{0}'"); public readonly string invalidAssetType = L10n.Tr("Unsupported type {0} for asset at path '{1}' ; only the following types are supported: {2}\nSuggestion: verify the import settings of this asset."); } }
UnityCsReference/Editor/Mono/UIElements/StyleSheets/StyleSheetImportGlossary.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/UIElements/StyleSheets/StyleSheetImportGlossary.cs", "repo_id": "UnityCsReference", "token_count": 971 }
343
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEditor.Connect; namespace UnityEditor { public class CloudProjectSettings { /// <summary> /// The user ID is derived from the user name without the domain (removing all characters starting with '@'), /// formatted in lowercase with no symbols. /// </summary> public static string userId { get { return UnityConnect.instance.GetUserId(); } } /// <summary> /// The user name is the email used for the user's Unity account. /// </summary> public static string userName { get { return UnityConnect.instance.GetUserName(); } } public static string accessToken { get { return UnityConnect.instance.GetAccessToken(); } } public static void RefreshAccessToken(Action<bool> refresh) { UnityConnect.instance.RefreshAccessToken(refresh); } /// <summary> /// This method shows the Unity login popup. /// </summary> public static void ShowLogin() { UnityConnect.instance.ShowLogin(); } /// <summary> /// The Project ID, or GUID. /// </summary> public static string projectId { get { return UnityConnect.instance.GetProjectGUID(); } } /// <summary> /// The name of the project. /// </summary> public static string projectName { get { return UnityConnect.instance.GetProjectName(); } } /// <summary> /// The Organization ID, formatted in lowercase with no symbols. /// </summary> public static string organizationId { get { return UnityConnect.instance.GetOrganizationId(); } } /// <summary> /// The Organization name used on the dashboard. /// </summary> public static string organizationName { get { return UnityConnect.instance.GetOrganizationName(); } } /// <summary> /// The key of the organization used on the dashboard /// </summary> public static string organizationKey { get { return UnityConnect.instance.GetOrganizationForeignKey(); } } /// <summary> /// The current COPPA compliance state. /// </summary> public static CoppaCompliance coppaCompliance { get { return UnityConnect.instance.projectInfo.COPPA; } } /// <summary> /// Returns true if the project has been bound. /// </summary> public static bool projectBound { get { return UnityConnect.instance.projectInfo.projectBound; } } } }
UnityCsReference/Editor/Mono/UnityConnect/CloudProjectSettings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/UnityConnect/CloudProjectSettings.cs", "repo_id": "UnityCsReference", "token_count": 1626 }
344
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Collections; using System.Collections.Generic; using UnityEngine; namespace UnityEditor { public class MathUtils { internal static float ClampToFloat(double value) { return Mathf.ClampToFloat(value); } internal static int ClampToInt(long value) { return Mathf.ClampToInt(value); } internal static float RoundToMultipleOf(float value, float roundingValue) { return Mathf.RoundToMultipleOf(value, roundingValue); } internal static float GetClosestPowerOfTen(float positiveNumber) { return Mathf.GetClosestPowerOfTen(positiveNumber); } internal static int GetNumberOfDecimalsForMinimumDifference(float minDifference) { return Mathf.GetNumberOfDecimalsForMinimumDifference(minDifference); } internal static int GetNumberOfDecimalsForMinimumDifference(double minDifference) { return Mathf.GetNumberOfDecimalsForMinimumDifference(minDifference); } internal static float RoundBasedOnMinimumDifference(float valueToRound, float minDifference) { return Mathf.RoundBasedOnMinimumDifference(valueToRound, minDifference); } internal static double RoundBasedOnMinimumDifference(double valueToRound, double minDifference) { return Mathf.RoundBasedOnMinimumDifference(valueToRound, minDifference); } internal static float DiscardLeastSignificantDecimal(float v) { return Mathf.DiscardLeastSignificantDecimal(v); } internal static double DiscardLeastSignificantDecimal(double v) { return Mathf.DiscardLeastSignificantDecimal(v); } public static float GetQuatLength(Quaternion q) { return Mathf.Sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w); } public static Quaternion GetQuatConjugate(Quaternion q) { return new Quaternion(-q.x, -q.y, -q.z, q.w); } public static Matrix4x4 OrthogonalizeMatrix(Matrix4x4 m) { Matrix4x4 n = Matrix4x4.identity; Vector3 i = m.GetColumn(0); Vector3 j = m.GetColumn(1); Vector3 k = m.GetColumn(2); k = k.normalized; i = Vector3.Cross(j, k).normalized; j = Vector3.Cross(k, i).normalized; n.SetColumn(0, i); n.SetColumn(1, j); n.SetColumn(2, k); return n; } public static void QuaternionNormalize(ref Quaternion q) { float invMag = 1.0f / Mathf.Sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w); q.x *= invMag; q.y *= invMag; q.z *= invMag; q.w *= invMag; } public static Quaternion QuaternionFromMatrix(Matrix4x4 m) { // Adapted from: http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm Quaternion q = new Quaternion(); q.w = Mathf.Sqrt(Mathf.Max(0, 1 + m[0, 0] + m[1, 1] + m[2, 2])) / 2; q.x = Mathf.Sqrt(Mathf.Max(0, 1 + m[0, 0] - m[1, 1] - m[2, 2])) / 2; q.y = Mathf.Sqrt(Mathf.Max(0, 1 - m[0, 0] + m[1, 1] - m[2, 2])) / 2; q.z = Mathf.Sqrt(Mathf.Max(0, 1 - m[0, 0] - m[1, 1] + m[2, 2])) / 2; q.x *= Mathf.Sign(q.x * (m[2, 1] - m[1, 2])); q.y *= Mathf.Sign(q.y * (m[0, 2] - m[2, 0])); q.z *= Mathf.Sign(q.z * (m[1, 0] - m[0, 1])); // normalize QuaternionNormalize(ref q); return q; } /// <summary> /// Logarithm of a unit quaternion. The result is not necessary a unit quaternion. /// </summary> public static Quaternion GetQuatLog(Quaternion q) { Quaternion res = q; res.w = 0; if (Mathf.Abs(q.w) < 1.0f) { float theta = Mathf.Acos(q.w); float sin_theta = Mathf.Sin(theta); if (Mathf.Abs(sin_theta) > 0.0001) { float coef = theta / sin_theta; res.x = q.x * coef; res.y = q.y * coef; res.z = q.z * coef; } } return res; } public static Quaternion GetQuatExp(Quaternion q) { Quaternion res = q; float fAngle = Mathf.Sqrt(q.x * q.x + q.y * q.y + q.z * q.z); float fSin = Mathf.Sin(fAngle); res.w = Mathf.Cos(fAngle); if (Mathf.Abs(fSin) > 0.0001) { float coef = fSin / fAngle; res.x = coef * q.x; res.y = coef * q.y; res.z = coef * q.z; } return res; } /// <summary> /// SQUAD Spherical Quadrangle interpolation [Shoe87] /// </summary> public static Quaternion GetQuatSquad(float t, Quaternion q0, Quaternion q1, Quaternion a0, Quaternion a1) { float slerpT = 2.0f * t * (1.0f - t); Quaternion slerpP = Slerp(q0, q1, t); Quaternion slerpQ = Slerp(a0, a1, t); Quaternion slerp = Slerp(slerpP, slerpQ, slerpT); // normalize quaternion float l = Mathf.Sqrt(slerp.x * slerp.x + slerp.y * slerp.y + slerp.z * slerp.z + slerp.w * slerp.w); slerp.x /= l; slerp.y /= l; slerp.z /= l; slerp.w /= l; return slerp; } public static Quaternion GetSquadIntermediate(Quaternion q0, Quaternion q1, Quaternion q2) { Quaternion q1Inv = GetQuatConjugate(q1); Quaternion p0 = GetQuatLog(q1Inv * q0); Quaternion p2 = GetQuatLog(q1Inv * q2); Quaternion sum = new Quaternion(-0.25f * (p0.x + p2.x), -0.25f * (p0.y + p2.y), -0.25f * (p0.z + p2.z), -0.25f * (p0.w + p2.w)); return q1 * GetQuatExp(sum); } /// <summary> /// Smooths the input parameter t. /// If less than k1 ir greater than k2, it uses a sin. /// Between k1 and k2 it uses linear interp. /// </summary> public static float Ease(float t, float k1, float k2) { float f; float s; f = k1 * 2 / Mathf.PI + k2 - k1 + (1.0f - k2) * 2 / Mathf.PI; if (t < k1) { s = k1 * (2 / Mathf.PI) * (Mathf.Sin((t / k1) * Mathf.PI / 2 - Mathf.PI / 2) + 1); } else if (t < k2) { s = (2 * k1 / Mathf.PI + t - k1); } else { s = 2 * k1 / Mathf.PI + k2 - k1 + ((1 - k2) * (2 / Mathf.PI)) * Mathf.Sin(((t - k2) / (1.0f - k2)) * Mathf.PI / 2); } return (s / f); } /// <summary> /// We need this because Quaternion.Slerp always uses the shortest arc. /// </summary> public static Quaternion Slerp(Quaternion p, Quaternion q, float t) { Quaternion ret; float fCos = Quaternion.Dot(p, q); if ((1.0f + fCos) > 0.00001) { float fCoeff0, fCoeff1; if ((1.0f - fCos) > 0.00001) { float omega = Mathf.Acos(fCos); float invSin = 1.0f / Mathf.Sin(omega); fCoeff0 = Mathf.Sin((1.0f - t) * omega) * invSin; fCoeff1 = Mathf.Sin(t * omega) * invSin; } else { fCoeff0 = 1.0f - t; fCoeff1 = t; } ret.x = fCoeff0 * p.x + fCoeff1 * q.x; ret.y = fCoeff0 * p.y + fCoeff1 * q.y; ret.z = fCoeff0 * p.z + fCoeff1 * q.z; ret.w = fCoeff0 * p.w + fCoeff1 * q.w; } else { float fCoeff0 = Mathf.Sin((1.0f - t) * Mathf.PI * 0.5f); float fCoeff1 = Mathf.Sin(t * Mathf.PI * 0.5f); ret.x = fCoeff0 * p.x - fCoeff1 * p.y; ret.y = fCoeff0 * p.y + fCoeff1 * p.x; ret.z = fCoeff0 * p.z - fCoeff1 * p.w; ret.w = p.z; } return ret; } // intersect_RayTriangle(): intersect a ray with a 3D triangle // Input: a ray R, and 3 vector3 forming a triangle // Output: *I = intersection point (when it exists) // Return: null = no intersection // RaycastHit = intersection // -1 = triangle is degenerate (a segment or point) // 0 = disjoint (no intersect) // 1 = intersect in unique point I1 // 2 = are in the same plane public static object IntersectRayTriangle(Ray ray, Vector3 v0, Vector3 v1, Vector3 v2, bool bidirectional) { Vector3 ab = v1 - v0; Vector3 ac = v2 - v0; // Compute triangle normal. Can be precalculated or cached if // intersecting multiple segments against the same triangle Vector3 n = Vector3.Cross(ab, ac); // Compute denominator d. If d <= 0, segment is parallel to or points // away from triangle, so exit early float d = Vector3.Dot(-ray.direction, n); if (d <= 0.0f) return null; // Compute intersection t value of pq with plane of triangle. A ray // intersects iff 0 <= t. Segment intersects iff 0 <= t <= 1. Delay // dividing by d until intersection has been found to pierce triangle Vector3 ap = ray.origin - v0; float t = Vector3.Dot(ap, n); if ((t < 0.0f) && (!bidirectional)) return null; //if (t > d) return null; // For segment; exclude this code line for a ray test // Compute barycentric coordinate components and test if within bounds Vector3 e = Vector3.Cross(-ray.direction, ap); float v = Vector3.Dot(ac, e); if (v < 0.0f || v > d) return null; float w = -Vector3.Dot(ab, e); if (w < 0.0f || v + w > d) return null; // Segment/ray intersects triangle. Perform delayed division and // compute the last barycentric coordinate component float ood = 1.0f / d; t *= ood; v *= ood; w *= ood; float u = 1.0f - v - w; RaycastHit hit = new RaycastHit(); hit.point = ray.origin + t * ray.direction; hit.distance = t; hit.barycentricCoordinate = new Vector3(u, v, w); hit.normal = Vector3.Normalize(n); return hit; } // Returns closest point on segment // squaredDist = squared distance between the two closest points // s = offset along segment public static Vector3 ClosestPtSegmentRay(Vector3 p1, Vector3 q1, Ray ray, out float squaredDist, out float s, out Vector3 closestRay) { Vector3 p2 = ray.origin; Vector3 q2 = ray.GetPoint(10000.0f); Vector3 d1 = q1 - p1; // Direction vector of segment S1 Vector3 d2 = q2 - p2; // Direction vector of segment S2 Vector3 r = p1 - p2; float a = Vector3.Dot(d1, d1); // Squared length of segment S1, always nonnegative float e = Vector3.Dot(d2, d2); // Squared length of segment S2, always nonnegative float f = Vector3.Dot(d2, r); float t = 0.0f; // Check if either or both segments degenerate into points if (a <= Mathf.Epsilon && e <= Mathf.Epsilon) { // Both segments degenerate into points squaredDist = Vector3.Dot(p1 - p2, p1 - p2); s = 0.0f; closestRay = p2; return p1; } if (a <= Mathf.Epsilon) { // First segment degenerates into a point s = 0.0f; t = f / e; // s = 0 => t = (b*s + f) / e = f / e t = Mathf.Clamp(t, 0.0f, 1.0f); } else { float c = Vector3.Dot(d1, r); if (e <= Mathf.Epsilon) { // Second segment degenerates into a point t = 0.0f; s = Mathf.Clamp(-c / a, 0.0f, 1.0f); // t = 0 => s = (b*t - c) / a = -c / a } else { // The general nondegenerate case starts here float b = Vector3.Dot(d1, d2); float denom = a * e - b * b; // Always nonnegative // If segments not parallel, compute closest point on L1 to L2, and // clamp to segment S1. Else pick arbitrary s (here 0) if (denom != 0.0f) { s = Mathf.Clamp((b * f - c * e) / denom, 0.0f, 1.0f); } else s = 0.0f; // Compute point on L2 closest to S1(s) using // t = Dot((P1+D1*s)-P2,D2) / Dot(D2,D2) = (b*s + f) / e t = (b * s + f) / e; // If t in [0,1] done. Else clamp t, recompute s for the new value // of t using s = Dot((P2+D2*t)-P1,D1) / Dot(D1,D1)= (t*b - c) / a // and clamp s to [0, 1] if (t < 0.0f) { t = 0.0f; s = Mathf.Clamp(-c / a, 0.0f, 1.0f); } else if (t > 1.0f) { t = 1.0f; s = Mathf.Clamp((b - c) / a, 0.0f, 1.0f); } } } Vector3 c1 = p1 + d1 * s; Vector3 c2 = p2 + d2 * t; squaredDist = Vector3.Dot(c1 - c2, c1 - c2); closestRay = c2; return c1; } public static bool IntersectRaySphere(Ray ray, Vector3 sphereOrigin, float sphereRadius, ref float t, ref Vector3 q) { Vector3 m = ray.origin - sphereOrigin; float b = Vector3.Dot(m, ray.direction); float c = Vector3.Dot(m, m) - (sphereRadius * sphereRadius); // Exit if r�s origin outside s (c > 0)and r pointing away from s (b > 0) if ((c > 0.0f) && (b > 0.0f)) return false; float discr = (b * b) - c; // A negative discriminant corresponds to ray missing sphere if (discr < 0.0f) return false; // Ray now found to intersect sphere, compute smallest t value of intersection t = -b - Mathf.Sqrt(discr); // If t is negative, ray started inside sphere so clamp t to zero if (t < 0.0f) t = 0.0f; q = ray.origin + t * ray.direction; return true; } // Closest point public static bool ClosestPtRaySphere(Ray ray, Vector3 sphereOrigin, float sphereRadius, ref float t, ref Vector3 q) { Vector3 m = ray.origin - sphereOrigin; float b = Vector3.Dot(m, ray.direction); float c = Vector3.Dot(m, m) - (sphereRadius * sphereRadius); // Exit if r�s origin outside s (c > 0)and r pointing away from s (b > 0) if ((c > 0.0f) && (b > 0.0f)) { // ray origin is closest t = 0.0f; q = ray.origin; return true; } float discr = (b * b) - c; // A negative discriminant corresponds to ray missing sphere if (discr < 0.0f) { discr = 0.0f; } // Ray now found to intersect sphere, compute smallest t value of intersection t = -b - Mathf.Sqrt(discr); // If t is negative, ray started inside sphere so clamp t to zero if (t < 0.0f) t = 0.0f; q = ray.origin + t * ray.direction; return true; } } }
UnityCsReference/Editor/Mono/Utils/MathUtils.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Utils/MathUtils.cs", "repo_id": "UnityCsReference", "token_count": 9161 }
345
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Text; using UnityEditor.Utils; using UnityEngine; namespace UnityEditor { class StateCache<T> { string m_CacheFolder; Dictionary<Hash128, T> m_Cache = new Dictionary<Hash128, T>(); public string cacheFolderPath { get { return m_CacheFolder; } } public StateCache(string cacheFolder) { if (string.IsNullOrEmpty(cacheFolder)) throw new ArgumentException("cacheFolder cannot be null or empty string", cacheFolder); if (cacheFolder.IndexOfAny(System.IO.Path.GetInvalidPathChars()) >= 0) { throw new ArgumentException("Cache folder path has invalid path characters: '" + cacheFolder + "'"); } cacheFolder = cacheFolder.ConvertSeparatorsToUnity(); if (!cacheFolder.EndsWith("/")) { Debug.LogError("The cache folder path should end with a forward slash: '/'. Path: " + cacheFolder + ". Fixed up."); cacheFolder += "/"; } if (cacheFolder.StartsWith("/")) { Debug.LogError("The cache folder path should not start with a forward slash: '/'. Path: " + cacheFolder + ". Fixed up."); // since on OSX a leading '/' means the root directory cacheFolder = cacheFolder.TrimStart(new[] { '/' }); } m_CacheFolder = cacheFolder; } public void SetState(Hash128 key, T obj) { ThrowIfInvalid(key); if (obj == null) throw new ArgumentNullException("obj"); string json = JsonUtility.ToJson(obj); var filePath = GetFilePathForKey(key); try { string directory = System.IO.Path.GetDirectoryName(filePath); System.IO.Directory.CreateDirectory(directory); System.IO.File.WriteAllText(filePath, json, Encoding.UTF8); // Persist state } catch (Exception e) { Debug.LogError(string.Format("Error saving file {0}. Error: {1}", filePath, e)); } m_Cache[key] = obj; } public T GetState(Hash128 key, T defaultValue = default(T)) { ThrowIfInvalid(key); T obj; if (m_Cache.TryGetValue(key, out obj)) return obj; string filePath = GetFilePathForKey(key); if (System.IO.File.Exists(filePath)) { string jsonString = null; try { jsonString = System.IO.File.ReadAllText(filePath, Encoding.UTF8); } catch (Exception e) { Debug.LogError(string.Format("Error loading file {0}. Error: {1}", filePath, e)); return defaultValue; } try { obj = JsonUtility.FromJson<T>(jsonString); } catch (ArgumentException exception) { Debug.LogError(string.Format("Invalid file content for {0}. Removing file. Error: {1}", filePath, exception)); RemoveState(key); return defaultValue; } m_Cache[key] = obj; return obj; } return defaultValue; } public void RemoveState(Hash128 key) { ThrowIfInvalid(key); m_Cache.Remove(key); string filePath = GetFilePathForKey(key); if (System.IO.File.Exists(filePath)) System.IO.File.Delete(filePath); } void ThrowIfInvalid(Hash128 key) { if (!key.isValid) throw new ArgumentException("Hash128 key is invalid: " + key.ToString()); } public string GetFilePathForKey(Hash128 key) { // Hashed folder structure to ensure we scale with large amounts of state files. // See: https://medium.com/eonian-technologies/file-name-hashing-creating-a-hashed-directory-structure-eabb03aa4091 string hexKey = key.ToString(); string hexFolder = hexKey.Substring(0, 2) + "/"; return m_CacheFolder + hexFolder + hexKey + ".json"; } } }
UnityCsReference/Editor/Mono/Utils/StateCache.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Utils/StateCache.cs", "repo_id": "UnityCsReference", "token_count": 2235 }
346
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Linq; using UnityEditorInternal; using UnityEngine; using UnityEngine.Internal; namespace UnityEditor.VersionControl { [System.Flags] public enum CheckoutMode { Asset = 1, Meta = 2, Both = 3, Exact = 4 } [System.Flags] public enum ResolveMethod { UseMine = 1, UseTheirs = 2, UseMerged } [System.Flags] [System.Obsolete("MergeMethod is no longer used.")] public enum MergeMethod { MergeNone = 0, MergeAll = 1, [System.Obsolete("This member is no longer supported (UnityUpgradable) -> MergeNone", true)] MergeNonConflicting = 2 } [System.Flags] public enum OnlineState { Updating = 0, Online = 1, Offline = 2 } [System.Flags] public enum RevertMode { Normal = 0, Unchanged = 1, KeepModifications = 2 } [System.Flags] public enum FileMode { None = 0, Binary = 1, Text = 2 } public partial class Provider { //*Undocumented static internal Asset CacheStatus(string assetPath) { return Internal_CacheStatus(assetPath); } static public Task Status(AssetList assets) { return Internal_Status(assets.ToArray(), true); } static public Task Status(Asset asset) { return Internal_Status(new Asset[] { asset }, true); } static public Task Status(AssetList assets, bool recursively) { return Internal_Status(assets.ToArray(), recursively); } static public Task Status(Asset asset, bool recursively) { return Internal_Status(new Asset[] { asset }, recursively); } static public Task Status(string[] assets) { return Internal_StatusStrings(assets, true); } static public Task Status(string[] assets, bool recursively) { return Internal_StatusStrings(assets, recursively); } static public Task Status(string asset) { return Internal_StatusStrings(new string[] { asset }, true); } static public Task Status(string asset, bool recursively) { return Internal_StatusStrings(new string[] { asset }, recursively); } static public Task Move(string from, string to) { return Internal_MoveAsStrings(from, to); } static public bool CheckoutIsValid(AssetList assets) { return CheckoutIsValid(assets, CheckoutMode.Exact); } static public bool CheckoutIsValid(AssetList assets, CheckoutMode mode) { return Internal_CheckoutIsValid(assets.ToArray(), mode); } //Returns null except where there is an error static private Task CheckAndCreateUserSuppliedChangeSet(string changesetID, string description, ref ChangeSet changeset) { //Options here: // ID is default and description is null - use default // ID is not default and description is null - use an existing changeset if changesets are supported // ID is default but description is not null - create a new changeset if changesets are supported // ID is not default and description is not null - This *should* rename an existing changeset to be consistent, but the current plugin doesn't implement this. Throw back an error if (string.IsNullOrEmpty(description)) { if (changesetID == ChangeSet.defaultID) //Checkout to default changeset changeset = null; else { //Check that the changeset exists var task = VerifyChangesetID(changesetID); if (task != null) return task; changeset = new ChangeSet(description, changesetID); } } else { if (changesetID == ChangeSet.defaultID) { //Description is not null but no changeset ID set - create a new changeset unless the VCS provider does not support changesets if (hasChangelistSupport == false) return Internal_ErrorTask( "User-created pre-checkout callback has set a changeset description but the VCS provider does not support changesets"); var createChangeSetTask = Internal_Submit(null, null, description, true); createChangeSetTask.Wait(); if (createChangeSetTask.success == false) return createChangeSetTask; var changesetsTask = ChangeSets(); changesetsTask.Wait(); if (changesetsTask.success == false) return changesetsTask; changeset = new ChangeSet(); foreach (var queriedChangeset in changesetsTask.changeSets) { //Assuming here that changeset IDs are incremental if (System.Convert.ToInt64(queriedChangeset.id) > System.Convert.ToInt64(changeset.id)) changeset = new ChangeSet(description, queriedChangeset.id); } } else //Description and changeset ID are set - this should rename but this is not currently supported return Internal_ErrorTask("User-created pre-checkout callback has set both a changeset ID and a changeset Description. This is not currently supported."); } return null; } static internal AssetList ConsolidateAssetList(AssetList assets, CheckoutMode mode) { var consolidatedAssetArray = Internal_ConsolidateAssetList(assets.ToArray(), mode); var consolidatedAssetList = new AssetList(); consolidatedAssetList.AddRange(consolidatedAssetArray); return consolidatedAssetList; } static private Task CheckCallbackAndCheckout(AssetList assets, CheckoutMode mode, ChangeSet changeset) { var consolidatedAssetList = assets; if (preCheckoutCallback != null) { consolidatedAssetList = ConsolidateAssetList(assets, mode); mode = CheckoutMode.Exact; var changesetID = changeset == null ? ChangeSet.defaultID : changeset.id; string changesetDescription = null; try { if (preCheckoutCallback(consolidatedAssetList, ref changesetID, ref changesetDescription) == false) return Internal_WarningTask("User-created pre-checkout callback has blocked this checkout."); } catch (System.Exception ex) { return Internal_ErrorTask("User-created pre-checkout callback has raised an exception and this checkout will be blocked. Exception Message: " + ex.Message); } var changesetTask = CheckAndCreateUserSuppliedChangeSet(changesetID, changesetDescription, ref changeset); if (changesetTask != null) return changesetTask; } return Internal_Checkout(consolidatedAssetList.ToArray(), mode, changeset); } static public Task Checkout(AssetList assets, CheckoutMode mode) { return Checkout(assets, mode, null); } static public Task Checkout(AssetList assets, CheckoutMode mode, ChangeSet changeset) { return CheckCallbackAndCheckout(assets, mode, changeset); } static public Task Checkout(string[] assets, CheckoutMode mode) { return Checkout(assets, mode, null); } static public Task Checkout(string[] assets, CheckoutMode mode, ChangeSet changeset) { var assetList = new AssetList(); foreach (var path in assets) { var asset = GetAssetByPath(path); if (asset == null) { asset = new Asset(path); } assetList.Add(asset); } return CheckCallbackAndCheckout(assetList, mode, changeset); } static public Task Checkout(Object[] assets, CheckoutMode mode) { return Checkout(assets, mode, null); } static public Task Checkout(Object[] assets, CheckoutMode mode, ChangeSet changeset) { var assetList = new AssetList(); foreach (var o in assets) { assetList.Add(GetAssetByPath(AssetDatabase.GetAssetPath(o))); } return CheckCallbackAndCheckout(assetList, mode, changeset); } static public bool CheckoutIsValid(Asset asset) { return CheckoutIsValid(asset, CheckoutMode.Exact); } static public bool CheckoutIsValid(Asset asset, CheckoutMode mode) { return Internal_CheckoutIsValid(new Asset[] { asset }, mode); } static public Task Checkout(Asset asset, CheckoutMode mode) { return Checkout(asset, mode, null); } static public Task Checkout(Asset asset, CheckoutMode mode, ChangeSet changeset) { var assetList = new AssetList(); assetList.Add(asset); return CheckCallbackAndCheckout(assetList, mode, changeset); } static public Task Checkout(string asset, CheckoutMode mode) { return Checkout(asset, mode, null); } static public Task Checkout(string asset, CheckoutMode mode, ChangeSet changeset) { return Checkout(new string[] { asset }, mode, changeset); } static public Task Checkout(UnityEngine.Object asset, CheckoutMode mode) { return Checkout(asset, mode, null); } static public Task Checkout(UnityEngine.Object asset, CheckoutMode mode, ChangeSet changeset) { var path = AssetDatabase.GetAssetPath(asset); var vcasset = GetAssetByPath(path); var assetList = new AssetList(); assetList.Add(vcasset); return CheckCallbackAndCheckout(assetList, mode, changeset); } internal static bool HandlePreCheckoutCallback(ref string[] paths, ref ChangeSet changeSet) { if (preCheckoutCallback == null) return true; var assetList = new AssetList(); assetList.AddRange(paths.Select(GetAssetByPath).Where(a => a != null)); try { var id = changeSet == null ? ChangeSet.defaultID : changeSet.id; string desc = null; if (preCheckoutCallback(assetList, ref id, ref desc)) { var task = CheckAndCreateUserSuppliedChangeSet(id, desc, ref changeSet); if (task != null) { Debug.LogError( "Tried to create/rename remote ChangeSet to match the one specified in user-supplied callback but failed with error code: " + task.resultCode); return false; } paths = assetList.Where(a => a != null).Select(a => a.path).ToArray(); } else { Debug.LogWarning("User-created pre-checkout callback has blocked this checkout."); return false; } } catch (System.Exception ex) { Debug.LogWarning("User-created pre-checkout callback has thrown an exception: " + ex.Message); return false; } return true; } static public Task Delete(string assetProjectPath) { return Internal_DeleteAtProjectPath(assetProjectPath); } static public Task Delete(AssetList assets) { return Internal_Delete(assets.ToArray()); } static public Task Delete(Asset asset) { return Internal_Delete(new Asset[] { asset }); } static public bool AddIsValid(AssetList assets) { return Internal_AddIsValid(assets.ToArray()); } static public Task Add(AssetList assets, bool recursive) { return Internal_Add(assets.ToArray(), recursive); } static public Task Add(Asset asset, bool recursive) { return Internal_Add(new Asset[] { asset }, recursive); } static public bool DeleteChangeSetsIsValid(ChangeSets changesets) { return Internal_DeleteChangeSetsIsValid(changesets.ToArray()); } static public Task DeleteChangeSets(ChangeSets changesets) { return Internal_DeleteChangeSets(changesets.ToArray()); } static internal Task RevertChangeSets(ChangeSets changesets, RevertMode mode) { return Internal_RevertChangeSets(changesets.ToArray(), mode); } static public bool SubmitIsValid(ChangeSet changeset, AssetList assets) { return Internal_SubmitIsValid(changeset, assets != null ? assets.ToArray() : null); } private static Task VerifyChangesetID(string changesetID) { var changesetsTask = ChangeSets(); changesetsTask.Wait(); if (changesetsTask.success == false) { Debug.LogError(string.Format("Tried to validate user-supplied changeset ID {0} but Provider.ChangeSets task failed. See returned Task for details.", changesetID)); return changesetsTask; } var idIsValid = false; foreach (var changesetToCheck in changesetsTask.changeSets) { if (changesetToCheck.id == changesetID) { idIsValid = true; break; } } if (idIsValid == false) return Internal_ErrorTask(string.Format("The supplied changeset ID '{0}' did not match any known outgoing changesets. Aborting Task.", changesetID)); return null; } static public Task Submit(ChangeSet changeset, AssetList list, string description, bool saveOnly) { if (preSubmitCallback != null) { var changesetID = changeset == null ? ChangeSet.defaultID : changeset.id; try { if (preSubmitCallback(list, ref changesetID, ref description) == false) return Internal_WarningTask("User-created pre-submit callback has blocked this changeset submission."); } catch (System.Exception ex) { return Internal_ErrorTask("User-created pre-submit callback has raised an exception and this submission will be blocked. Exception Message: " + ex.Message); } if (changesetID == ChangeSet.defaultID) changeset = null; else { //Check that the changeset exists var task = VerifyChangesetID(changesetID); if (task != null) return task; changeset = new ChangeSet(description, changesetID); } } return Internal_Submit(changeset, list != null ? list.ToArray() : null, description, saveOnly); } static public bool DiffIsValid(AssetList assets) { return Internal_DiffIsValid(assets.ToArray()); } static public Task DiffHead(AssetList assets, bool includingMetaFiles) { return Internal_DiffHead(assets.ToArray(), includingMetaFiles); } static public bool ResolveIsValid(AssetList assets) { return Internal_ResolveIsValid(assets.ToArray()); } static public Task Resolve(AssetList assets, ResolveMethod resolveMethod) { return Internal_Resolve(assets.ToArray(), resolveMethod); } static public Task Merge(AssetList assets) { return Internal_Merge(assets.ToArray()); } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ExcludeFromDocs] [System.Obsolete("MergeMethod is no longer used.")] static public Task Merge(AssetList assets, MergeMethod method) { return Internal_Merge(assets.ToArray()); } static public bool LockIsValid(AssetList assets) { return Internal_LockIsValid(assets.ToArray()); } static public bool LockIsValid(Asset asset) { return Internal_LockIsValid(new Asset[] { asset }); } static public bool UnlockIsValid(AssetList assets) { return Internal_UnlockIsValid(assets.ToArray()); } static public bool UnlockIsValid(Asset asset) { return Internal_UnlockIsValid(new Asset[] { asset }); } static public Task Lock(AssetList assets, bool locked) { return Internal_Lock(assets.ToArray(), locked); } static public Task Lock(Asset asset, bool locked) { return Internal_Lock(new Asset[] { asset }, locked); } static public bool RevertIsValid(AssetList assets, RevertMode mode) { return Internal_RevertIsValid(assets.ToArray(), mode); } static public Task Revert(AssetList assets, RevertMode mode) { return Internal_Revert(assets.ToArray(), mode); } static public bool RevertIsValid(Asset asset, RevertMode mode) { return Internal_RevertIsValid(new Asset[] { asset }, mode); } static public Task Revert(Asset asset, RevertMode mode) { return Internal_Revert(new Asset[] { asset }, mode); } static public bool GetLatestIsValid(AssetList assets) { return Internal_GetLatestIsValid(assets.ToArray()); } static public bool GetLatestIsValid(Asset asset) { return Internal_GetLatestIsValid(new Asset[] { asset }); } static public Task GetLatest(AssetList assets) { return Internal_GetLatest(assets.ToArray()); } static public Task GetLatest(Asset asset) { return Internal_GetLatest(new Asset[] { asset }); } static internal Task SetFileMode(AssetList assets, FileMode mode) { return Internal_SetFileMode(assets.ToArray(), mode); } static internal Task SetFileMode(string[] assets, FileMode mode) { return Internal_SetFileModeStrings(assets, mode); } static public Task ChangeSetDescription(ChangeSet changeset) { return Internal_ChangeSetDescription(changeset); } static public Task ChangeSetStatus(ChangeSet changeset) { return Internal_ChangeSetStatus(changeset); } static public Task ChangeSetStatus(string changesetID) { ChangeSet cl = new ChangeSet("", changesetID); return Internal_ChangeSetStatus(cl); } static public Task IncomingChangeSetAssets(ChangeSet changeset) { return Internal_IncomingChangeSetAssets(changeset); } static public Task IncomingChangeSetAssets(string changesetID) { ChangeSet cl = new ChangeSet("", changesetID); return Internal_IncomingChangeSetAssets(cl); } static public Task ChangeSetMove(AssetList assets, ChangeSet changeset) { return Internal_ChangeSetMove(assets.ToArray(), changeset); } static public Task ChangeSetMove(Asset asset, ChangeSet changeset) { return Internal_ChangeSetMove(new Asset[] { asset }, changeset); } static public Task ChangeSetMove(AssetList assets, string changesetID) { ChangeSet cl = new ChangeSet("", changesetID); return Internal_ChangeSetMove(assets.ToArray(), cl); } static public Task ChangeSetMove(Asset asset, string changesetID) { ChangeSet cl = new ChangeSet("", changesetID); return Internal_ChangeSetMove(new Asset[] { asset }, cl); } static public AssetList GetAssetListFromSelection() { var list = new AssetList(); foreach (var asset in Internal_GetAssetArrayFromSelection()) { list.Add(asset); } return list; } public delegate bool PreSubmitCallback(AssetList list, ref string changesetID, ref string changesetDescription); static public PreSubmitCallback preSubmitCallback; public delegate bool PreCheckoutCallback(AssetList list, ref string changesetID, ref string changesetDescription); static public PreCheckoutCallback preCheckoutCallback; } }
UnityCsReference/Editor/Mono/VersionControl/Common/VCProvider.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/VersionControl/Common/VCProvider.cs", "repo_id": "UnityCsReference", "token_count": 9723 }
347
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEditor.ShortcutManagement; using UnityEngine; using UnityEngine.Scripting; using UnityEditorInternal.VersionControl; namespace UnityEditor.VersionControl { // Pending change list window which shows all the change lists for the version control system. This is // agnostic of any version control system as long as it supports the VCInterface interface. // // This window now works in an async manner but the method of update should now be improved to hide // the refreshing [EditorWindowTitle(title = "Version Control", icon = "UnityEditor.VersionControl")] internal class WindowPending : EditorWindow { internal class Styles { public GUIStyle box = "CN Box"; public GUIStyle bottomBarBg = "ProjectBrowserBottomBarBg"; public static readonly GUIContent connectingLabel = EditorGUIUtility.TrTextContent("CONNECTING..."); public static readonly GUIContent offlineLabel = EditorGUIUtility.TrTextContent("OFFLINE"); public static readonly GUIContent workOfflineLabel = EditorGUIUtility.TrTextContent("WORK OFFLINE is enabled in Version Control Settings. Unity will behave as if version control is disabled."); public static readonly GUIContent disabledLabel = EditorGUIUtility.TrTextContent("Disabled"); public static readonly GUIContent editorSettingsLabel = EditorGUIUtility.TrTextContent("Version Control Settings"); } static Styles s_Styles = null; static Texture2D changeIcon = null; static Texture2D syncIcon = null; static Texture2D refreshIcon = null; GUIStyle header; [SerializeField] ListControl pendingList; [SerializeField] ListControl incomingList; bool m_ShowIncoming = false; bool m_ShowIncomingPrevious = true; const float k_MinWindowHeight = 100f; const float k_ResizerHeight = 17f; const float k_MinIncomingAreaHeight = 50f; const float k_BottomBarHeight = 21f; const float k_MinSearchFieldWidth = 50f; const float k_MaxSearchFieldWidth = 240f; float s_ToolbarButtonsWidth = 0f; float s_SettingsButtonWidth = 0f; float s_DeleteChangesetsButtonWidth = 0f; string m_SearchText = string.Empty; DateTime lastRefresh = new DateTime(0); private int refreshInterval = 1000; // this is in MS private bool scheduleRefresh = false; // Workaround to reload vcs info upon domain reload. TODO: Fix VersionControl.ListControl to get rid of this static bool s_DidReload = false; // defaults to false after domain reload void InitStyles() { if (s_Styles == null) { s_Styles = new Styles(); } } void OnEnable() { titleContent = GetLocalizedTitleContent(); if (pendingList == null) pendingList = new ListControl(); pendingList.ExpandEvent += OnExpand; pendingList.DragEvent += OnDrop; pendingList.MenuDefault = "CONTEXT/Pending"; pendingList.MenuFolder = "CONTEXT/Change"; pendingList.DragAcceptOnly = true; if (incomingList == null) incomingList = new ListControl(); incomingList.ExpandEvent += OnExpandIncoming; UpdateWindow(); } // Watch for selections from another window public void OnSelectionChange() { if (!hasFocus) { pendingList.Sync(); Repaint(); } } // Handle drag events from the list void OnDrop(ChangeSet targetItem) { AssetList list = pendingList.SelectedAssets; Task moveTask = Provider.ChangeSetMove(list, targetItem); moveTask.SetCompletionAction(CompletionAction.UpdatePendingWindow); } static public void ExpandLatestChangeSet() { var wins = Resources.FindObjectsOfTypeAll(typeof(WindowPending)) as WindowPending[]; foreach (WindowPending win in wins) { win.pendingList.ExpandLastItem(); } } // Handle list elements being expanded void OnExpand(ChangeSet change, ListItem item) { if (!Provider.isActive) return; Task task = Provider.ChangeSetStatus(change); task.userIdentifier = item.Identifier; task.SetCompletionAction(CompletionAction.OnChangeContentsPendingWindow); if (!item.HasChildren) { Asset asset = new Asset("Updating..."); ListItem changeItem = pendingList.Add(item, asset.prettyPath, asset); changeItem.Dummy = true; pendingList.Refresh(false); //true here would cause recursion pendingList.Filter = m_SearchText; Repaint(); } } void OnExpandIncoming(ChangeSet change, ListItem item) { if (!Provider.isActive) return; Task task = Provider.IncomingChangeSetAssets(change); task.userIdentifier = item.Identifier; task.SetCompletionAction(CompletionAction.OnChangeContentsPendingWindow); if (!item.HasChildren) { Asset asset = new Asset("Updating..."); ListItem changeItem = incomingList.Add(item, asset.prettyPath, asset); changeItem.Dummy = true; incomingList.Refresh(false); //true here would cause recursion incomingList.Filter = m_SearchText; Repaint(); } } // called to update the status void UpdateWindow() { if (!Provider.isActive) { pendingList.Clear(); Repaint(); return; } if (TimeElapsed() > refreshInterval) { if (Provider.onlineState == OnlineState.Online) { Task changesTask = Provider.ChangeSets(); changesTask.SetCompletionAction(CompletionAction.OnChangeSetsPendingWindow); Task incomingTask = Provider.Incoming(); incomingTask.SetCompletionAction(CompletionAction.OnIncomingPendingWindow); } lastRefresh = DateTime.Now; } else scheduleRefresh = true; } void OnGotLatest(Task t) { UpdateWindow(); } [RequiredByNativeCode] static void OnVCTaskCompletedEvent(Task task, CompletionAction completionAction) { // inspector should re-calculate which VCS buttons it needs to show InspectorWindow.ClearVersionControlBarState(); var wins = Resources.FindObjectsOfTypeAll(typeof(WindowPending)) as WindowPending[]; foreach (WindowPending win in wins) { switch (completionAction) { case CompletionAction.UpdatePendingWindow: // fallthrough case CompletionAction.OnCheckoutCompleted: win.UpdateWindow(); break; case CompletionAction.OnChangeContentsPendingWindow: win.OnChangeContents(task); break; case CompletionAction.OnIncomingPendingWindow: win.OnIncoming(task); break; case CompletionAction.OnChangeSetsPendingWindow: win.OnChangeSets(task); break; case CompletionAction.OnGotLatestPendingWindow: win.OnGotLatest(task); break; } } switch (completionAction) { case CompletionAction.OnSubmittedChangeWindow: WindowChange.OnSubmitted(task); break; case CompletionAction.OnAddedChangeWindow: WindowChange.OnAdded(task); break; case CompletionAction.OnCheckoutCompleted: if (EditorUserSettings.showFailedCheckout) WindowCheckoutFailure.OpenIfCheckoutFailed(task.assetList); break; } task.Dispose(); } public static void OnStatusUpdated() { UpdateAllWindows(); } [RequiredByNativeCode] public static void UpdateAllWindows() { // inspector should re-calculate which VCS buttons it needs to show InspectorWindow.ClearVersionControlBarState(); var wins = Resources.FindObjectsOfTypeAll(typeof(WindowPending)) as WindowPending[]; foreach (WindowPending win in wins) { win.UpdateWindow(); } } public static void CloseAllWindows() { var wins = Resources.FindObjectsOfTypeAll(typeof(WindowPending)) as WindowPending[]; WindowPending win = wins.Length > 0 ? wins[0] : null; if (win != null) { win.Close(); } } // Incoming Change Lists have been updated void OnIncoming(Task task) { CreateStaticResources(); PopulateListControl(incomingList, task, syncIcon); } // Change lists have been updated void OnChangeSets(Task task) { CreateStaticResources(); PopulateListControl(pendingList, task, changeIcon); } internal string FormatChangeSetDescription(ChangeSet changeSet) { string formattedDescription; string[] description = changeSet.description.Split(new char[] {'\n'}, StringSplitOptions.RemoveEmptyEntries); formattedDescription = description.Length > 1 ? description[0] + description[1] : description[0]; formattedDescription = formattedDescription.Replace('\t', ' '); switch (VersionControlSettings.mode) { case "Perforce": return changeSet.id + ": " + formattedDescription; default: return changeSet.description; } } internal void PopulateListControl(ListControl list, Task task, Texture2D icon) { // We try to correct the existing list by removing/adding entries. // This way the entries will keep their children while the children are updated // and will prevent flicker // list.Clear (); // Remove from existing list entries not in the incoming one ChangeSets css = task.changeSets; ListItem it = list.Root.FirstChild; while (it != null) { ChangeSet cs = it.Item as ChangeSet; if (css.Find(elm => elm.id == cs.id) == null) { // Found an list item that was not in the incoming list. // Lets remove it. ListItem rm = it; it = it.Next; list.Root.Remove(rm); } else { it = it.Next; } } // Update the existing ones with the new content or add new ones foreach (ChangeSet change in css) { ListItem changeItem = list.GetChangeSetItem(change); if (changeItem != null) { changeItem.Item = change; changeItem.Name = FormatChangeSetDescription(change); } else { changeItem = list.Add(null, FormatChangeSetDescription(change), change); } changeItem.Exclusive = true; // Single selection only changeItem.CanAccept = true; // Accept drag and drop changeItem.Icon = icon; // changeset icon } // Refresh here will trigger the expand events to ensure the same change lists // are kept open. This will in turn trigger change list contents update requests list.Refresh(); list.Filter = m_SearchText; Repaint(); } // Change list contents have been updated void OnChangeContents(Task task) { ListItem pendingItem = pendingList.FindItemWithIdentifier(task.userIdentifier); ListItem item = pendingItem == null ? incomingList.FindItemWithIdentifier(task.userIdentifier) : pendingItem; if (item == null) return; ListControl list = pendingItem == null ? incomingList : pendingList; item.RemoveAll(); AssetList assetList = task.assetList; assetList.NaturalSort(); // Add all files to the list if (assetList.Count == 0) { // Can only happen for pendingList since incoming lists are frozen by design. ListItem empty = list.Add(item, ListControl.c_emptyChangeListMessage, (Asset)null); empty.Dummy = true; } else { foreach (Asset a in assetList) list.Add(item, a.prettyPath, a); } list.Refresh(false); // false means the expanded events are not called list.Filter = m_SearchText; Repaint(); } private ChangeSets GetEmptyChangeSetsCandidates() { ListControl l = pendingList; ChangeSets set = l.EmptyChangeSets; ChangeSets toDelete = new ChangeSets(); set .FindAll(item => item.id != ChangeSet.defaultID) .ForEach(delegate(ChangeSet s) { toDelete.Add(s); }); return toDelete; } private bool HasEmptyPendingChangesets() { ChangeSets changeSets = GetEmptyChangeSetsCandidates(); return Provider.DeleteChangeSetsIsValid(changeSets); } private void DeleteEmptyPendingChangesets() { ChangeSets changeSets = GetEmptyChangeSetsCandidates(); Provider.DeleteChangeSets(changeSets).SetCompletionAction(CompletionAction.UpdatePendingWindow); } private void SearchField(Event e, ListControl activeList) { string searchBarName = "SearchFilter"; if (e.commandName == EventCommandNames.Find) { if (e.type == EventType.ExecuteCommand) { EditorGUI.FocusTextInControl(searchBarName); } if (e.type != EventType.Layout) e.Use(); } string searchText = m_SearchText; if (e.type == EventType.KeyDown) { if (e.keyCode == KeyCode.Escape) { m_SearchText = searchText = string.Empty; activeList.Filter = searchText; GUI.FocusControl(null); activeList.SelectedSet(activeList.Root.NextOpenVisible); } else if ((e.keyCode == KeyCode.UpArrow || e.keyCode == KeyCode.DownArrow || e.keyCode == KeyCode.Return) && GUI.GetNameOfFocusedControl() == searchBarName) { GUI.FocusControl(null); activeList.SelectedSet(activeList.Root.NextOpenVisible); } } GUI.SetNextControlName(searchBarName); Rect rect = GUILayoutUtility.GetRect(0, EditorGUILayout.kLabelFloatMaxW * 1.5f, EditorGUI.kSingleLineHeight, EditorGUI.kSingleLineHeight, EditorStyles.toolbarSearchField, GUILayout.MinWidth(k_MinSearchFieldWidth), GUILayout.MaxWidth(k_MaxSearchFieldWidth)); var filteringText = EditorGUI.ToolbarSearchField(rect, searchText, false); if (m_SearchText != filteringText) { m_SearchText = filteringText; activeList.SelectedClear(); activeList.listState.Scroll = 0; activeList.Filter = filteringText; } } // Editor window GUI paint void OnGUI() { InitStyles(); if (!s_DidReload) { s_DidReload = true; UpdateWindow(); } CreateResources(); float toolBarHeight = EditorStyles.toolbar.fixedHeight; bool refresh = false; GUILayout.BeginArea(new Rect(0, 0, position.width, toolBarHeight)); GUILayout.BeginHorizontal(EditorStyles.toolbar); EditorGUI.BeginChangeCheck(); int incomingChangesetCount = incomingList.Root == null ? 0 : incomingList.Root.ChildCount; bool switchToOutgoing = GUILayout.Toggle(!m_ShowIncoming, "Outgoing", EditorStyles.toolbarButton); GUIContent cont = GUIContent.Temp("Incoming" + (incomingChangesetCount == 0 ? "" : " (" + incomingChangesetCount + ")")); bool switchToIncoming = GUILayout.Toggle(m_ShowIncoming, cont, EditorStyles.toolbarButton); m_ShowIncoming = m_ShowIncoming ? !switchToOutgoing : switchToIncoming; if (EditorGUI.EndChangeCheck()) refresh = true; GUILayout.FlexibleSpace(); Event e = Event.current; SearchField(e, m_ShowIncoming ? incomingList : pendingList); // Global context custom commands goes here using (new EditorGUI.DisabledScope(Provider.activeTask != null)) { foreach (CustomCommand c in Provider.customCommands) { if (c.context == CommandContext.Global && GUILayout.Button(c.label, EditorStyles.toolbarButton)) c.StartTask(); } } bool showDeleteEmptyChangesetsButton = Mathf.FloorToInt(position.width - s_ToolbarButtonsWidth - k_MinSearchFieldWidth - s_SettingsButtonWidth - s_DeleteChangesetsButtonWidth) > 0 && HasEmptyPendingChangesets(); if (showDeleteEmptyChangesetsButton && GUILayout.Button("Delete Empty Changesets", EditorStyles.toolbarButton)) { DeleteEmptyPendingChangesets(); } bool showSettingsButton = Mathf.FloorToInt(position.width - s_ToolbarButtonsWidth - k_MinSearchFieldWidth - s_SettingsButtonWidth) > 0; if (showSettingsButton && GUILayout.Button(Styles.editorSettingsLabel, EditorStyles.toolbarButton)) { SettingsService.OpenProjectSettings("Project/Version Control"); EditorWindow.FocusWindowIfItsOpen<InspectorWindow>(); GUIUtility.ExitGUI(); } bool refreshButtonClicked = GUILayout.Button(refreshIcon, EditorStyles.toolbarButton); refresh = refresh || refreshButtonClicked || scheduleRefresh; bool repaint = false; if (refresh) { if (refreshButtonClicked) { m_SearchText = string.Empty; GUI.FocusControl(null); Provider.InvalidateCache(); Provider.UpdateSettings(); } repaint = true; scheduleRefresh = false; UpdateWindow(); } GUILayout.EndArea(); Rect rect = new Rect(0, toolBarHeight, position.width, position.height - toolBarHeight - k_BottomBarHeight); GUILayout.EndHorizontal(); if (EditorUserSettings.WorkOffline) { GUI.color = new Color(0.8f, 0.5f, 0.5f); rect.height = toolBarHeight; GUILayout.BeginArea(rect); GUILayout.BeginHorizontal(EditorStyles.toolbar); GUILayout.FlexibleSpace(); GUILayout.Label(Styles.workOfflineLabel, EditorStyles.miniLabel); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.EndArea(); } // Disabled Window view else if (!Provider.isActive) { Color tmpColor = GUI.color; GUI.color = new Color(0.8f, 0.5f, 0.5f); rect.height = toolBarHeight; GUILayout.BeginArea(rect); GUILayout.BeginHorizontal(EditorStyles.toolbar); GUILayout.FlexibleSpace(); if (Provider.enabled) { if (Provider.onlineState == OnlineState.Updating) { GUI.color = new Color(0.8f, 0.8f, 0.5f); GUILayout.Label(Styles.connectingLabel, EditorStyles.miniLabel); } else GUILayout.Label(Styles.offlineLabel, EditorStyles.miniLabel); } else GUILayout.Label(Styles.disabledLabel, EditorStyles.miniLabel); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.EndArea(); rect.y += rect.height; if (!string.IsNullOrEmpty(Provider.offlineReason)) GUI.Label(rect, Provider.offlineReason); GUI.color = tmpColor; repaint = false; } else { if (m_ShowIncoming) { repaint |= incomingList.OnGUI(rect, hasFocus); } else { repaint |= pendingList.OnGUI(rect, hasFocus); } rect.y += rect.height; rect.height = k_BottomBarHeight; // Draw separation line over the button GUI.Label(rect, GUIContent.none, s_Styles.bottomBarBg); var content = EditorGUIUtility.TrTextContent("Apply All Incoming Changes"); var buttonSize = EditorStyles.miniButton.CalcSize(content); Rect progressRect = new Rect(rect.x, rect.y - 2, rect.width - buttonSize.x - 5f, rect.height); ProgressGUI(progressRect, Provider.activeTask, false); if (m_ShowIncoming) { // Draw "apply incoming" button var buttonRect = rect; buttonRect.width = buttonSize.x; buttonRect.height = buttonSize.y; buttonRect.y = rect.y + 2f; buttonRect.x = position.width - buttonSize.x - 5f; using (new EditorGUI.DisabledScope(incomingList?.Root?.VisibleChildCount == 0)) { if (GUI.Button(buttonRect, content, EditorStyles.miniButton)) { Asset root = new Asset(""); Task t = Provider.GetLatest(new AssetList() { root }); t.SetCompletionAction(CompletionAction.OnGotLatestPendingWindow); } } } } if (m_ShowIncoming != m_ShowIncomingPrevious) { (m_ShowIncoming ? incomingList : pendingList).Filter = m_SearchText; m_ShowIncomingPrevious = m_ShowIncoming; } if (repaint) Repaint(); } [Shortcut("VersionControl/RefreshWindow", typeof(WindowPending), KeyCode.F5, displayName = "Version Control/Refresh Window")] static void RefreshWindow(ShortcutArguments args) { if (GUIUtility.keyboardControl != 0) return; (args.context as WindowPending).UpdateWindow(); } /* Keep for future description area void ResizeHandling (float width, float height) { // We add a horizontal size controller to adjust incoming vs outgoing area float headersHeight = 26f + k_ResizerHeight + EditorStyles.toolbarButton.fixedHeight; Rect dragRect = new Rect (0f, m_IncomingAreaHeight + headersHeight, width, k_ResizerHeight); if (Event.current.type == EventType.Repaint) EditorGUIUtility.AddCursorRect (dragRect, MouseCursor.ResizeVertical); // Drag internal splitter float deltaY = EditorGUI.MouseDeltaReader(dragRect, true).y; if (deltaY != 0f) { m_IncomingAreaHeight += deltaY; } float maxHeight = height - k_MinIncomingAreaHeight - headersHeight; m_IncomingAreaHeight = Mathf.Clamp (m_IncomingAreaHeight, k_MinIncomingAreaHeight, maxHeight); } */ internal static bool ProgressGUI(Rect rect, Task activeTask, bool descriptionTextFirst) { if (activeTask != null && (activeTask.progressPct != -1 || activeTask.secondsSpent != -1 || activeTask.progressMessage.Length != 0)) { string msg = activeTask.progressMessage; Rect sr = rect; GUIContent cont = UnityEditorInternal.InternalEditorUtility.animatedProgressImage; sr.width = sr.height; sr.x += 4; sr.y += 4; GUI.Label(sr, cont); rect.x += sr.width + 4; msg = msg.Length == 0 ? activeTask.description : msg; if (activeTask.progressPct == -1) { rect.width -= sr.width + 4; rect.y += 4; GUI.Label(rect, msg, EditorStyles.miniLabel); } else { rect.width = 120; EditorGUI.ProgressBar(rect, activeTask.progressPct, msg); } return true; } return false; } void CreateResources() { if (refreshIcon == null) { refreshIcon = EditorGUIUtility.LoadIcon("Refresh"); refreshIcon.hideFlags = HideFlags.HideAndDontSave; refreshIcon.name = "RefreshIcon"; } if (header == null) header = "OL Title"; CreateStaticResources(); if (s_ToolbarButtonsWidth == 0f) { s_ToolbarButtonsWidth = EditorStyles.toolbarButton.CalcSize(EditorGUIUtility.TrTextContent("Incoming (xx)")).x; s_ToolbarButtonsWidth += EditorStyles.toolbarButton.CalcSize(EditorGUIUtility.TrTextContent("Outgoing")).x; s_ToolbarButtonsWidth += EditorStyles.toolbarButton.CalcSize(new GUIContent(refreshIcon)).x; s_SettingsButtonWidth = EditorStyles.toolbarButton.CalcSize(Styles.editorSettingsLabel).x; s_DeleteChangesetsButtonWidth = EditorStyles.toolbarButton.CalcSize(EditorGUIUtility.TrTextContent("Delete Empty Changesets")).x; minSize = new Vector2(s_ToolbarButtonsWidth + k_MinSearchFieldWidth, k_MinWindowHeight); } } void CreateStaticResources() { if (syncIcon == null) { syncIcon = EditorGUIUtility.LoadIcon("VersionControl/Incoming Icon"); syncIcon.hideFlags = HideFlags.HideAndDontSave; syncIcon.name = "SyncIcon"; } if (changeIcon == null) { changeIcon = EditorGUIUtility.LoadIcon("VersionControl/Outgoing Icon"); changeIcon.hideFlags = HideFlags.HideAndDontSave; changeIcon.name = "ChangeIcon"; } } double TimeElapsed() { var elapsed = DateTime.Now - lastRefresh; return elapsed.TotalMilliseconds; } } }
UnityCsReference/Editor/Mono/VersionControl/UI/VCWindowPending.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/VersionControl/UI/VCWindowPending.cs", "repo_id": "UnityCsReference", "token_count": 14059 }
348
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Linq; using UnityEngine; using UnityEngine.Scripting; namespace UnityEditor { // The WindowAction attribute allows you to add global actions to the windows (items in the generic menu or extra buttons). [AttributeUsage(AttributeTargets.Method)] internal sealed class WindowActionAttribute : Attribute { [RequiredSignature] private static WindowAction signature() { return null; } } internal class WindowAction { public delegate void ExecuteHandler(EditorWindow window, WindowAction action); public delegate bool ValidateHandler(EditorWindow window, WindowAction action); public delegate bool DrawHandler(EditorWindow window, WindowAction action, Rect rect); public string id; public ExecuteHandler executeHandler; public object userData; public ValidateHandler validateHandler; public string menuPath; public float? width; public Texture2D icon; public DrawHandler drawHandler; // i.e. if used in the tab bar public int priority; private WindowAction(string id, ExecuteHandler executeHandler, string menuPath) { this.id = id; this.executeHandler = executeHandler; this.menuPath = menuPath; } public static WindowAction CreateWindowMenuItem(string id, ExecuteHandler executeHandler, string menuPath) { return new WindowAction(id, executeHandler, menuPath); } public static WindowAction CreateWindowActionButton(string id, ExecuteHandler executeHandler, string menuPath, float width, Texture2D icon) { return new WindowAction(id, executeHandler, menuPath) { width = width, icon = icon }; } public static WindowAction CreateWindowActionButton(string id, ExecuteHandler executeHandler, string menuPath, float width, DrawHandler drawHandler) { return new WindowAction(id, executeHandler, menuPath) { width = width, drawHandler = drawHandler }; } } }
UnityCsReference/Editor/Mono/WindowAction.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/WindowAction.cs", "repo_id": "UnityCsReference", "token_count": 896 }
349
// // File autogenerated from Include/C/Baselib_NetworkAddress.h // using System; using System.Runtime.InteropServices; using UnityEngine.Bindings; using size_t = System.UIntPtr; namespace Unity.Baselib.LowLevel { [NativeHeader("baselib/CSharp/BindingsUnity/Baselib_NetworkAddress.gen.binding.h")] internal static unsafe partial class Binding { /// <summary>Address family.</summary> public enum Baselib_NetworkAddress_Family : Int32 { Invalid = 0x0, IPv4 = 0x1, IPv6 = 0x2, } /// <summary>Fixed size address structure, large enough to hold IPv4 and IPv6 addresses.</summary> [StructLayout(LayoutKind.Explicit)] public struct Baselib_NetworkAddress { // byte data[16]; [FieldOffset(0)] public byte data0; [FieldOffset(1)] public byte data1; [FieldOffset(2)] public byte data2; [FieldOffset(3)] public byte data3; [FieldOffset(4)] public byte data4; [FieldOffset(5)] public byte data5; [FieldOffset(6)] public byte data6; [FieldOffset(7)] public byte data7; [FieldOffset(8)] public byte data8; [FieldOffset(9)] public byte data9; [FieldOffset(10)] public byte data10; [FieldOffset(11)] public byte data11; [FieldOffset(12)] public byte data12; [FieldOffset(13)] public byte data13; [FieldOffset(14)] public byte data14; [FieldOffset(15)] public byte data15; // byte ipv6[16]; [FieldOffset(0)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_0; [FieldOffset(1)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_1; [FieldOffset(2)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_2; [FieldOffset(3)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_3; [FieldOffset(4)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_4; [FieldOffset(5)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_5; [FieldOffset(6)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_6; [FieldOffset(7)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_7; [FieldOffset(8)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_8; [FieldOffset(9)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_9; [FieldOffset(10)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_10; [FieldOffset(11)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_11; [FieldOffset(12)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_12; [FieldOffset(13)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_13; [FieldOffset(14)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_14; [FieldOffset(15)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_15; // byte ipv4[4]; [FieldOffset(0)] [Ignore(DoesNotContributeToSize = true)] public byte ipv4_0; [FieldOffset(1)] [Ignore(DoesNotContributeToSize = true)] public byte ipv4_1; [FieldOffset(2)] [Ignore(DoesNotContributeToSize = true)] public byte ipv4_2; [FieldOffset(3)] [Ignore(DoesNotContributeToSize = true)] public byte ipv4_3; /// <summary>in network byte order</summary> // byte port[2]; [FieldOffset(16)] public byte port0; [FieldOffset(17)] public byte port1; [FieldOffset(18)] public byte family; /// <summary>Explicit padding to allow for deterministic bitwise compare.</summary> [FieldOffset(19)] public byte _padding; /// <summary> /// Scope zone index for IPv6 (ignored for IPv4) /// Defaults to zero if not specified. /// Note that unlike the other fields in this struct, this is *not* in network byte order! /// </summary> [FieldOffset(20)] public UInt32 ipv6_scope_id; } /// <summary>Max length of any string representing an IP address</summary> public const UInt32 Baselib_NetworkAddress_IpMaxStringLength = 46; /// <summary>Binary encode string representation of an address.</summary> /// <remarks> /// Neither port not ipAddressBuffer scope id are parsed from the ip string. /// dstAddress->ipv6_scope_id is set to zero and needs to be manually set if required. /// /// Possible error codes: /// - Baselib_ErrorCode_InvalidArgument - One or more of the input parameters are invalid /// </remarks> [FreeFunction(IsThreadSafe = true)] public static extern void Baselib_NetworkAddress_Encode(Baselib_NetworkAddress* dstAddress, Baselib_NetworkAddress_Family family, byte* ip, UInt16 port, Baselib_ErrorState* errorState); /// <summary>Decode binary representation of an address.</summary> /// <remarks> /// family, ipAddressBuffer, and port are all optional arguments. /// passing zero as ipAddressBufferLen is the same as passing an ipAddressBuffer nullptr. /// Port and IPv6 scope id are not encodeded to ipAddressBuffer. /// /// Possible error codes: /// - Baselib_ErrorCode_InvalidArgument - srcAddress is null or otherwise invalid. /// - Baselib_ErrorCode_InvalidBufferSize - ipAddressBuffer is too small to hold decoded ip address. /// </remarks> [FreeFunction(IsThreadSafe = true)] public static extern void Baselib_NetworkAddress_Decode(Baselib_NetworkAddress* srcAddress, Baselib_NetworkAddress_Family* family, byte* ipAddressBuffer, UInt32 ipAddressBufferLen, UInt16* port, Baselib_ErrorState* errorState); public enum Baselib_NetworkAddress_AddressReuse : Int32 { DoNotAllow = 0x0, /// <summary> /// Allow multiple sockets to be bound to the same address/port. /// All sockets bound to the same address/port need to have this flag set. /// </summary> Allow = 0x1, } } }
UnityCsReference/External/baselib/baselib/CSharp/BindingsUnity/Baselib_NetworkAddress.gen.binding.cs/0
{ "file_path": "UnityCsReference/External/baselib/baselib/CSharp/BindingsUnity/Baselib_NetworkAddress.gen.binding.cs", "repo_id": "UnityCsReference", "token_count": 3318 }
350
For terms of use, see https://unity3d.com/legal/licenses/Unity_Reference_Only_License
UnityCsReference/LICENSE.md/0
{ "file_path": "UnityCsReference/LICENSE.md", "repo_id": "UnityCsReference", "token_count": 27 }
351
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Runtime.CompilerServices; using UnityEngine; using UnityEngine.AI; using UnityEngine.Scripting.APIUpdating; using UnityEngine.Bindings; using UnityEngine.Scripting; [assembly:InternalsVisibleTo("Unity.AI.Navigation.Editor")] [assembly:InternalsVisibleTo("Unity.AI.Navigation.Editor")] namespace UnityEditor.AI { [MovedFrom("UnityEditor")] [StaticAccessor("GetNavMeshVisualizationSettings()", StaticAccessorType.Dot)] public sealed class NavMeshVisualizationSettings { [Obsolete("showNavigation is no longer supported and will be removed.")] public static int showNavigation { get; set; } internal static extern bool showOnlySelectedSurfaces { get; set; } internal static extern Color32 heightMeshColor { get; set; } internal static extern float selectedSurfacesOpacity { get; set; } internal static extern float unselectedSurfacesOpacity { get; set; } internal static extern bool showNavMesh { get; set; } internal static extern bool showHeightMesh { get; set; } internal static extern bool showNavMeshPortals { get; set; } internal static extern bool showNavMeshLinks { get; set; } internal static extern bool showProximityGrid { get; set; } internal static extern bool showHeightMeshBVTree { get; set; } internal static extern bool showHeightMaps { get; set; } internal static extern bool showAgentPath { get; set; } internal static extern bool showAgentPathInfo { get; set; } internal static extern bool showAgentNeighbours { get; set; } internal static extern bool showAgentWalls { get; set; } internal static extern bool showAgentAvoidance { get; set; } internal static extern bool showObstacleCarveHull { get; set; } internal static extern void ResetHeightMeshColor(); internal static extern void ResetSelectedSurfacesOpacity(); internal static extern void ResetUnselectedSurfacesOpacity(); } [NativeHeader("Modules/AIEditor/Visualization/NavMeshVisualizationSettings.bindings.h")] [StaticAccessor("NavMeshVisualizationSettingsScriptBindings", StaticAccessorType.DoubleColon)] public static partial class NavMeshEditorHelpers { [UnityEngine.Internal.ExcludeFromDocs] public static void DrawBuildDebug(NavMeshData navMeshData) { DrawBuildDebug(navMeshData, NavMeshBuildDebugFlags.All); } public static extern void DrawBuildDebug(NavMeshData navMeshData, [UnityEngine.Internal.DefaultValue(@"NavMeshBuildDebugFlags.All")] NavMeshBuildDebugFlags flags); [StaticAccessor("GetNavMeshManager()", StaticAccessorType.Dot)] internal static extern bool HasPendingAgentDebugInfoRequests(); [StaticAccessor("GetNavMeshManager()", StaticAccessorType.Dot)] internal static extern void GetAgentsDebugInfoRejectedRequestsCount(out int rejected, out int allowed); internal static event Action<int, int> agentRejectedDebugInfoRequestsCountChanged; internal static event Action agentDebugRequestsPending; internal static event Action agentDebugRequestsProcessed; [RequiredByNativeCode] private static void OnAgentRejectedDebugInfoRequestsCountChanged(int rejected, int allowed) { if (agentRejectedDebugInfoRequestsCountChanged != null) agentRejectedDebugInfoRequestsCountChanged(rejected, allowed); } [RequiredByNativeCode] private static void OnAgentDebugInfoRequestsPending() { if (agentDebugRequestsPending != null) agentDebugRequestsPending(); } [RequiredByNativeCode] private static void OnAgentDebugInfoRequestsProcessed() { if (agentDebugRequestsProcessed != null) agentDebugRequestsProcessed(); } internal static void SetupLegacyNavigationWindow() { } } }
UnityCsReference/Modules/AIEditor/Visualization/NavMeshVisualizationSettings.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/AIEditor/Visualization/NavMeshVisualizationSettings.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1431 }
352
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; namespace UnityEngine.Accessibility { internal class ServiceManager { // All of the services that are currently created, but not necessarily active. readonly IDictionary<Type, IService> m_Services; public ServiceManager() { m_Services = new Dictionary<Type, IService>(); AccessibilityManager.screenReaderStatusChanged += ScreenReaderStatusChanged; // In the Editor context, we always initialize services in order to allow users to build, // activate and debug (using the Accessibility Hierarchy Viewer for instance) their Accessibility hierarchies in play mode // even if Screen Reader is off and the Accessibility backend is not supported. UpdateServices(true); } public T GetService<T>() where T : IService { var serviceType = typeof(T); m_Services.TryGetValue(serviceType, out var service); return (T)service; } void StartService<T>() where T : IService { var service = GetService<T>(); // If the service doesn't exist yet or isn't running, create a new instance and start it if (service == null) { var serviceType = typeof(T); service = (T)Activator.CreateInstance(serviceType); service.Start(); m_Services.Add(serviceType, service); } } void StopService<T>() where T : IService { var service = GetService<T>(); // Only stop the service if it exists and is already running, then remove references to it if (service != null) { service.Stop(); m_Services.Remove(typeof(T)); } } void UpdateServices(bool isScreenReaderEnabled) { if (isScreenReaderEnabled) { if (!m_Services.ContainsKey(typeof(AccessibilityHierarchyService))) { var service = new AccessibilityHierarchyService(); service.Start(); m_Services.Add(typeof(AccessibilityHierarchyService), service); } } else { StopService<AccessibilityHierarchyService>(); } } protected void ScreenReaderStatusChanged(bool isScreenReaderEnabled) { UpdateServices(isScreenReaderEnabled); } } }
UnityCsReference/Modules/Accessibility/Managed/Services/ServiceManager.cs/0
{ "file_path": "UnityCsReference/Modules/Accessibility/Managed/Services/ServiceManager.cs", "repo_id": "UnityCsReference", "token_count": 1222 }
353
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; namespace UnityEngine.Android { /// <summary> /// <seealso href="https://developer.android.com/reference/android/app/GameManager">developer.android.com</seealso> /// </summary> public enum AndroidGameMode { /// <summary> /// <para>Game mode is not supported for this application.</para> /// <seealso href="https://developer.android.com/reference/android/app/GameManager#GAME_MODE_UNSUPPORTED">developer.android.com</seealso> /// </summary> Unsupported = 0x00000000, /// <summary> /// <para>Standard game mode means the platform will use the game's default performance characteristics.</para> /// <seealso href="https://developer.android.com/reference/android/app/GameManager#GAME_MODE_STANDARD">developer.android.com</seealso> /// </summary> Standard = 0x00000001, /// <summary> /// <para>Performance game mode maximizes the game's performance.</para> /// <seealso href="https://developer.android.com/reference/android/app/GameManager#GAME_MODE_PERFORMANCE">developer.android.com</seealso> /// </summary> Performance = 0x00000002, /// <summary> /// <para>Battery game mode will save battery and give longer game play time.</para> /// <seealso href="https://developer.android.com/reference/android/app/GameManager#GAME_MODE_BATTERY">developer.android.com</seealso> /// </summary> Battery = 0x00000003 } public static class AndroidGame { private static AndroidJavaObject m_UnityGameManager; private static AndroidJavaObject m_UnityGameState; private static AndroidJavaObject GetUnityGameManager() { if (m_UnityGameManager != null) { return m_UnityGameManager; } m_UnityGameManager = new AndroidJavaClass("com.unity3d.player.UnityGameManager"); return m_UnityGameManager; } private static AndroidJavaObject GetUnityGameState() { if (m_UnityGameState != null) { return m_UnityGameState; } m_UnityGameState = new AndroidJavaClass("com.unity3d.player.UnityGameState"); return m_UnityGameState; } /// <summary> /// <para>Get the user selected game mode for the application.</para> /// <seealso href="https://developer.android.com/reference/android/app/GameManager#getGameMode()">developer.android.com</seealso> /// </summary> /// <returns>User selected <see cref="Android.GameMode"/></returns> public static AndroidGameMode GameMode { get { return AndroidGameMode.Unsupported; } } /// <summary> /// <para>Create a GameState with the specified loading status.</para> /// <seealso href="https://developer.android.com/reference/android/app/GameState#GameState(boolean,%20int)">developer.android.com</seealso> /// </summary> /// <param name="isLoading">Whether the game is in the loading state.</param> /// <param name="gameState">The game state of type <see cref="AndroidGameState"/></param> public static void SetGameState(bool isLoading, AndroidGameState gameState) { } /// <summary> /// <para>Create a GameState with the given state variables.</para> /// <seealso href="https://developer.android.com/reference/android/app/GameState#GameState(boolean,%20int,%20int,%20int)">developer.android.com</seealso> /// </summary> /// <param name="isLoading">Whether the game is in the loading state.</param> /// <param name="gameState">The game state of type <see cref="AndroidGameState"/></param> /// <param name="label">An developer-supplied value e.g. for the current level.</param> /// <param name="quality">An developer-supplied value, e.g. for the current quality level.</param> public static void SetGameState(bool isLoading, AndroidGameState gameState, int label, int quality) { } } }
UnityCsReference/Modules/AndroidJNI/AndroidGame.cs/0
{ "file_path": "UnityCsReference/Modules/AndroidJNI/AndroidGame.cs", "repo_id": "UnityCsReference", "token_count": 1714 }
354
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEngine.Scripting; namespace UnityEngine.Animations { [RequiredByNativeCode] [AttributeUsage(AttributeTargets.Field | AttributeTargets.Class)] public class NotKeyableAttribute : Attribute { } }
UnityCsReference/Modules/Animation/Managed/NotKeyableAttribute.cs/0
{ "file_path": "UnityCsReference/Modules/Animation/Managed/NotKeyableAttribute.cs", "repo_id": "UnityCsReference", "token_count": 131 }
355
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine.Bindings; using UnityEngine.Scripting; using UnityEngine.Playables; using UnityObject = UnityEngine.Object; namespace UnityEngine.Animations { [NativeHeader("Modules/Animation/ScriptBindings/AnimationPosePlayable.bindings.h")] [NativeHeader("Modules/Animation/Director/AnimationPosePlayable.h")] [NativeHeader("Runtime/Director/Core/HPlayable.h")] [StaticAccessor("AnimationPosePlayableBindings", StaticAccessorType.DoubleColon)] [RequiredByNativeCode] internal struct AnimationPosePlayable : IPlayable, IEquatable<AnimationPosePlayable> { PlayableHandle m_Handle; static readonly AnimationPosePlayable m_NullPlayable = new AnimationPosePlayable(PlayableHandle.Null); public static AnimationPosePlayable Null { get { return m_NullPlayable; } } public static AnimationPosePlayable Create(PlayableGraph graph) { var handle = CreateHandle(graph); return new AnimationPosePlayable(handle); } private static PlayableHandle CreateHandle(PlayableGraph graph) { PlayableHandle handle = PlayableHandle.Null; if (!CreateHandleInternal(graph, ref handle)) return PlayableHandle.Null; return handle; } internal AnimationPosePlayable(PlayableHandle handle) { if (handle.IsValid()) { if (!handle.IsPlayableOfType<AnimationPosePlayable>()) throw new InvalidCastException("Can't set handle: the playable is not an AnimationPosePlayable."); } m_Handle = handle; } public PlayableHandle GetHandle() { return m_Handle; } public static implicit operator Playable(AnimationPosePlayable playable) { return new Playable(playable.GetHandle()); } public static explicit operator AnimationPosePlayable(Playable playable) { return new AnimationPosePlayable(playable.GetHandle()); } public bool Equals(AnimationPosePlayable other) { return Equals(other.GetHandle()); } public bool GetMustReadPreviousPose() { return GetMustReadPreviousPoseInternal(ref m_Handle); } public void SetMustReadPreviousPose(bool value) { SetMustReadPreviousPoseInternal(ref m_Handle, value); } public bool GetReadDefaultPose() { return GetReadDefaultPoseInternal(ref m_Handle); } public void SetReadDefaultPose(bool value) { SetReadDefaultPoseInternal(ref m_Handle, value); } public bool GetApplyFootIK() { return GetApplyFootIKInternal(ref m_Handle); } public void SetApplyFootIK(bool value) { SetApplyFootIKInternal(ref m_Handle, value); } // Bindings methods. [NativeThrows] extern private static bool CreateHandleInternal(PlayableGraph graph, ref PlayableHandle handle); [NativeThrows] extern static private bool GetMustReadPreviousPoseInternal(ref PlayableHandle handle); [NativeThrows] extern static private void SetMustReadPreviousPoseInternal(ref PlayableHandle handle, bool value); [NativeThrows] extern static private bool GetReadDefaultPoseInternal(ref PlayableHandle handle); [NativeThrows] extern static private void SetReadDefaultPoseInternal(ref PlayableHandle handle, bool value); [NativeThrows] extern static private bool GetApplyFootIKInternal(ref PlayableHandle handle); [NativeThrows] extern static private void SetApplyFootIKInternal(ref PlayableHandle handle, bool value); } }
UnityCsReference/Modules/Animation/ScriptBindings/AnimationPosePlayable.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Animation/ScriptBindings/AnimationPosePlayable.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1604 }
356
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Diagnostics; using System.Runtime.InteropServices; using UnityEngine.Bindings; using UnityEngine.Scripting; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using Unity.Burst; namespace UnityEngine.Animations { internal enum Flags { kNone = 0, kDiscrete = 1 << 0, kPPtr = 1 << 1, kSerializeReference = 1 << 2, kPhantom = 1 << 3, kUnknown = 1 << 4 }; [NativeType(CodegenOptions.Custom, "UnityEngine::Animation::MonoGenericBinding")] [UsedByNativeCode] public readonly struct GenericBinding { public bool isObjectReference => (m_Flags & Flags.kPPtr) == Flags.kPPtr; public bool isDiscrete => (m_Flags & (Flags.kDiscrete | Flags.kPPtr)) != 0; public bool isSerializeReference => (m_Flags & Flags.kSerializeReference) == Flags.kSerializeReference; public uint transformPathHash => m_Path; public uint propertyNameHash => m_PropertyName; public int scriptInstanceID => m_ScriptInstanceID; public int typeID => m_TypeID; public byte customTypeID => m_CustomType; readonly uint m_Path; readonly uint m_PropertyName; readonly int m_ScriptInstanceID; readonly int m_TypeID; readonly byte m_CustomType; internal readonly Flags m_Flags; } [NativeHeader("Modules/Animation/ScriptBindings/GenericBinding.bindings.h")] [StaticAccessor("UnityEngine::Animation::GenericBindingUtility", StaticAccessorType.DoubleColon)] public static partial class GenericBindingUtility { public static bool CreateGenericBinding(UnityEngine.Object targetObject, string property, GameObject root, bool isObjectReference, out GenericBinding genericBinding) { if (targetObject == null) throw new ArgumentNullException(nameof(targetObject)); if (typeof(Transform).IsAssignableFrom(targetObject.GetType())) throw new ArgumentException($"Unsupported type for {nameof(targetObject)}. Cannot create a generic binding from a Transform component."); if (targetObject is Component component) { return CreateGenericBindingForComponent(component, property, root, isObjectReference, out genericBinding); } else if (targetObject is GameObject gameObject) { return CreateGenericBindingForGameObject(gameObject, property, root, out genericBinding); } throw new ArgumentException($"Type {targetObject.GetType()} for {nameof(targetObject)} is unsupported. Expecting either a GameObject or a Component"); } [NativeMethod(IsThreadSafe = false)] extern private static bool CreateGenericBindingForGameObject([NotNull] GameObject gameObject, string property, [NotNull] GameObject root, out GenericBinding genericBinding); [NativeMethod(IsThreadSafe = false)] extern private static bool CreateGenericBindingForComponent([NotNull] Component component, string property, [NotNull] GameObject root, bool isObjectReference, out GenericBinding genericBinding); // Discover bindings [NativeMethod(IsThreadSafe = false)] extern public static GenericBinding[] GetAnimatableBindings([NotNull] GameObject targetObject, [NotNull] GameObject root); [NativeMethod(IsThreadSafe = false)] extern public static GenericBinding[] GetCurveBindings([NotNull] AnimationClip clip); // Bind animatable properties public static unsafe void BindProperties(GameObject rootGameObject, NativeArray<GenericBinding> genericBindings, out NativeArray<BoundProperty> floatProperties, out NativeArray<BoundProperty> discreteProperties, Allocator allocator) { const int transformTypeID = 4; ValidateIsCreated(genericBindings); int floatPropertyCount = 0; int discretePropertiesCount = 0; for (int i = 0; i < genericBindings.Length; i++) { // Transform bindings is not supported if (genericBindings[i].typeID == transformTypeID) continue; if (genericBindings[i].isDiscrete || genericBindings[i].isObjectReference) discretePropertiesCount++; else floatPropertyCount++; } floatProperties = new NativeArray<BoundProperty>(floatPropertyCount, allocator); discreteProperties = new NativeArray<BoundProperty>(discretePropertiesCount, allocator); void* genericBidingsPtr = genericBindings.GetUnsafePtr(); void* floatPropertiesPtr = NativeArrayUnsafeUtility.GetUnsafePtr(floatProperties); void* discretePropertiesPtr = NativeArrayUnsafeUtility.GetUnsafePtr(discreteProperties); Internal_BindProperties(rootGameObject, genericBidingsPtr, genericBindings.Length, floatPropertiesPtr, discretePropertiesPtr); } [NativeMethod(IsThreadSafe = false)] extern internal static unsafe void Internal_BindProperties([NotNull] GameObject gameObject, void* genericBindings, int genericBindingsCount, void* floatProperties, void* discreteProperties); // Bind animatable properties public static unsafe void UnbindProperties(NativeArray<BoundProperty> boundProperties) { ValidateIsCreated(boundProperties); void* boundPropertiesPtr = NativeArrayUnsafeUtility.GetUnsafePtr(boundProperties); Internal_UnbindProperties(boundPropertiesPtr, boundProperties.Length); } [NativeMethod(IsThreadSafe = false)] extern internal static unsafe void Internal_UnbindProperties(void* boundProperties, int boundPropertiesCount); // Read/Write to/from animatable properties // Not thread safe public static unsafe void SetValues(NativeArray<BoundProperty> boundProperties, NativeArray<float> values) { ValidateIsCreated(boundProperties); ValidateIsCreated(values); ValidateLengthMatch(boundProperties, values); void* boundPropertiesPtr = NativeArrayUnsafeUtility.GetUnsafePtr(boundProperties); void* valuesPtr = NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(values); SetFloatValues(boundPropertiesPtr, boundProperties.Length, valuesPtr, values.Length); } public static unsafe void SetValues(NativeArray<BoundProperty> boundProperties, NativeArray<int> indices, NativeArray<float> values) { ValidateIsCreated(boundProperties); ValidateIsCreated(indices); ValidateIsCreated(values); ValidateLengthMatch(boundProperties, indices); ValidateIndicesAreInRange(indices, values.Length); void* boundPropertiesPtr = NativeArrayUnsafeUtility.GetUnsafePtr(boundProperties); void* indicesPtr = NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(indices); void* valuesPtr = NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(values); SetScatterFloatValues(boundPropertiesPtr, boundProperties.Length, indicesPtr, indices.Length, valuesPtr, values.Length); } public static unsafe void SetValues(NativeArray<BoundProperty> boundProperties, NativeArray<int> values) { ValidateIsCreated(boundProperties); ValidateIsCreated(values); ValidateLengthMatch(boundProperties, values); void* boundPropertiesPtr = NativeArrayUnsafeUtility.GetUnsafePtr(boundProperties); void* valuesPtr = NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(values); SetDiscreteValues(boundPropertiesPtr, boundProperties.Length, valuesPtr, values.Length); } public static unsafe void SetValues(NativeArray<BoundProperty> boundProperties, NativeArray<int> indices, NativeArray<int> values) { ValidateIsCreated(boundProperties); ValidateIsCreated(indices); ValidateIsCreated(values); ValidateLengthMatch(boundProperties, indices); ValidateIndicesAreInRange(indices, values.Length); void* boundPropertiesPtr = NativeArrayUnsafeUtility.GetUnsafePtr(boundProperties); void* indicesPtr = NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(indices); void* valuesPtr = NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(values); SetScatterDiscreteValues(boundPropertiesPtr, boundProperties.Length, indicesPtr, indices.Length, valuesPtr, values.Length); } public static unsafe void GetValues(NativeArray<BoundProperty> boundProperties, NativeArray<float> values) { ValidateIsCreated(boundProperties); ValidateIsCreated(values); ValidateLengthMatch(boundProperties, values); void* boundPropertiesPtr = NativeArrayUnsafeUtility.GetUnsafePtr(boundProperties); void* valuesPtr = NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(values); GetFloatValues(boundPropertiesPtr, boundProperties.Length, valuesPtr, values.Length); } public static unsafe void GetValues(NativeArray<BoundProperty> boundProperties, NativeArray<int> indices, NativeArray<float> values) { ValidateIsCreated(boundProperties); ValidateIsCreated(indices); ValidateIsCreated(values); ValidateLengthMatch(boundProperties, indices); ValidateIndicesAreInRange(indices, values.Length); void* boundPropertiesPtr = NativeArrayUnsafeUtility.GetUnsafePtr(boundProperties); void* indicesPtr = NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(indices); void* valuesPtr = NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(values); GetScatterFloatValues(boundPropertiesPtr, boundProperties.Length, indicesPtr, indices.Length, valuesPtr, values.Length); } public static unsafe void GetValues(NativeArray<BoundProperty> boundProperties, NativeArray<int> values) { ValidateIsCreated(boundProperties); ValidateIsCreated(values); ValidateLengthMatch(boundProperties, values); void* boundPropertiesPtr = NativeArrayUnsafeUtility.GetUnsafePtr(boundProperties); void* valuesPtr = NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(values); GetDiscreteValues(boundPropertiesPtr, boundProperties.Length, valuesPtr, values.Length); } public static unsafe void GetValues(NativeArray<BoundProperty> boundProperties, NativeArray<int> indices, NativeArray<int> values) { ValidateIsCreated(boundProperties); ValidateIsCreated(indices); ValidateIsCreated(values); ValidateLengthMatch(boundProperties, indices); ValidateIndicesAreInRange(indices, values.Length); void* boundPropertiesPtr = NativeArrayUnsafeUtility.GetUnsafePtr(boundProperties); void* indicesPtr = NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(indices); void* valuesPtr = NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(values); GetScatterDiscreteValues(boundPropertiesPtr, boundProperties.Length, indicesPtr, indices.Length, valuesPtr, values.Length); } [NativeMethod(IsThreadSafe = false)] extern internal static unsafe void SetFloatValues(void* boundProperties, int boundPropertiesCount, void* values, int valuesCount); [NativeMethod(IsThreadSafe = false)] extern internal static unsafe void SetScatterFloatValues(void* boundProperties, int boundPropertiesCount, void* indices, int indicesCount, void* values, int valuesCount); [NativeMethod(IsThreadSafe = false)] extern internal static unsafe void SetDiscreteValues(void* boundProperties, int boundPropertiesCount, void* values, int valuesCount); [NativeMethod(IsThreadSafe = false)] extern internal static unsafe void SetScatterDiscreteValues(void* boundProperties, int boundPropertiesCount, void* indices, int indicesCount, void* values, int valuesCount); [NativeMethod(IsThreadSafe = false)] extern internal static unsafe void GetFloatValues(void* boundProperties, int boundPropertiesCount, void* values, int valuesCount); [NativeMethod(IsThreadSafe = false)] extern internal static unsafe void GetScatterFloatValues(void* boundProperties, int boundPropertiesCount, void* indices, int indicesCount, void* values, int valuesCount); [NativeMethod(IsThreadSafe = false)] extern internal static unsafe void GetDiscreteValues(void* boundProperties, int boundPropertiesCount, void* values, int valuesCount); [NativeMethod(IsThreadSafe = false)] extern internal static unsafe void GetScatterDiscreteValues(void* boundProperties, int boundPropertiesCount, void* indices, int indicesCount, void* values, int valuesCount); [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] internal static void ValidateIsCreated<T>(NativeArray<T> array) where T : unmanaged { if (!array.IsCreated) throw new System.ArgumentException($"NativeArray of {typeof(T).Name} is not created."); } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] internal static void ValidateIndicesAreInRange(NativeArray<int> indices, int maxValue) { for(int i = 0; i < indices.Length; i++) { if(indices[i] < 0 || indices[i] >= maxValue) throw new System.IndexOutOfRangeException($"NativeArray of indices contain element out of range at index '{i}': value '{indices[i]}' is not in the range 0 to {maxValue}."); } } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] internal static void ValidateLengthMatch<T1, T2>(NativeArray<T1> array1, NativeArray<T2> array2) where T1 : unmanaged where T2 : unmanaged { if (array1.Length != array2.Length ) throw new System.ArgumentException($"Length must be equals for NativeArray<{typeof(T1).Name}> and NativeArray<{typeof(T2).Name}>."); } } }
UnityCsReference/Modules/Animation/ScriptBindings/GenericBinding.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Animation/ScriptBindings/GenericBinding.bindings.cs", "repo_id": "UnityCsReference", "token_count": 5431 }
357
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using UnityEngine.Bindings; using UnityEngine.Scripting; using UnityEngineInternal; namespace UnityEngine { [StructLayout(LayoutKind.Sequential)] [RequiredByNativeCode] [NativeHeader("Modules/AssetBundle/Public/AssetBundleUnloadOperation.h")] public class AssetBundleUnloadOperation : AsyncOperation { [NativeMethod("WaitForCompletion")] public extern void WaitForCompletion(); public AssetBundleUnloadOperation() { } private AssetBundleUnloadOperation(IntPtr ptr) : base(ptr) { } new internal static class BindingsMarshaller { public static AssetBundleUnloadOperation ConvertToManaged(IntPtr ptr) => new AssetBundleUnloadOperation(ptr); public static IntPtr ConvertToNative(AssetBundleUnloadOperation assetBundleUnloadOperation) => assetBundleUnloadOperation.m_Ptr; } } }
UnityCsReference/Modules/AssetBundle/Managed/AssetBundleUnloadOperation.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/AssetBundle/Managed/AssetBundleUnloadOperation.bindings.cs", "repo_id": "UnityCsReference", "token_count": 398 }
358
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.IO; using UnityEditor.AssetImporters; using UnityEngine; using UnityEngine.Scripting.APIUpdating; namespace UnityEditor.AssetImporters { [MovedFrom("UnityEditor.Experimental.AssetImporters")] public class SketchupMaterialDescriptionPreprocessor : AssetPostprocessor { static readonly uint k_Version = 2; static readonly int k_Order = -990; public override uint GetVersion() { return k_Version; } public override int GetPostprocessOrder() { return k_Order; } public void OnPreprocessMaterialDescription(MaterialDescription description, Material material, AnimationClip[] clips) { var lowerCasePath = Path.GetExtension(assetPath).ToLower(); if (lowerCasePath == ".skp") CreateFromSketchupMaterial(description, material, clips); } void CreateFromSketchupMaterial(MaterialDescription description, Material material, AnimationClip[] clips) { var shader = Shader.Find("Standard"); if (shader == null) { context.LogImportError("SketchupMaterialDescriptionPreprocessor cannot find a shader named 'Standard'."); return; } material.shader = shader; float floatProperty; Vector4 vectorProperty; TexturePropertyDescription textureProperty; if (description.TryGetProperty("DiffuseColor", out vectorProperty)) { if (QualitySettings.activeColorSpace == ColorSpace.Gamma) { vectorProperty.x = Mathf.LinearToGammaSpace(vectorProperty.x); vectorProperty.y = Mathf.LinearToGammaSpace(vectorProperty.y); vectorProperty.z = Mathf.LinearToGammaSpace(vectorProperty.z); } material.SetColor("_Color", vectorProperty); } if (description.TryGetProperty("DiffuseMap", out textureProperty)) { SetMaterialTextureProperty("_MainTex", material, textureProperty); material.SetColor("_Color", new Color(1.0f, 1.0f, 1.0f, 1.0f)); } if (description.TryGetProperty("IsTransparent", out floatProperty) && floatProperty == 1.0f) { material.SetFloat("_Mode", (float)StandardShaderGUI.BlendMode.Transparent); material.SetOverrideTag("RenderType", "Transparent"); material.SetFloat("_SrcBlend", (float)UnityEngine.Rendering.BlendMode.One); material.SetFloat("_DstBlend", (float)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetFloat("_ZWrite", 0.0f); material.EnableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent; } else { material.SetFloat("_Mode", (float)StandardShaderGUI.BlendMode.Opaque); material.SetOverrideTag("RenderType", ""); material.SetFloat("_SrcBlend", (float)UnityEngine.Rendering.BlendMode.One); material.SetFloat("_DstBlend", (float)UnityEngine.Rendering.BlendMode.Zero); material.SetFloat("_ZWrite", 1.0f); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = -1; } } static void SetMaterialTextureProperty(string propertyName, Material material, TexturePropertyDescription textureProperty) { material.SetTexture(propertyName, textureProperty.texture); material.SetTextureOffset(propertyName, textureProperty.offset); material.SetTextureScale(propertyName, textureProperty.scale); } } }
UnityCsReference/Modules/AssetPipelineEditor/AssetPostprocessors/SketchupMaterialDescriptionPreprocessor.cs/0
{ "file_path": "UnityCsReference/Modules/AssetPipelineEditor/AssetPostprocessors/SketchupMaterialDescriptionPreprocessor.cs", "repo_id": "UnityCsReference", "token_count": 1830 }
359
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor.Build; using UnityEngine; using UnityEngine.Bindings; namespace UnityEditor { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.Obsolete("UnityEditor.AudioImporterFormat has been deprecated. Use UnityEngine.AudioCompressionFormat instead.")] public enum AudioImporterFormat { Native = -1, Compressed = 0 } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.Obsolete("UnityEditor.AudioImporterLoadType has been deprecated. Use UnityEngine.AudioClipLoadType instead (UnityUpgradable) -> [UnityEngine] UnityEngine.AudioClipLoadType", true)] public enum AudioImporterLoadType { DecompressOnLoad = -1, CompressedInMemory = -1, [System.Obsolete("UnityEditor.AudioImporterLoadType.StreamFromDisc has been deprecated. Use UnityEngine.AudioClipLoadType.Streaming instead (UnityUpgradable) -> UnityEngine.AudioClipLoadType.Streaming", true)] StreamFromDisc = -1 } [System.Obsolete("Setting and getting import channels is not used anymore (use forceToMono instead)", true)] public enum AudioImporterChannels { Automatic = 0, Mono = 1, Stereo = 2, } public enum AudioSampleRateSetting { PreserveSampleRate = 0, OptimizeSampleRate = 1, OverrideSampleRate = 2 } [System.Serializable] public partial struct AudioImporterSampleSettings { public AudioClipLoadType loadType; public AudioSampleRateSetting sampleRateSetting; public uint sampleRateOverride; public AudioCompressionFormat compressionFormat; public float quality; public int conversionMode; public bool preloadAudioData; } [NativeHeader("Modules/AssetPipelineEditor/Public/AudioImporter.h")] // Audio importer lets you modify [[AudioClip]] import settings from editor scripts. public sealed partial class AudioImporter : AssetImporter { public extern AudioImporterSampleSettings defaultSampleSettings { get; set; } public bool ContainsSampleSettingsOverride(string platform) { return ValidatePlatform(ref platform, "AudioImporter.ContainsSampleSettingsOverride") ? Internal_ContainsSampleSettingsOverride(platform) : false; } public bool ContainsSampleSettingsOverride(BuildTargetGroup platformGroup) { return ValidatePlatform(platformGroup, "AudioImporter.ContainsSampleSettingsOverride", out string platformName) ? Internal_ContainsSampleSettingsOverride(platformName) : false; } [NativeName("ContainsSampleSettingsOverride")] internal extern bool Internal_ContainsSampleSettingsOverride(string platform); public AudioImporterSampleSettings GetOverrideSampleSettings(string platform) { return ValidatePlatform(ref platform, "AudioImporter.GetOverrideSampleSettings") ? Internal_GetOverrideSampleSettings(platform) : defaultSampleSettings; } public AudioImporterSampleSettings GetOverrideSampleSettings(BuildTargetGroup platformGroup) { return ValidatePlatform(platformGroup, "AudioImporter.GetOverrideSampleSettings", out string platformName) ? Internal_GetOverrideSampleSettings(platformName) : defaultSampleSettings; } [NativeName("GetTranslatedSettingsForPlatform")] internal extern AudioImporterSampleSettings Internal_GetOverrideSampleSettings(string platform); public bool SetOverrideSampleSettings(string platform, AudioImporterSampleSettings settings) { return ValidatePlatform(ref platform, "AudioImporter.SetOverrideSampleSettings") ? Internal_SetOverrideSampleSettings(platform, settings) : false; } public bool SetOverrideSampleSettings(BuildTargetGroup platformGroup, AudioImporterSampleSettings settings) { return ValidatePlatform(platformGroup, "AudioImporter.SetOverrideSampleSettings", out string platformName) ? Internal_SetOverrideSampleSettings(platformName, settings) : false; } [NativeName("SetSampleSettingsForPlatform")] internal extern bool Internal_SetOverrideSampleSettings(string platform, AudioImporterSampleSettings settings); public bool ClearSampleSettingOverride(string platform) { return ValidatePlatform(ref platform, "AudioImporter.ClearSampleSettingOverride") ? Internal_ClearSampleSettingOverride(platform) : false; } public bool ClearSampleSettingOverride(BuildTargetGroup platformGroup) { return ValidatePlatform(platformGroup, "AudioImporter.ClearSampleSettingOverride", out string platformName) ? Internal_ClearSampleSettingOverride(platformName) : false; } private static bool ValidatePlatform(ref string platformName, string methodName) { return ValidatePlatform(BuildPipeline.GetBuildTargetGroupByName(platformName), methodName, out platformName); } private static bool ValidatePlatform(BuildTargetGroup platformGroup, string methodName, out string platformName) { if (platformGroup != BuildTargetGroup.Unknown) { platformName = BuildPipeline.GetBuildTargetGroupName(platformGroup); return true; } platformName = null; Debug.LogErrorFormat("Unknown platform passed to {0} ({1})", methodName, platformGroup); return false; } [NativeName("ClearSampleSettingOverride")] internal extern bool Internal_ClearSampleSettingOverride(string platformGroup); // Force this clip to mono? public extern bool forceToMono { get; set; } // Is this clip ambisonic? public extern bool ambisonic { get; set; } //Set/get the way Unity is loading the Audio data. public extern bool loadInBackground { get; set; } [System.Obsolete("Preload audio data has been moved to AudioImporter.SampleSettings as a per platform local setting", true)] public extern bool preloadAudioData { get; set; } [System.Obsolete("Setting and getting the compression format is not used anymore (use compressionFormat in defaultSampleSettings instead). Source audio file is assumed to be PCM Wav.")] AudioImporterFormat format { get { return (defaultSampleSettings.compressionFormat == AudioCompressionFormat.PCM) ? AudioImporterFormat.Native : AudioImporterFormat.Compressed; } set { AudioImporterSampleSettings settings = defaultSampleSettings; settings.compressionFormat = (value == AudioImporterFormat.Native) ? AudioCompressionFormat.PCM : AudioCompressionFormat.Vorbis; defaultSampleSettings = settings; } } [System.Obsolete("Setting and getting import channels is not used anymore (use forceToMono instead)", true)] public AudioImporterChannels channels { get { return 0; } set {} } // Compression bitrate. [System.Obsolete("AudioImporter.compressionBitrate is no longer supported", true)] public int compressionBitrate { get { return 0; } set {} } [System.Obsolete("AudioImporter.loopable is no longer supported. All audio assets encoded by Unity are by default loopable.")] public bool loopable { get { return true; } set {} } [System.Obsolete("AudioImporter.hardware is no longer supported. All mixing of audio is done by software and only some platforms use hardware acceleration to perform decoding.")] public bool hardware { get { return false; } set {} } // Should audio data be decompressed on load? [System.Obsolete("Setting/Getting decompressOnLoad is deprecated. Use AudioImporterSampleSettings.loadType instead.")] bool decompressOnLoad { get { return (defaultSampleSettings.loadType == AudioClipLoadType.DecompressOnLoad); } set { AudioImporterSampleSettings settings = defaultSampleSettings; settings.loadType = value ? AudioClipLoadType.DecompressOnLoad : AudioClipLoadType.CompressedInMemory; defaultSampleSettings = settings; } } [System.Obsolete("AudioImporter.quality is no longer supported. Use AudioImporterSampleSettings.")] float quality { get { return defaultSampleSettings.quality; } set { AudioImporterSampleSettings settings = defaultSampleSettings; settings.quality = value; defaultSampleSettings = settings; } } // Is this clip a 2D or 3D sound? [System.Obsolete("AudioImporter.threeD is no longer supported")] public bool threeD { get { return true; } set {} } //*undocumented* Update/cache audio info. important to call this before any of the next. you only need to call it once per audiofile [System.Obsolete("AudioImporter.updateOrigData is deprecated.", true)] internal void updateOrigData() {} //*undocumented* Duration of imported audio. call updateOrigData before [System.Obsolete("AudioImporter.durationMS is deprecated.", true)] internal int durationMS { get { return 0; } } // Frequency (sample rate) of imported audio. call updateOrigData before [System.Obsolete("AudioImporter.frequency is deprecated.", true)] internal int frequency { get { return 0; } } // Original channel count. call updateOrigData before [System.Obsolete("AudioImporter.origChannelCount is deprecated.", true)] internal int origChannelCount { get { return 0; } } // Is original source compressible to Ogg/MP3 (depending on platform)? call updateOrigData before [System.Obsolete("AudioImporter.origIsCompressible is deprecated.", true)] internal bool origIsCompressible { get { return false; } } // Is original source forcable(?) to mono? call updateOrigData before [System.Obsolete("AudioImporter.origIsMonoForcable is deprecated.", true)] internal bool origIsMonoForcable { get { return false; } } //*undocumented* Min bitrate for ogg/mp3 compression. call updateOrigData before [System.Obsolete("AudioImporter.minBitrate is deprecated.", true)] internal int minBitrate(AudioType type) { return 0; } //*undocumented* Max bitrate for ogg/mp3 compression. call updateOrigData before [System.Obsolete("AudioImporter.maxBitrate is deprecated.", true)] internal int maxBitrate(AudioType type) { return 0; } [System.Obsolete("AudioImporter.defaultBitrate is deprecated.", true)] internal int defaultBitrate { get { return 0; } } //*undocumented* Get the format for automatic format [System.Obsolete("AudioImporter.origType is deprecated.", true)] internal AudioType origType { get { return 0; } } //*undocumented* Return the size of the original file. Note this is slow [System.Obsolete("AudioImporter.origFileSize is deprecated.", true)] internal int origFileSize { get { return 0; } } [NativeProperty("GetPreviewData().m_OrigSize", TargetType.Field)] internal extern int origSize { get; } [NativeProperty("GetPreviewData().m_CompSize", TargetType.Field)] internal extern int compSize { get; } } }
UnityCsReference/Modules/AssetPipelineEditor/Public/AudioImporter.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/AssetPipelineEditor/Public/AudioImporter.bindings.cs", "repo_id": "UnityCsReference", "token_count": 4578 }
360
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using UnityEngine.Audio; using UnityEngine.Bindings; using UnityEngine.Internal; using UnityEngine.Playables; using RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute; [assembly: InternalsVisibleTo("Unity.AudioMixer.Tests")] namespace UnityEngine.Audio { [NativeHeader("Modules/Audio/Public/AudioResource.h")] public abstract class AudioResource : Object { protected internal AudioResource() {} } [NativeHeader("Modules/Audio/Public/ScriptBindings/Audio.bindings.h")] sealed class AudioManagerTestProxy { [NativeMethod(Name = "AudioManagerTestProxy::ComputeAudibilityConsistency", IsFreeFunction = true)] internal static extern bool ComputeAudibilityConsistency(); } } namespace UnityEngine { // These are speaker types defined for use with [[AudioSettings.speakerMode]]. public enum AudioSpeakerMode { // Channel count is unaffected. [Obsolete("Raw speaker mode is not supported. Do not use.", true)] Raw = 0, // Channel count is set to 1. The speakers are monaural. Mono = 1, // Channel count is set to 2. The speakers are stereo. This is the editor default. Stereo = 2, // Channel count is set to 4. 4 speaker setup. This includes front left, front right, rear left, rear right. Quad = 3, // Channel count is set to 5. 5 speaker setup. This includes front left, front right, center, rear left, rear right. Surround = 4, // Channel count is set to 6. 5.1 speaker setup. This includes front left, front right, center, rear left, rear right and a subwoofer. Mode5point1 = 5, // Channel count is set to 8. 7.1 speaker setup. This includes front left, front right, center, rear left, rear right, side left, side right and a subwoofer. Mode7point1 = 6, // Channel count is set to 2. Stereo output, but data is encoded in a way that is picked up by a Prologic/Prologic2 decoder and split into a 5.1 speaker setup. Prologic = 7 } public enum AudioDataLoadState { Unloaded = 0, Loading = 1, Loaded = 2, Failed = 3 } public struct AudioConfiguration { public AudioSpeakerMode speakerMode; public int dspBufferSize; public int sampleRate; public int numRealVoices; public int numVirtualVoices; } // Imported audio format for [[AudioImporter]]. public enum AudioCompressionFormat { PCM = 0, Vorbis = 1, ADPCM = 2, MP3 = 3, VAG = 4, HEVAG = 5, XMA = 6, AAC = 7, GCADPCM = 8, ATRAC9 = 9 } // The way we load audio assets [[AudioImporter]]. public enum AudioClipLoadType { DecompressOnLoad = 0, CompressedInMemory = 1, Streaming = 2 } // Describes when an [[AudioSource]] or [[AudioListener]] is updated. public enum AudioVelocityUpdateMode { // Updates the source or listener in the fixed update loop if it is attached to a [[Rigidbody]], dynamic otherwise. Auto = 0, // Updates the source or listener in the fixed update loop. Fixed = 1, // Updates the source or listener in the dynamic update loop. Dynamic = 2 } // Spectrum analysis windowing types public enum FFTWindow { // w[n] = 1.0 Rectangular = 0, // w[n] = TRI(2n/N) Triangle = 1, // w[n] = 0.54 - (0.46 * COS(n/N) ) Hamming = 2, // w[n] = 0.5 * (1.0 - COS(n/N) ) Hanning = 3, // w[n] = 0.42 - (0.5 * COS(n/N) ) + (0.08 * COS(2.0 * n/N) ) Blackman = 4, // w[n] = 0.35875 - (0.48829 * COS(1.0 * n/N)) + (0.14128 * COS(2.0 * n/N)) - (0.01168 * COS(3.0 * n/N)) BlackmanHarris = 5 } // Rolloff modes that a 3D sound can have in an audio source. public enum AudioRolloffMode { // Use this mode when you want a real-world rolloff. Logarithmic = 0, // Use this mode when you want to lower the volume of your sound over the distance Linear = 1, // Use this when you want to use a custom rolloff. Custom = 2 } public enum AudioSourceCurveType { CustomRolloff = 0, SpatialBlend = 1, ReverbZoneMix = 2, Spread = 3 } public enum GamepadSpeakerOutputType { Speaker = 0, Vibration = 1, SecondaryVibration = 2 } // Reverb presets used by the Reverb Zone class and the audio reverb filter public enum AudioReverbPreset { // No reverb preset selected Off = 0, // Generic preset. Generic = 1, // Padded cell preset. PaddedCell = 2, // Room preset. Room = 3, // Bathroom preset. Bathroom = 4, // Livingroom preset Livingroom = 5, // Stoneroom preset Stoneroom = 6, // Auditorium preset. Auditorium = 7, // Concert hall preset. Concerthall = 8, // Cave preset. Cave = 9, // Arena preset. Arena = 10, // Hangar preset. Hangar = 11, // Carpeted hallway preset. CarpetedHallway = 12, // Hallway preset. Hallway = 13, // Stone corridor preset. StoneCorridor = 14, // Alley preset. Alley = 15, // Forest preset. Forest = 16, // City preset. City = 17, // Mountains preset. Mountains = 18, // Quarry preset. Quarry = 19, // Plain preset. Plain = 20, // Parking Lot preset ParkingLot = 21, // Sewer pipe preset. SewerPipe = 22, // Underwater presset Underwater = 23, // Drugged preset Drugged = 24, // Dizzy preset. Dizzy = 25, // Psychotic preset. Psychotic = 26, // User defined preset. User = 27 } internal struct PlayableSettings { public AudioContainerElement element { get; } public double scheduledTime { get; } public float pitchOffset { get; } public float volumeOffset { get; } public double triggerTimeOffset { get; } } internal struct ActivePlayable { public PlayableSettings settings { get; } public PlayableHandle clipPlayableHandle { get; } } // Controls the global audio settings from script. [NativeHeader("Modules/Audio/Public/ScriptBindings/Audio.bindings.h")] [StaticAccessor("GetAudioManager()", StaticAccessorType.Dot)] public sealed partial class AudioSettings { extern static private AudioSpeakerMode GetSpeakerMode(); [NativeThrows, NativeMethod(Name = "AudioSettings::SetConfiguration", IsFreeFunction = true)] extern static private bool SetConfiguration(AudioConfiguration config); [NativeMethod(Name = "AudioSettings::GetSampleRate", IsFreeFunction = true)] extern static private int GetSampleRate(); extern static private bool SetSpatializerName(string pluginName); // Returns the speaker mode capability of the current audio driver. Read only. extern static public AudioSpeakerMode driverCapabilities { [NativeName("GetSpeakerModeCaps")] get; } // Gets the current speaker mode. Default is 2 channel stereo. static public AudioSpeakerMode speakerMode { get { return GetSpeakerMode(); } set { Debug.LogWarning("Setting AudioSettings.speakerMode is deprecated and has been replaced by audio project settings and the AudioSettings.GetConfiguration/AudioSettings.Reset API."); AudioConfiguration config = GetConfiguration(); config.speakerMode = value; if (!SetConfiguration(config)) Debug.LogWarning("Setting AudioSettings.speakerMode failed"); } } extern static internal int profilerCaptureFlags { get; } // Returns the current time of the audio system. This is based on the number of samples the audio system processes and is therefore more exact than the time obtained via the Time.time property. // It is constant while Unity is paused. extern static public double dspTime { [NativeMethod(Name = "GetDSPTime", IsThreadSafe = true)] get; } // Get and set the mixer's current output rate. static public int outputSampleRate { get { return GetSampleRate(); } set { Debug.LogWarning("Setting AudioSettings.outputSampleRate is deprecated and has been replaced by audio project settings and the AudioSettings.GetConfiguration/AudioSettings.Reset API."); AudioConfiguration config = GetConfiguration(); config.sampleRate = value; if (!SetConfiguration(config)) Debug.LogWarning("Setting AudioSettings.outputSampleRate failed"); } } [NativeMethod(Name = "AudioSettings::GetDSPBufferSize", IsFreeFunction = true)] extern static public void GetDSPBufferSize(out int bufferLength, out int numBuffers); // Set the mixer's buffer size in samples. [Obsolete("AudioSettings.SetDSPBufferSize is deprecated and has been replaced by audio project settings and the AudioSettings.GetConfiguration/AudioSettings.Reset API.")] static public void SetDSPBufferSize(int bufferLength, int numBuffers) { Debug.LogWarning("AudioSettings.SetDSPBufferSize is deprecated and has been replaced by audio project settings and the AudioSettings.GetConfiguration/AudioSettings.Reset API."); AudioConfiguration config = GetConfiguration(); config.dspBufferSize = bufferLength; if (!SetConfiguration(config)) Debug.LogWarning("SetDSPBufferSize failed"); } extern static internal bool editingInPlaymode { [NativeName("IsEditingInPlaymode")] get; [NativeName("SetEditingInPlaymode")] set; } [NativeMethod(Name = "AudioSettings::GetSpatializerNames", IsFreeFunction = true)] extern static public string[] GetSpatializerPluginNames(); [NativeName("GetCurrentSpatializerDefinitionName")] extern static public string GetSpatializerPluginName(); static public void SetSpatializerPluginName(string pluginName) { if (!SetSpatializerName(pluginName)) throw new ArgumentException("Invalid spatializer plugin name"); } extern static public AudioConfiguration GetConfiguration(); static public bool Reset(AudioConfiguration config) { return SetConfiguration(config); } public delegate void AudioConfigurationChangeHandler(bool deviceWasChanged); static public event AudioConfigurationChangeHandler OnAudioConfigurationChanged; internal static event Action OnAudioSystemShuttingDown; internal static event Action OnAudioSystemStartedUp; [RequiredByNativeCode] static internal void InvokeOnAudioConfigurationChanged(bool deviceWasChanged) { if (OnAudioConfigurationChanged != null) OnAudioConfigurationChanged(deviceWasChanged); } [RequiredByNativeCode] internal static void InvokeOnAudioSystemShuttingDown() => OnAudioSystemShuttingDown?.Invoke(); [RequiredByNativeCode] internal static void InvokeOnAudioSystemStartedUp() => OnAudioSystemStartedUp?.Invoke(); extern static internal bool unityAudioDisabled { [NativeName("IsAudioDisabled")] get; } [NativeMethod(Name = "AudioSettings::GetCurrentAmbisonicDefinitionName", IsFreeFunction = true)] extern static internal string GetAmbisonicDecoderPluginName(); [NativeMethod(Name = "AudioSettings::SetAmbisonicName", IsFreeFunction = true)] extern static internal void SetAmbisonicDecoderPluginName(string name); public static class Mobile { static public bool muteState { get { return false; } } static public bool stopAudioOutputOnMute { get { return false; } set { Debug.LogWarning("Setting AudioSettings.Mobile.stopAudioOutputOnMute is possible on iOS and Android only"); } } static public bool audioOutputStarted { get { return true; } } #pragma warning disable 0067 static public event Action<bool> OnMuteStateChanged; #pragma warning restore 0067 static public void StartAudioOutput() { Debug.LogWarning("AudioSettings.Mobile.StartAudioOutput is implemented for iOS and Android only"); } static public void StopAudioOutput() { Debug.LogWarning("AudioSettings.Mobile.StopAudioOutput is implemented for iOS and Android only"); } } } // A container for audio data. [NativeHeader("Modules/Audio/Public/ScriptBindings/Audio.bindings.h")] [StaticAccessor("AudioClipBindings", StaticAccessorType.DoubleColon)] public sealed class AudioClip : AudioResource { private AudioClip() {} extern static private bool GetData([NotNull] AudioClip clip, Span<float> data, int samplesOffset); extern static private bool SetData([NotNull] AudioClip clip, ReadOnlySpan<float> data, int samplesOffset); extern static private AudioClip Construct_Internal(); extern private string GetName(); extern private void CreateUserSound(string name, int lengthSamples, int channels, int frequency, bool stream); // The length of the audio clip in seconds (read-only) [NativeProperty("LengthSec")] extern public float length { get; } // The length of the audio clip in samples (read-only) // Prints how many samples the attached audio source has [NativeProperty("SampleCount")] extern public int samples { get; } // Channels in audio clip (read-only) [NativeProperty("ChannelCount")] extern public int channels { get; } // Sample frequency (read-only) extern public int frequency { get; } // Is a streamed audio clip ready to play? (read-only) [Obsolete("Use AudioClip.loadState instead to get more detailed information about the loading process.")] extern public bool isReadyToPlay { [NativeName("ReadyToPlay")] get; } // AudioClip load type (read-only) extern public AudioClipLoadType loadType { get; } extern public bool LoadAudioData(); extern public bool UnloadAudioData(); extern public bool preloadAudioData { get; } extern public bool ambisonic { get; } extern public bool loadInBackground { get; } extern public AudioDataLoadState loadState { [NativeMethod(Name = "AudioClipBindings::GetLoadState", HasExplicitThis = true)] get; } // Fills a Span with sample data from the clip. The samples are floats ranging from -1.0f to 1.0f. The sample count is determined by the length of the Span. public unsafe bool GetData(Span<float> data, int offsetSamples) { if (channels <= 0) { Debug.Log("AudioClip.GetData failed; AudioClip " + GetName() + " contains no data"); return false; } return GetData(this, data, offsetSamples); } // Fills an array with sample data from the clip. The samples are floats ranging from -1.0f to 1.0f. The sample count is determined by the length of the float array. public bool GetData(float[] data, int offsetSamples) { if (channels <= 0) { Debug.Log("AudioClip.GetData failed; AudioClip " + GetName() + " contains no data"); return false; } return GetData(this, data.AsSpan(), offsetSamples); } // Set sample data in a clip. The samples should be float values ranging from -1.0f to 1.0f. Exceeding these limits causes artifacts and undefined behaviour. public bool SetData(float[] data, int offsetSamples) { if (channels <= 0) { Debug.Log("AudioClip.SetData failed; AudioClip " + GetName() + " contains no data"); return false; } if ((offsetSamples < 0) || (offsetSamples >= samples)) throw new ArgumentException("AudioClip.SetData failed; invalid offsetSamples"); if ((data == null) || (data.Length == 0)) throw new ArgumentException("AudioClip.SetData failed; invalid data"); return SetData(this, data.AsSpan(), offsetSamples); } // Set sample data in a clip. The samples should be float values ranging from -1.0f to 1.0f. Exceeding these limits causes artifacts and undefined behaviour. public unsafe bool SetData(ReadOnlySpan<float> data, int offsetSamples) { if (channels <= 0) { Debug.Log("AudioClip.SetData failed; AudioClip " + GetName() + " contains no data"); return false; } if ((offsetSamples < 0) || (offsetSamples >= samples)) throw new ArgumentException("AudioClip.SetData failed; invalid offsetSamples"); if (data.Length == 0) throw new ArgumentException("AudioClip.SetData failed; invalid data"); return SetData(this, data, offsetSamples); } /// *listonly* [Obsolete("The _3D argument of AudioClip is deprecated. Use the spatialBlend property of AudioSource instead to morph between 2D and 3D playback.")] public static AudioClip Create(string name, int lengthSamples, int channels, int frequency, bool _3D, bool stream) { return Create(name, lengthSamples, channels, frequency, stream); } [Obsolete("The _3D argument of AudioClip is deprecated. Use the spatialBlend property of AudioSource instead to morph between 2D and 3D playback.")] public static AudioClip Create(string name, int lengthSamples, int channels, int frequency, bool _3D, bool stream, PCMReaderCallback pcmreadercallback) { return Create(name, lengthSamples, channels, frequency, stream, pcmreadercallback, null); } [Obsolete("The _3D argument of AudioClip is deprecated. Use the spatialBlend property of AudioSource instead to morph between 2D and 3D playback.")] public static AudioClip Create(string name, int lengthSamples, int channels, int frequency, bool _3D, bool stream, PCMReaderCallback pcmreadercallback, PCMSetPositionCallback pcmsetpositioncallback) { return Create(name, lengthSamples, channels, frequency, stream, pcmreadercallback, pcmsetpositioncallback); } public static AudioClip Create(string name, int lengthSamples, int channels, int frequency, bool stream) { AudioClip clip = Create(name, lengthSamples, channels, frequency, stream, null, null); return clip; } /// *listonly* public static AudioClip Create(string name, int lengthSamples, int channels, int frequency, bool stream, PCMReaderCallback pcmreadercallback) { AudioClip clip = Create(name, lengthSamples, channels, frequency, stream, pcmreadercallback, null); return clip; } // Creates a user AudioClip with a name and with the given length in samples, channels and frequency. public static AudioClip Create(string name, int lengthSamples, int channels, int frequency, bool stream, PCMReaderCallback pcmreadercallback, PCMSetPositionCallback pcmsetpositioncallback) { if (name == null) throw new NullReferenceException(); if (lengthSamples <= 0) throw new ArgumentException("Length of created clip must be larger than 0"); if (channels <= 0) throw new ArgumentException("Number of channels in created clip must be greater than 0"); if (frequency <= 0) throw new ArgumentException("Frequency in created clip must be greater than 0"); AudioClip clip = Construct_Internal(); if (pcmreadercallback != null) clip.m_PCMReaderCallback += pcmreadercallback; if (pcmsetpositioncallback != null) clip.m_PCMSetPositionCallback += pcmsetpositioncallback; clip.CreateUserSound(name, lengthSamples, channels, frequency, stream); return clip; } /// *listonly* public delegate void PCMReaderCallback(float[] data); private event PCMReaderCallback m_PCMReaderCallback = null; /// *listonly* public delegate void PCMSetPositionCallback(int position); private event PCMSetPositionCallback m_PCMSetPositionCallback = null; [RequiredByNativeCode] private void InvokePCMReaderCallback_Internal(float[] data) { if (m_PCMReaderCallback != null) m_PCMReaderCallback(data); } [RequiredByNativeCode] private void InvokePCMSetPositionCallback_Internal(int position) { if (m_PCMSetPositionCallback != null) m_PCMSetPositionCallback(position); } } public class AudioBehaviour : Behaviour { } // Representation of a listener in 3D space. [RequireComponent(typeof(Transform))] [StaticAccessor("AudioListenerBindings", StaticAccessorType.DoubleColon)] public sealed class AudioListener : AudioBehaviour { [NativeThrows] extern static private void GetOutputDataHelper([Out] float[] samples, int channel); [NativeThrows] extern static private void GetSpectrumDataHelper([Out] float[] samples, int channel, FFTWindow window); // Controls the game sound volume (0.0 to 1.0) extern static public float volume { get; set; } // The paused state of the audio. If set to True, the listener will not generate sound. [NativeProperty("ListenerPause")] extern static public bool pause { get; set; } // This lets you set whether the Audio Listener should be updated in the fixed or dynamic update. extern public AudioVelocityUpdateMode velocityUpdateMode { get; set; } // Returns a block of the listener (master)'s output data [Obsolete("GetOutputData returning a float[] is deprecated, use GetOutputData and pass a pre allocated array instead.")] static public float[] GetOutputData(int numSamples, int channel) { float[] samples = new float[numSamples]; GetOutputDataHelper(samples, channel); return samples; } // Returns a block of the listener (master)'s output data static public void GetOutputData(float[] samples, int channel) { GetOutputDataHelper(samples, channel); } // Returns a block of the listener (master)'s spectrum data [Obsolete("GetSpectrumData returning a float[] is deprecated, use GetSpectrumData and pass a pre allocated array instead.")] static public float[] GetSpectrumData(int numSamples, int channel, FFTWindow window) { float[] samples = new float[numSamples]; GetSpectrumDataHelper(samples, channel, window); return samples; } // Returns a block of the listener (master)'s spectrum data static public void GetSpectrumData(float[] samples, int channel, FFTWindow window) { GetSpectrumDataHelper(samples, channel, window); } } // A representation of audio sources in 3D. [RequireComponent(typeof(Transform))] [StaticAccessor("AudioSourceBindings", StaticAccessorType.DoubleColon)] public sealed partial class AudioSource : AudioBehaviour { extern static private float GetPitch([NotNull] AudioSource source); extern static private void SetPitch([NotNull] AudioSource source, float pitch); extern static private void PlayHelper([NotNull] AudioSource source, UInt64 delay); extern private void Play(double delay); extern static private void PlayOneShotHelper([NotNull] AudioSource source, [NotNull] AudioClip clip, float volumeScale); extern private void Stop(bool stopOneShots); [NativeThrows] extern static private void SetCustomCurveHelper([NotNull] AudioSource source, AudioSourceCurveType type, AnimationCurve curve); extern static private AnimationCurve GetCustomCurveHelper([NotNull] AudioSource source, AudioSourceCurveType type); extern static private void GetOutputDataHelper([NotNull] AudioSource source, [Out] float[] samples, int channel); [NativeThrows] extern static private void GetSpectrumDataHelper([NotNull] AudioSource source, [Out] float[] samples, int channel, FFTWindow window); // The volume of the audio source (0.0 to 1.0) extern public float volume { get; set; } // The pitch of the audio source. public float pitch { get { return GetPitch(this); } set { SetPitch(this, value); } } // Playback position in seconds. [NativeProperty("SecPosition")] extern public float time { get; set; } // Playback position in PCM samples. [NativeProperty("SamplePosition")] extern public int timeSamples { [NativeMethod(IsThreadSafe = true)] get; [NativeMethod(IsThreadSafe = true)] set; } // The default [[AudioClip]] to play [NativeProperty("AudioClip")] extern public AudioClip clip { get; set; } extern public AudioResource resource { get; set; } extern public AudioMixerGroup outputAudioMixerGroup { get; set; } [NativeConditional("PLATFORM_SUPPORTS_GAMEPAD_AUDIO")] [NativeMethod(Name = "AudioSourceBindings::PlayOnDualShock4", HasExplicitThis = true, ThrowsException = true)] [Obsolete("Use PlayOnGamepad instead")] extern public bool PlayOnDualShock4(Int32 userId); [NativeConditional("PLATFORM_SUPPORTS_GAMEPAD_AUDIO")] [NativeMethod(Name = "AudioSourceBindings::SetDualShock4SpeakerMixLevel", HasExplicitThis = true, ThrowsException = true)] [Obsolete("Use SetGamepadSpeakerMixLevel instead")] extern public bool SetDualShock4PadSpeakerMixLevel(Int32 userId, Int32 mixLevel); [NativeConditional("PLATFORM_SUPPORTS_GAMEPAD_AUDIO")] [NativeMethod(Name = "AudioSourceBindings::SetDualShock4SpeakerMixLevelDefault", HasExplicitThis = true, ThrowsException = true)] [Obsolete("Use SetGamepadSpeakerMixLevelDefault instead")] extern public bool SetDualShock4PadSpeakerMixLevelDefault(Int32 userId); [NativeConditional("PLATFORM_SUPPORTS_GAMEPAD_AUDIO")] [NativeMethod(Name = "AudioSourceBindings::SetDualShock4SpeakerRestrictedAudio", HasExplicitThis = true, ThrowsException = true)] [Obsolete("Use SetgamepadSpeakerRestrictedAudio instead")] extern public bool SetDualShock4PadSpeakerRestrictedAudio(Int32 userId, bool restricted); [NativeConditional("PLATFORM_SUPPORTS_GAMEPAD_AUDIO")] [NativeMethod(Name = "AudioSourceBindings::PlayOnGamepad", HasExplicitThis = true, ThrowsException = true)] [Obsolete("Use PlayOnGamepad instead")] extern public bool PlayOnDualShock4PadIndex(Int32 slot); [NativeConditional("PLATFORM_SUPPORTS_GAMEPAD_AUDIO")] [NativeMethod(Name = "AudioSourceBindings::DisableGamepadOutput", HasExplicitThis = true)] [Obsolete("Use DisableGamepadOutput instead")] extern public bool DisableDualShock4Output(); [NativeConditional("PLATFORM_SUPPORTS_GAMEPAD_AUDIO")] [NativeMethod(Name = "AudioSourceBindings::SetGamepadSpeakerMixLevel", HasExplicitThis = true, ThrowsException = true)] [Obsolete("Use SetGamepadSpeakerMixLevel instead")] extern public bool SetDualShock4PadSpeakerMixLevelPadIndex(Int32 slot, Int32 mixLevel); [NativeConditional("PLATFORM_SUPPORTS_GAMEPAD_AUDIO")] [NativeMethod(Name = "AudioSourceBindings::SetGamepadSpeakerMixLevelDefault", HasExplicitThis = true, ThrowsException = true)] [Obsolete("Use SetGamepadSpeakerMixLevelDefault instead")] extern public bool SetDualShock4PadSpeakerMixLevelDefaultPadIndex(Int32 slot); [NativeConditional("PLATFORM_SUPPORTS_GAMEPAD_AUDIO")] [NativeMethod(Name = "AudioSourceBindings::SetGamepadSpeakerRestrictedAudio", HasExplicitThis = true, ThrowsException = true)] [Obsolete("Use SetGamepadSpeakerRestrictedAudio instead")] extern public bool SetDualShock4PadSpeakerRestrictedAudioPadIndex(Int32 slot, bool restricted); [NativeConditional("PLATFORM_SUPPORTS_GAMEPAD_AUDIO")] [NativeMethod(Name = "AudioSourceBindings::PlayOnGamepad", HasExplicitThis = true, ThrowsException = true)] extern public bool PlayOnGamepad(Int32 slot); [NativeConditional("PLATFORM_SUPPORTS_GAMEPAD_AUDIO")] [NativeMethod(Name = "AudioSourceBindings::DisableGamepadOutput", HasExplicitThis = true)] extern public bool DisableGamepadOutput(); [NativeConditional("PLATFORM_SUPPORTS_GAMEPAD_AUDIO")] [NativeMethod(Name = "AudioSourceBindings::SetGamepadSpeakerMixLevel", HasExplicitThis = true, ThrowsException = true)] extern public bool SetGamepadSpeakerMixLevel(Int32 slot, Int32 mixLevel); [NativeConditional("PLATFORM_SUPPORTS_GAMEPAD_AUDIO")] [NativeMethod(Name = "AudioSourceBindings::SetGamepadSpeakerMixLevelDefault", HasExplicitThis = true, ThrowsException = true)] extern public bool SetGamepadSpeakerMixLevelDefault(Int32 slot); [NativeConditional("PLATFORM_SUPPORTS_GAMEPAD_AUDIO")] [NativeMethod(Name = "AudioSourceBindings::SetGamepadSpeakerRestrictedAudio", HasExplicitThis = true, ThrowsException = true)] extern public bool SetGamepadSpeakerRestrictedAudio(Int32 slot, bool restricted); [NativeConditional("PLATFORM_SUPPORTS_GAMEPAD_AUDIO")] [NativeMethod(Name = "GamepadSpeakerSupportsOutputType", HasExplicitThis = false)] extern static public bool GamepadSpeakerSupportsOutputType(GamepadSpeakerOutputType outputType); [NativeConditional("PLATFORM_SUPPORTS_GAMEPAD_AUDIO")] extern public GamepadSpeakerOutputType gamepadSpeakerOutputType { get; set; } // Plays the ::ref::clip with a certain delay (the optional delay argument is deprecated since 4.1a3) and the functionality has been replaced by PlayDelayed. [ExcludeFromDocs] public void Play() { PlayHelper(this, 0); } public void Play([UnityEngine.Internal.DefaultValue("0")] UInt64 delay) { PlayHelper(this, delay); } // Plays the ::ref::clip with a delay specified in seconds. Users are advised to use this function instead of the old Play(delay) function that took a delay specified in samples relative to a reference rate of 44.1 kHz as an argument. public void PlayDelayed(float delay) { Play((delay < 0.0f) ? 0.0 : -(double)delay); } // Schedules the ::ref::clip to play at the specified absolute time. This is the preferred way to stitch AudioClips in music players because it is independent of the frame rate and gives the audio system enough time to prepare the playback of the sound to fetch it from media where the opening and buffering takes a lot of time (streams) without causing sudden performance peaks. public void PlayScheduled(double time) { Play((time < 0.0) ? 0.0 : time); } // Plays an [[AudioClip]], and scales the [[AudioSource]] volume by volumeScale. [ExcludeFromDocs] public void PlayOneShot(AudioClip clip) { PlayOneShot(clip, 1.0f); } public void PlayOneShot(AudioClip clip, [UnityEngine.Internal.DefaultValue("1.0F")] float volumeScale) { if (clip == null) { Debug.LogWarning("PlayOneShot was called with a null AudioClip."); return; } PlayOneShotHelper(this, clip, volumeScale); } extern public void SetScheduledStartTime(double time); extern public void SetScheduledEndTime(double time); // Stops playing the ::ref::clip. public void Stop() { Stop(true); } // Pauses playing the ::ref::clip. extern public void Pause(); // Unpauses the paused source, different from play in that it does not start any new playback. extern public void UnPause(); // Calls skip on any AudioContainers on the source internal extern void SkipToNextElementIfHasContainer(); // Is the ::ref::clip playing right now (RO)? extern public bool isPlaying { [NativeName("IsPlayingScripting")] get; } internal extern bool isContainerPlaying { [NativeName("IsContainerPlaying")] get; } internal extern ActivePlayable[] containerActivePlayables { get; } extern public bool isVirtual { [NativeName("GetLastVirtualState")] get; } // Plays the clip at position. Automatically cleans up the audio source after it has finished playing. [ExcludeFromDocs] static public void PlayClipAtPoint(AudioClip clip, Vector3 position) { PlayClipAtPoint(clip, position, 1.0f); } static public void PlayClipAtPoint(AudioClip clip, Vector3 position, [UnityEngine.Internal.DefaultValue("1.0F")] float volume) { GameObject go = new GameObject("One shot audio"); go.transform.position = position; AudioSource source = (AudioSource)go.AddComponent(typeof(AudioSource)); source.clip = clip; source.spatialBlend = 1.0f; source.volume = volume; source.Play(); // Note: timeScale > 1 means that game time is accelerated. However, the sounds play at their normal speed, // so we need to postpone the point in time, when the sound is stopped. // Conversly, when timescale approaches 0, the inaccuracies of float precision mean that it kills the sound early // Also when timescale is 0, the object is destroyed immediately. // Note: The behaviour here means that when the timescale is 0, GameObjects will pile up until the timescale // is taken above 0 again. Destroy(go, clip.length * (Time.timeScale < 0.01f ? 0.01f : Time.timeScale)); } // Is the audio clip looping? extern public bool loop { get; set; } // This makes the audio source not take into account the volume of the audio listener. extern public bool ignoreListenerVolume { get; set; } // If set to true, the audio source will automatically start playing on awake extern public bool playOnAwake { get; set; } // If set to true, the audio source will be playable while the AudioListener is paused extern public bool ignoreListenerPause { get; set; } // Whether the Audio Source should be updated in the fixed or dynamic update. extern public AudioVelocityUpdateMode velocityUpdateMode { get; set; } // Sets how a Mono or 2D sound is panned linearly to the left or right. [NativeProperty("StereoPan")] extern public float panStereo { get; set; } // Sets how much a playing sound is treated as a 3D source [NativeProperty("SpatialBlendMix")] extern public float spatialBlend { get; set; } // Enables/disables custom spatialization extern public bool spatialize { get; set; } // Determines if the spatializer effect is inserted before or after the effect filters. extern public bool spatializePostEffects { get; set; } public void SetCustomCurve(AudioSourceCurveType type, AnimationCurve curve) { SetCustomCurveHelper(this, type, curve); } public AnimationCurve GetCustomCurve(AudioSourceCurveType type) { return GetCustomCurveHelper(this, type); } // Sets how much a playing sound is mixed into the reverb zones extern public float reverbZoneMix { get; set; } // Bypass effects extern public bool bypassEffects { get; set; } // Bypass listener effects extern public bool bypassListenerEffects { get; set; } // Bypass reverb zones extern public bool bypassReverbZones { get; set; } // Sets the Doppler scale for this AudioSource extern public float dopplerLevel { get; set; } // Sets the spread angle a 3d stereo or multichannel sound in speaker space. extern public float spread { get; set; } // Sets the priority of the [[AudioSource]] extern public int priority { get; set; } // Un- / Mutes the AudioSource. Mute sets the volume=0, Un-Mute restore the original volume. extern public bool mute { get; set; } // Within the Min distance the AudioSource will cease to grow louder in volume. extern public float minDistance { get; set; } // (Logarithmic rolloff) MaxDistance is the distance a sound stops attenuating at. extern public float maxDistance { get; set; } // Sets/Gets how the AudioSource attenuates over distance extern public AudioRolloffMode rolloffMode { get; set; } // Returns a block of the currently playing source's output data [Obsolete("GetOutputData returning a float[] is deprecated, use GetOutputData and pass a pre allocated array instead.")] public float[] GetOutputData(int numSamples, int channel) { float[] samples = new float[numSamples]; GetOutputDataHelper(this, samples, channel); return samples; } // Returns a block of the currently playing source's output data public void GetOutputData(float[] samples, int channel) { GetOutputDataHelper(this, samples, channel); } // Returns a block of the currently playing source's spectrum data [Obsolete("GetSpectrumData returning a float[] is deprecated, use GetSpectrumData and pass a pre allocated array instead.")] public float[] GetSpectrumData(int numSamples, int channel, FFTWindow window) { float[] samples = new float[numSamples]; GetSpectrumDataHelper(this, samples, channel, window); return samples; } // Returns a block of the currently playing source's spectrum data public void GetSpectrumData(float[] samples, int channel, FFTWindow window) { GetSpectrumDataHelper(this, samples, channel, window); } [Obsolete("minVolume is not supported anymore. Use min-, maxDistance and rolloffMode instead.", true)] public float minVolume { get { Debug.LogError("minVolume is not supported anymore. Use min-, maxDistance and rolloffMode instead."); return 0.0f; } set { Debug.LogError("minVolume is not supported anymore. Use min-, maxDistance and rolloffMode instead."); } } [Obsolete("maxVolume is not supported anymore. Use min-, maxDistance and rolloffMode instead.", true)] public float maxVolume { get { Debug.LogError("maxVolume is not supported anymore. Use min-, maxDistance and rolloffMode instead."); return 0.0f; } set { Debug.LogError("maxVolume is not supported anymore. Use min-, maxDistance and rolloffMode instead."); } } [Obsolete("rolloffFactor is not supported anymore. Use min-, maxDistance and rolloffMode instead.", true)] public float rolloffFactor { get { Debug.LogError("rolloffFactor is not supported anymore. Use min-, maxDistance and rolloffMode instead."); return 0.0f; } set { Debug.LogError("rolloffFactor is not supported anymore. Use min-, maxDistance and rolloffMode instead."); } } extern public bool SetSpatializerFloat(int index, float value); extern public bool GetSpatializerFloat(int index, out float value); extern public bool GetAmbisonicDecoderFloat(int index, out float value); extern public bool SetAmbisonicDecoderFloat(int index, float value); extern internal float GetAudioRandomContainerRuntimeMeterValue(); } // Reverb Zones are used when you want to gradually change from a point [RequireComponent(typeof(Transform))] [NativeHeader("Modules/Audio/Public/AudioReverbZone.h")] public sealed class AudioReverbZone : Behaviour { // The distance from the centerpoint that the reverb will have full effect at. Default = 10.0. extern public float minDistance { get; set; } // The distance from the centerpoint that the reverb will not have any effect. Default = 15.0. extern public float maxDistance { get; set; } // Set/Get reverb preset properties extern public AudioReverbPreset reverbPreset { get; set; } // room effect level (at mid frequencies) extern public int room { get; set; } // relative room effect level at high frequencies extern public int roomHF { get; set; } // relative room effect level at low frequencies extern public int roomLF { get; set; } // reverberation decay time at mid frequencies extern public float decayTime { get; set; } // high-frequency to mid-frequency decay time ratio extern public float decayHFRatio { get; set; } // early reflections level relative to room effect extern public int reflections { get; set; } // initial reflection delay time extern public float reflectionsDelay { get; set; } // late reverberation level relative to room effect extern public int reverb { get; set; } // late reverberation delay time relative to initial reflection extern public float reverbDelay { get; set; } // reference high frequency (hz) extern public float HFReference { get; set; } // reference low frequency (hz) extern public float LFReference { get; set; } // like rolloffscale in global settings, but for reverb room size effect [Obsolete("Warning! roomRolloffFactor is no longer supported.")] public float roomRolloffFactor { get { Debug.LogWarning("Warning! roomRolloffFactor is no longer supported."); return 10.0f; } set { Debug.LogWarning("Warning! roomRolloffFactor is no longer supported."); } } // Value that controls the echo density in the late reverberation decay extern public float diffusion { get; set; } // Value that controls the modal density in the late reverberation decay extern public float density { get; set; } extern internal bool active { get; set; } } [RequireComponent(typeof(AudioBehaviour))] public sealed partial class AudioLowPassFilter : Behaviour { extern private AnimationCurve GetCustomLowpassLevelCurveCopy(); [NativeThrows] [NativeMethod(Name = "AudioLowPassFilterBindings::SetCustomLowpassLevelCurveHelper", IsFreeFunction = true)] extern static private void SetCustomLowpassLevelCurveHelper([NotNull] AudioLowPassFilter source, AnimationCurve curve); public AnimationCurve customCutoffCurve { get { return GetCustomLowpassLevelCurveCopy(); } set { SetCustomLowpassLevelCurveHelper(this, value); } } // Lowpass cutoff frequency in hz. 10.0 to 22000.0. Default = 5000.0. extern public float cutoffFrequency { get; set; } // Determines how much the filter's self-resonance is dampened. extern public float lowpassResonanceQ { get; set; } } [RequireComponent(typeof(AudioBehaviour))] public sealed partial class AudioHighPassFilter : Behaviour { // Highpass cutoff frequency in hz. 10.0 to 22000.0. Default = 5000.0. extern public float cutoffFrequency { get; set; } // Determines how much the filter's self-resonance isdampened. extern public float highpassResonanceQ {get; set; } } // The Audio Distortion Filter distorts the sound from an AudioSource or [RequireComponent(typeof(AudioBehaviour))] public sealed class AudioDistortionFilter : Behaviour { // Distortion value. 0.0 to 1.0. Default = 0.5. extern public float distortionLevel { get; set; } } // The Audio Echo Filter repeats a sound after a given Delay, attenuating [RequireComponent(typeof(AudioBehaviour))] public sealed class AudioEchoFilter : Behaviour { // Echo delay in ms. 10 to 5000. Default = 500. extern public float delay { get; set; } // Echo decay per delay. 0 to 1. 1.0 = No decay, 0.0 = total decay (i.e. simple 1 line delay). Default = 0.5. extern public float decayRatio { get; set; } // Volume of original signal to pass to output. 0.0 to 1.0. Default = 1.0. extern public float dryMix { get; set; } // Volume of echo signal to pass to output. 0.0 to 1.0. Default = 1.0. extern public float wetMix {get; set; } } // The Audio Chorus Filter takes an Audio Clip and processes it creating a chorus effect. [RequireComponent(typeof(AudioBehaviour))] public sealed class AudioChorusFilter : Behaviour { // Volume of original signal to pass to output. 0.0 to 1.0. Default = 0.5. extern public float dryMix { get; set; } // Volume of 1st chorus tap. 0.0 to 1.0. Default = 0.5. extern public float wetMix1 { get; set; } // Volume of 2nd chorus tap. This tap is 90 degrees out of phase of the first tap. 0.0 to 1.0. Default = 0.5. extern public float wetMix2 { get; set; } // Volume of 3rd chorus tap. This tap is 90 degrees out of phase of the second tap. 0.0 to 1.0. Default = 0.5. extern public float wetMix3 { get; set; } // Chorus delay in ms. 0.1 to 100.0. Default = 40.0 ms. extern public float delay { get; set; } // Chorus modulation rate in hz. 0.0 to 20.0. Default = 0.8 hz. extern public float rate { get; set; } // Chorus modulation depth. 0.0 to 1.0. Default = 0.03. extern public float depth { get; set; } // Chorus feedback. Controls how much of the wet signal gets fed back into the chorus buffer. 0.0 to 1.0. Default = 0.0. [Obsolete("Warning! Feedback is deprecated. This property does nothing.")] public float feedback { get { Debug.LogWarning("Warning! Feedback is deprecated. This property does nothing."); return 0.0f; } set { Debug.LogWarning("Warning! Feedback is deprecated. This property does nothing."); } } } // The Audio Reverb Filter takes an Audio Clip and distortionates it in a [RequireComponent(typeof(AudioBehaviour))] public sealed partial class AudioReverbFilter : Behaviour { // Set/Get reverb preset properties extern public AudioReverbPreset reverbPreset { get; set; } // Mix level of dry signal in output in mB. Ranges from -10000.0 to 0.0. Default is 0. extern public float dryLevel { get; set; } // Room effect level at low frequencies in mB. Ranges from -10000.0 to 0.0. Default is 0.0. extern public float room { get; set; } // Room effect high-frequency level re. low frequency level in mB. Ranges from -10000.0 to 0.0. Default is 0.0. extern public float roomHF { get; set; } // Rolloff factor for room effect. Ranges from 0.0 to 10.0. Default is 10.0 [Obsolete("Warning! roomRolloffFactor is no longer supported.")] public float roomRolloffFactor { get { Debug.LogWarning("Warning! roomRolloffFactor is no longer supported."); return 10.0f; } set { Debug.LogWarning("Warning! roomRolloffFactor is no longer supported."); } } // Reverberation decay time at low-frequencies in seconds. Ranges from 0.1 to 20.0. Default is 1.0. extern public float decayTime { get; set; } // Decay HF Ratio : High-frequency to low-frequency decay time ratio. Ranges from 0.1 to 2.0. Default is 0.5. extern public float decayHFRatio { get; set; } // Early reflections level relative to room effect in mB. Ranges from -10000.0 to 1000.0. Default is -10000.0. extern public float reflectionsLevel { get; set; } // Late reverberation level relative to room effect in mB. Ranges from -10000.0 to 2000.0. Default is 0.0. extern public float reflectionsDelay { get; set; } // Late reverberation level relative to room effect in mB. Ranges from -10000.0 to 2000.0. Default is 0.0. extern public float reverbLevel { get; set; } // Late reverberation delay time relative to first reflection in seconds. Ranges from 0.0 to 0.1. Default is 0.04. extern public float reverbDelay { get; set; } // Reverberation diffusion (echo density) in percent. Ranges from 0.0 to 100.0. Default is 100.0. extern public float diffusion { get; set; } // Reverberation density (modal density) in percent. Ranges from 0.0 to 100.0. Default is 100.0. extern public float density { get; set; } // Reference high frequency in Hz. Ranges from 20.0 to 20000.0. Default is 5000.0. extern public float hfReference { get; set; } // Room effect low-frequency level in mB. Ranges from -10000.0 to 0.0. Default is 0.0. extern public float roomLF { get; set; } // Reference low-frequency in Hz. Ranges from 20.0 to 1000.0. Default is 250.0. extern public float lfReference { get; set; } } // Use this class to record to an [[AudioClip|audio clip]] using a connected microphone. [StaticAccessor("GetAudioManager()", StaticAccessorType.Dot)] public sealed class Microphone { [NativeMethod(IsThreadSafe = true)] extern static private int GetMicrophoneDeviceIDFromName(string name); extern static private AudioClip StartRecord(int deviceID, bool loop, float lengthSec, int frequency); extern static private void EndRecord(int deviceID); extern static private bool IsRecording(int deviceID); [NativeMethod(IsThreadSafe = true)] extern static private int GetRecordPosition(int deviceID); extern static private void GetDeviceCaps(int deviceID, out int minFreq, out int maxFreq); // Start Recording with device static public AudioClip Start(string deviceName, bool loop, int lengthSec, int frequency) { int deviceID = GetMicrophoneDeviceIDFromName(deviceName); if (deviceID == -1) throw new ArgumentException("Couldn't acquire device ID for device name " + deviceName); if (lengthSec <= 0) throw new ArgumentException("Length of recording must be greater than zero seconds (was: " + lengthSec + " seconds)"); if (lengthSec > 60 * 60) throw new ArgumentException("Length of recording must be less than one hour (was: " + lengthSec + " seconds)"); if (frequency <= 0) throw new ArgumentException("Frequency of recording must be greater than zero (was: " + frequency + " Hz)"); return StartRecord(deviceID, loop, lengthSec, frequency); } // Stops recording static public void End(string deviceName) { int deviceID = GetMicrophoneDeviceIDFromName(deviceName); if (deviceID == -1) return; EndRecord(deviceID); } // Gives you a list microphone devices, identified by name. extern static public string[] devices { [NativeName("GetRecordDevices")] get; } internal static extern bool isAnyDeviceRecording { [NativeName("IsAnyRecordDeviceActive")] get; } // Query if a device is currently recording. static public bool IsRecording(string deviceName) { int deviceID = GetMicrophoneDeviceIDFromName(deviceName); if (deviceID == -1) return false; return IsRecording(deviceID); } // Get the position in samples of the recording. static public int GetPosition(string deviceName) { int deviceID = GetMicrophoneDeviceIDFromName(deviceName); if (deviceID == -1) return 0; return GetRecordPosition(deviceID); } // Get the frequency capabilities of a device. static public void GetDeviceCaps(string deviceName, out int minFreq, out int maxFreq) { minFreq = 0; maxFreq = 0; int deviceID = GetMicrophoneDeviceIDFromName(deviceName); if (deviceID == -1) return; GetDeviceCaps(deviceID, out minFreq, out maxFreq); } } }
UnityCsReference/Modules/Audio/Public/ScriptBindings/Audio.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Audio/Public/ScriptBindings/Audio.bindings.cs", "repo_id": "UnityCsReference", "token_count": 21013 }
361
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Runtime.InteropServices; using UnityEngine.Bindings; using UnityEngine.Scripting; using UnityEditor.Build.Player; namespace UnityEditor.Build.Content { [Flags] public enum ContentBuildFlags { None = 0, DisableWriteTypeTree = 1 << 0, StripUnityVersion = 1 << 1, DevelopmentBuild = 1 << 2, } [Serializable] [UsedByNativeCode] [StructLayout(LayoutKind.Sequential)] public struct BuildSettings { [NativeName("typeDB")] internal TypeDB m_TypeDB; public TypeDB typeDB { get { return m_TypeDB; } set { m_TypeDB = value; } } [NativeName("target")] internal BuildTargetSelection m_Target; internal BuildTargetSelection buildTargetSelection { get { return m_Target; } set { m_Target = value; } } public BuildTarget target { get { return m_Target.platform; } set { m_Target.platform = value; } } public int subtarget { get { return m_Target.subTarget; } set { m_Target.subTarget = value; } } [NativeName("group")] internal BuildTargetGroup m_Group; public BuildTargetGroup group { get { return m_Group; } set { m_Group = value; } } [NativeName("buildFlags")] internal ContentBuildFlags m_BuildFlags; public ContentBuildFlags buildFlags { get { return m_BuildFlags; } set { m_BuildFlags = value; } } } }
UnityCsReference/Modules/BuildPipeline/Editor/Managed/BuildSettings.cs/0
{ "file_path": "UnityCsReference/Modules/BuildPipeline/Editor/Managed/BuildSettings.cs", "repo_id": "UnityCsReference", "token_count": 811 }
362
// 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 { // AssetImporter for importing ReferenceArtifactGenerator [NativeHeader("Modules/AssetPipelineEditor/Public/ReferencesArtifactGenerator.h")] [ExcludeFromPreset] internal partial class ReferencesArtifactGenerator : AssetImporter { } }
UnityCsReference/Modules/BuildPipeline/Editor/Shared/ReferencesArtifactGenerator.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/BuildPipeline/Editor/Shared/ReferencesArtifactGenerator.bindings.cs", "repo_id": "UnityCsReference", "token_count": 148 }
363
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.Build.Profile { /// <summary> /// Class containing build profile window utility functions. /// </summary> internal static class Util { internal const string k_StyleSheet = "BuildProfile/StyleSheets/BuildProfile.uss"; internal const string k_PY_MediumUssClass = "py-medium"; const int k_HelBoxChildItemCount = 2; /// <summary> /// Helper function for setting the platform settings helpbox based on /// license and module installation status. /// </summary> internal static bool UpdatePlatformRequirementsWarningHelpBox(HelpBox target, string moduleName, StandaloneBuildSubtarget subtarget) { if (target.childCount > k_HelBoxChildItemCount) { // Remove extra element added by this method. HelpBox default is // two elements. target[2].RemoveFromHierarchy(); } var licenseNotFoundElement = BuildProfileModuleUtil.CreateLicenseNotFoundElement(moduleName); if (licenseNotFoundElement is not null) { target.text = string.Empty; target.Add(licenseNotFoundElement); target.Show(); return true; } if (!BuildProfileModuleUtil.IsModuleInstalled(moduleName, subtarget)) { target.text = string.Empty; target.Add(BuildProfileModuleUtil.CreateModuleNotInstalledElement(moduleName, subtarget)); target.Show(); return true; } if (!BuildProfileModuleUtil.IsBuildProfileSupported(moduleName, subtarget)) { target.text = TrText.notSupportedWarning; target.Show(); return true; } target.Hide(); return false; } internal static void ApplyActionState(this VisualElement elem, ActionState state) { switch (state) { case ActionState.Hidden: elem.Hide(); elem.SetEnabled(false); break; case ActionState.Disabled: elem.Show(); elem.SetEnabled(false); break; case ActionState.Enabled: elem.Show(); elem.SetEnabled(true); break; default: throw new ArgumentOutOfRangeException(nameof(state), state, nameof(elem)); } } internal static void Hide(this VisualElement elem) => elem.style.display = DisplayStyle.None; internal static void Show(this VisualElement elem) => elem.style.display = DisplayStyle.Flex; } }
UnityCsReference/Modules/BuildProfileEditor/Util.cs/0
{ "file_path": "UnityCsReference/Modules/BuildProfileEditor/Util.cs", "repo_id": "UnityCsReference", "token_count": 1424 }
364
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEditor; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEditor.Build.Reporting; namespace UnityEditor.Build.Reporting { public class StrippingInfo : ScriptableObject, ISerializationCallbackReceiver { public IEnumerable<string> includedModules { get { return modules; } } public IEnumerable<string> GetReasonsForIncluding(string entityName) { HashSet<string> deps; return dependencies.TryGetValue(entityName, out deps) ? deps : Enumerable.Empty<string>(); } internal const string RequiredByScripts = "Required by Scripts"; [System.Serializable] internal struct SerializedDependency { [SerializeField] public string key; [SerializeField] public List<string> value; [SerializeField] public string icon; [SerializeField] public int size; } [SerializeField] internal List<SerializedDependency> serializedDependencies; [SerializeField] internal List<string> modules = new List<string>(); // Not needed any more since we have SerializedDependency.size now, but keep it as long as the BuildReport UI uses it. [SerializeField] internal List<int> serializedSizes = new List<int>(); [SerializeField] internal Dictionary<string, HashSet<string>> dependencies = new Dictionary<string, HashSet<string>>(); [SerializeField] internal Dictionary<string, int> sizes = new Dictionary<string, int>(); [SerializeField] internal Dictionary<string, string> icons = new Dictionary<string, string>(); [SerializeField] internal int totalSize = 0; void OnEnable() { SetIcon(RequiredByScripts, "class/MonoScript"); } void ISerializationCallbackReceiver.OnBeforeSerialize() { serializedDependencies = new List<SerializedDependency>(); foreach (var dep in dependencies) { var list = new List<string>(); foreach (var nc in dep.Value) list.Add(nc); SerializedDependency sd; sd.key = dep.Key; sd.value = list; sd.icon = icons.ContainsKey(dep.Key) ? icons[dep.Key] : "class/DefaultAsset"; sd.size = sizes.ContainsKey(dep.Key) ? sizes[dep.Key] : 0; serializedDependencies.Add(sd); } serializedSizes = new List<int>(); foreach (var module in modules) { serializedSizes.Add(sizes.ContainsKey(module) ? sizes[module] : 0); } } void ISerializationCallbackReceiver.OnAfterDeserialize() { dependencies = new Dictionary<string, HashSet<string>>(); icons = new Dictionary<string, string>(); sizes = new Dictionary<string, int>(); for (int i = 0; i < serializedDependencies.Count; i++) { HashSet<string> depends = new HashSet<string>(); foreach (var s in serializedDependencies[i].value) depends.Add(s); dependencies.Add(serializedDependencies[i].key, depends); icons[serializedDependencies[i].key] = serializedDependencies[i].icon; sizes[serializedDependencies[i].key] = serializedDependencies[i].size; } for (int i = 0; i < serializedSizes.Count; i++) sizes[modules[i]] = serializedSizes[i]; } internal void RegisterDependency(string obj, string depends) { if (!dependencies.ContainsKey(obj)) dependencies[obj] = new HashSet<string>(); dependencies[obj].Add(depends); if (!icons.ContainsKey(depends)) SetIcon(depends, "class/" + depends); } internal void AddModule(string module, bool appendModuleToName = true) { var moduleName = appendModuleToName ? ModuleName(module) : module; var packageName = $"com.unity.modules.{module.ToLower()}"; if (!modules.Contains(moduleName)) modules.Add(moduleName); if (!sizes.ContainsKey(moduleName)) sizes[moduleName] = 0; // Fall back to default icon for unknown modules if (!icons.ContainsKey(moduleName)) SetIcon(moduleName, $"package/{packageName}"); } internal void SetIcon(string dependency, string icon) { icons[dependency] = icon; if (!dependencies.ContainsKey(dependency)) dependencies[dependency] = new HashSet<string>(); } internal void AddModuleSize(string module, int size) { if (modules.Contains(module)) sizes[module] = size; } internal static StrippingInfo GetBuildReportData(BuildReport report) { if (report == null) return null; var allStrippingData = report.GetAppendices<StrippingInfo>(); if (allStrippingData.Length > 0) return allStrippingData[0]; var newData = ScriptableObject.CreateInstance<StrippingInfo>(); report.AddAppendix(newData); return newData; } internal static string ModuleName(string module) { return module + " Module"; } } }
UnityCsReference/Modules/BuildReportingEditor/Managed/StrippingInfo.cs/0
{ "file_path": "UnityCsReference/Modules/BuildReportingEditor/Managed/StrippingInfo.cs", "repo_id": "UnityCsReference", "token_count": 2567 }
365
// 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 Unity.Audio { [NativeType(Header = "Modules/DSPGraph/Public/AudioOutputHookManager.bindings.h")] internal struct AudioOutputHookManager { [NativeMethod(IsFreeFunction = true, ThrowsException = true)] public static extern unsafe void Internal_CreateAudioOutputHook(out Handle outputHook, void* jobReflectionData, void* jobData); [NativeMethod(IsFreeFunction = true, ThrowsException = true)] public static extern unsafe void Internal_DisposeAudioOutputHook(ref Handle outputHook); } }
UnityCsReference/Modules/DSPGraph/Public/ScriptBindings/AudioOutputHookManager.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/DSPGraph/Public/ScriptBindings/AudioOutputHookManager.bindings.cs", "repo_id": "UnityCsReference", "token_count": 234 }
366
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using UnityEngine; namespace UnityEditor.DeviceSimulation { internal class EndedTouch { public Vector2 position; public double endTime; public int tapCount; public EndedTouch(Vector2 position, double endTime, int tapCount) { this.position = position; this.endTime = endTime; this.tapCount = tapCount; } } internal class InputManagerBackend { public float tapTimeout = .5f; public float tapDistance = 10f; // iOS and Android have different behaviors, iOS will keep Touch.deltaTime unchanged while finger is stationary while Android resets to 0 public bool resetDeltaTimeWhenStationary; private int m_LastEventFrame = -1; private double m_LastEventTime; private List<EndedTouch> m_EndedTouches = new List<EndedTouch>(); private Touch m_NextTouch; private bool m_TouchInProgress; public InputManagerBackend() { EditorApplication.update += TouchStationary; } private void TouchStationary() { if (m_TouchInProgress && m_LastEventFrame != Time.frameCount) { m_NextTouch.phase = UnityEngine.TouchPhase.Stationary; if (resetDeltaTimeWhenStationary) { m_NextTouch.deltaTime = 0; m_LastEventTime = EditorApplication.timeSinceStartup; } Input.SimulateTouch(m_NextTouch); } } public void Touch(int id, Vector2 position, TouchPhase phase) { m_LastEventFrame = Time.frameCount; var newPhase = ToLegacy(phase); m_NextTouch.position = position; m_NextTouch.phase = newPhase; m_NextTouch.fingerId = id; m_NextTouch.deltaTime = (float)(EditorApplication.timeSinceStartup - m_LastEventTime); m_LastEventTime = EditorApplication.timeSinceStartup; if (newPhase == UnityEngine.TouchPhase.Began) { m_TouchInProgress = true; m_NextTouch.tapCount = GetTapCount(m_NextTouch.position); m_NextTouch.deltaTime = 0; } else if (m_NextTouch.phase == UnityEngine.TouchPhase.Ended || m_NextTouch.phase == UnityEngine.TouchPhase.Canceled) { m_TouchInProgress = false; if (m_NextTouch.phase == UnityEngine.TouchPhase.Ended) m_EndedTouches.Add(new EndedTouch(m_NextTouch.position, EditorApplication.timeSinceStartup, m_NextTouch.tapCount)); } Input.SimulateTouch(m_NextTouch); } private int GetTapCount(Vector2 position) { var foundTime = false; for (var i = m_EndedTouches.Count - 1; i >= 0; i--) { var endedTouch = m_EndedTouches[i]; if (tapTimeout > EditorApplication.timeSinceStartup - endedTouch.endTime) { foundTime = true; if (Vector2.Distance(position, endedTouch.position) < tapDistance) return endedTouch.tapCount + 1; } } if (!foundTime) m_EndedTouches.Clear(); return 1; } private static UnityEngine.TouchPhase ToLegacy(TouchPhase original) { switch (original) { case TouchPhase.Began: return UnityEngine.TouchPhase.Began; case TouchPhase.Moved: return UnityEngine.TouchPhase.Moved; case TouchPhase.Ended: return UnityEngine.TouchPhase.Ended; case TouchPhase.Canceled: return UnityEngine.TouchPhase.Canceled; case TouchPhase.Stationary: return UnityEngine.TouchPhase.Stationary; default: throw new ArgumentOutOfRangeException(nameof(original), original, "None is not a supported phase with legacy input system"); } } public void Dispose() { EditorApplication.update -= TouchStationary; } } }
UnityCsReference/Modules/DeviceSimulatorEditor/Input/InputManagerBackend.cs/0
{ "file_path": "UnityCsReference/Modules/DeviceSimulatorEditor/Input/InputManagerBackend.cs", "repo_id": "UnityCsReference", "token_count": 2162 }
367
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor { internal class DiagnosticSwitchPreferences : SettingsProvider { private static class Styles { public static Texture2D smallWarningIcon; public static GUIContent restartNeededWarning = EditorGUIUtility.TrTextContent("Some settings will not take effect until you restart Unity."); public static GUIStyle boldFoldout; static Styles() { smallWarningIcon = EditorGUIUtility.LoadIconRequired("console.warnicon.sml"); boldFoldout = new GUIStyle(EditorStyles.foldout) {fontStyle = FontStyle.Bold}; } } class SwitchGroup { public string name; public DiagnosticSwitch[] switches; public bool foldout; public bool HasAnyChangedValues => switches.Any(s => !s.isSetToDefault); public bool HasAnyUnappliedValues => switches.Any(s => s.needsRestart); } private const uint kMaxRangeForSlider = 10; private List<SwitchGroup> m_Switches; private bool m_HasAcceptedWarning; public DiagnosticSwitchPreferences() : base("Preferences/Diagnostics", SettingsScope.User) { } public override bool HasSearchInterest(string searchContext) { foreach (var diagSwitch in Debug.diagnosticSwitches) { if (PassesFilter(diagSwitch, searchContext)) return true; } return false; } public override void OnActivate(string searchContext, VisualElement rootElement) { var switches = Debug.diagnosticSwitches; // If any switch has been configured, assume that the user already previously saw the warning, and don't get // in their way if they are looking to reset it m_HasAcceptedWarning = switches.Any(s => !s.isSetToDefault); m_Switches = switches .GroupBy(s => s.owningModule) .Select(group => new SwitchGroup { name = group.Key, switches = group.OrderBy(s => s.name).ToArray(), foldout = group.Any(s => !s.isSetToDefault) }) .OrderBy(group => group.name) .ToList(); if (!m_HasAcceptedWarning) { VisualTreeAsset warningPanel = (VisualTreeAsset)EditorGUIUtility.LoadRequired("UXML/DiagnosticsPreferences/WarningPanel.uxml"); warningPanel.CloneTree(rootElement); rootElement.Q<Button>("ShowSettings").clicked += () => { m_HasAcceptedWarning = true; rootElement.Clear(); EditorWindow.GetWindow<PreferenceSettingsWindow>().SetupIMGUIForCurrentProviderIfNeeded(); }; } } public override void OnTitleBarGUI() { using (new EditorGUI.DisabledGroupScope(m_Switches.All(group => !group.HasAnyChangedValues))) { if (GUILayout.Button("Reset all")) { foreach (var diagnosticSwitch in m_Switches.SelectMany(group => group.switches)) diagnosticSwitch.persistentValue = diagnosticSwitch.defaultValue; DiagnosticSwitchesConsoleMessage.Instance.Update(); } } } public override void OnGUI(string searchContext) { using (new SettingsWindow.GUIScope()) { foreach (var group in m_Switches) { group.foldout = EditorGUILayout.Foldout(group.foldout, String.IsNullOrEmpty(group.name) ? "General" : group.name, group.HasAnyChangedValues ? Styles.boldFoldout : EditorStyles.foldout); if (group.foldout) { foreach (var diagnosticSwitch in group.switches) { DisplaySwitch(diagnosticSwitch); EditorGUILayout.Space(EditorGUI.kControlVerticalSpacing); EditorGUIUtility.SetBoldDefaultFont(false); } } EditorGUILayout.Space(EditorGUI.kControlVerticalSpacing.value * 1.2f); } } } public override void OnFooterBarGUI() { var helpBox = GUILayoutUtility.GetRect(Styles.restartNeededWarning, EditorStyles.helpBox, GUILayout.MinHeight(40)); if (m_Switches.Any(group => group.HasAnyUnappliedValues)) EditorGUI.HelpBox(helpBox, Styles.restartNeededWarning.text, MessageType.Warning); } private static bool PassesFilter(DiagnosticSwitch diagnosticSwitch, string filterString) { return string.IsNullOrEmpty(filterString) || SearchUtils.MatchSearchGroups(filterString, diagnosticSwitch.name); } private void DisplaySwitch(DiagnosticSwitch diagnosticSwitch) { var labelText = new GUIContent(diagnosticSwitch.name, diagnosticSwitch.description); var rowRect = GUILayoutUtility.GetRect(0, EditorGUI.kSingleLineHeight, GUILayout.ExpandWidth(true)); rowRect.xMax -= GUISkin.current.verticalScrollbar.fixedWidth + 5; var iconScaleFactor = EditorGUI.kSingleLineHeight / Styles.smallWarningIcon.height; var warningRect = new Rect(rowRect.x, rowRect.y, Styles.smallWarningIcon.width * iconScaleFactor, Styles.smallWarningIcon.height * iconScaleFactor); rowRect.x += warningRect.width + 2; if (diagnosticSwitch.needsRestart && Event.current.type == EventType.Repaint) GUI.DrawTexture(warningRect, Styles.smallWarningIcon); var resetButtonSize = EditorStyles.miniButton.CalcSize(GUIContent.Temp("Reset")); var resetButtonRect = new Rect(rowRect.xMax - resetButtonSize.x, rowRect.y, resetButtonSize.x, resetButtonSize.y); rowRect.xMax -= resetButtonSize.x + 2; if (!diagnosticSwitch.isSetToDefault) { if (GUI.Button(resetButtonRect, "Reset", EditorStyles.miniButton)) { diagnosticSwitch.persistentValue = diagnosticSwitch.defaultValue; DiagnosticSwitchesConsoleMessage.Instance.Update(); } } else { // Reserve an ID for the 'reset' button so that if the user begins typing in a text-valued switch, the // button showing up doesn't cause the focus to change GUIUtility.GetControlID("Button".GetHashCode(), FocusType.Passive, resetButtonRect); } EditorGUIUtility.SetBoldDefaultFont(!diagnosticSwitch.persistentValue.Equals(diagnosticSwitch.defaultValue)); EditorGUI.BeginChangeCheck(); if (diagnosticSwitch.value is bool) { diagnosticSwitch.persistentValue = EditorGUI.Toggle(rowRect, labelText, (bool)diagnosticSwitch.persistentValue); } else if (diagnosticSwitch.enumInfo != null) { if (diagnosticSwitch.enumInfo.isFlags) { // MaskField's "Everything" entry will set the value to 0xffffffff, but that might mean that it has set bits that // are not actually valid in the enum. Correct for it by masking the value against the bit patterns that are actually valid. int validMask = 0; foreach (int value in diagnosticSwitch.enumInfo.values) validMask |= value; // Also, many enums will provide a 'Nothing' entry at the bottom. If so we need to chop it off, because MaskField can't cope with there being two 'Nothing' entries. string[] names = diagnosticSwitch.enumInfo.names; int[] values = diagnosticSwitch.enumInfo.values; if (diagnosticSwitch.enumInfo.values[0] == 0) { names = new string[names.Length - 1]; values = new int[values.Length - 1]; Array.Copy(diagnosticSwitch.enumInfo.names, 1, names, 0, names.Length); Array.Copy(diagnosticSwitch.enumInfo.values, 1, values, 0, values.Length); } diagnosticSwitch.persistentValue = EditorGUI.MaskFieldInternal(rowRect, labelText, (int)diagnosticSwitch.persistentValue, names, values, EditorStyles.popup) & validMask; } else { var guiNames = new GUIContent[diagnosticSwitch.enumInfo.names.Length]; for (int i = 0; i < diagnosticSwitch.enumInfo.names.Length; ++i) guiNames[i] = new GUIContent(diagnosticSwitch.enumInfo.names[i], diagnosticSwitch.enumInfo.annotations[i]); diagnosticSwitch.persistentValue = EditorGUI.IntPopup(rowRect, labelText, (int)diagnosticSwitch.persistentValue, guiNames, diagnosticSwitch.enumInfo.values); } } else if (diagnosticSwitch.value is UInt32) { UInt32 minValue = (UInt32)diagnosticSwitch.minValue; UInt32 maxValue = (UInt32)diagnosticSwitch.maxValue; if ((maxValue - minValue <= kMaxRangeForSlider) && (maxValue - minValue > 0) && (minValue < int.MaxValue && maxValue < int.MaxValue)) { diagnosticSwitch.persistentValue = (UInt32)EditorGUI.IntSlider(rowRect, labelText, (int)(UInt32)diagnosticSwitch.persistentValue, (int)minValue, (int)maxValue); } else { diagnosticSwitch.persistentValue = (UInt32)EditorGUI.IntField(rowRect, labelText, (int)(UInt32)diagnosticSwitch.persistentValue); } } else if (diagnosticSwitch.value is int) { int minValue = (int)diagnosticSwitch.minValue; int maxValue = (int)diagnosticSwitch.maxValue; if ((maxValue - minValue <= kMaxRangeForSlider) && (maxValue - minValue > 0) && (minValue < int.MaxValue && maxValue < int.MaxValue)) { diagnosticSwitch.persistentValue = EditorGUI.IntSlider(rowRect, labelText, (int)diagnosticSwitch.persistentValue, minValue, maxValue); } else { diagnosticSwitch.persistentValue = EditorGUI.IntField(rowRect, labelText, (int)diagnosticSwitch.persistentValue); } } else if (diagnosticSwitch.value is string) { diagnosticSwitch.persistentValue = EditorGUI.TextField(rowRect, labelText, (string)diagnosticSwitch.persistentValue); } else if (diagnosticSwitch.value is float) { diagnosticSwitch.persistentValue = EditorGUI.FloatField(rowRect, labelText, (float)diagnosticSwitch.persistentValue); } else { var redStyle = new GUIStyle(); redStyle.normal.textColor = Color.red; EditorGUI.LabelField(rowRect, labelText, EditorGUIUtility.TrTextContent("Unsupported type: " + diagnosticSwitch.value.GetType().Name), redStyle); } if (EditorGUI.EndChangeCheck()) DiagnosticSwitchesConsoleMessage.Instance.Update(); } [SettingsProvider] internal static SettingsProvider CreateDiagnosticProvider() { // Diagnostic switches might be turned off in the build, // in which case there will be none of them -- don't // create the preference pane then. return Debug.diagnosticSwitches.Length != 0 ? new DiagnosticSwitchPreferences() : null; } } }
UnityCsReference/Modules/DiagnosticsEditor/DiagnosticsPreferences.cs/0
{ "file_path": "UnityCsReference/Modules/DiagnosticsEditor/DiagnosticsPreferences.cs", "repo_id": "UnityCsReference", "token_count": 5858 }
368
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor.Overlays; using UnityEditor.UIElements; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.Toolbars { public class EditorToolbarToggle : ToolbarToggle { internal const string textIconClassName = EditorToolbar.elementTextIconClassName; internal const string textClassName = EditorToolbar.elementLabelClassName; internal const string iconClassName = EditorToolbar.elementIconClassName; internal const string k_TextIconElementName = "EditorToolbarToggleTextIcon"; internal const string k_TextElementName = "EditorToolbarToggleText"; public new const string ussClassName = "unity-editor-toolbar-toggle"; internal static readonly string toggleNoIconClassName = ussClassName + "-noicon"; Texture2D m_OnIcon; Texture2D m_OffIcon; TextElement m_TextElement; TextElement m_TextIconElement; Image m_IconElement; public new string text { get => m_TextElement?.text; set { if (string.IsNullOrEmpty(value)) { m_TextElement?.RemoveFromHierarchy(); m_TextElement = null; return; } if (m_TextElement == null) { m_TextElement = new TextElement(); m_TextElement.name = k_TextElementName; m_TextElement.AddToClassList(textClassName); var input = this.Q<VisualElement>(className: Toggle.inputUssClassName); if (m_IconElement != null) input.Insert(input.IndexOf(m_IconElement) + 1, m_TextElement); else if (m_TextIconElement != null) input.Insert(input.IndexOf(m_TextIconElement) + 1, m_TextElement); else input.Add(m_TextElement); } m_TextElement.text = value; UpdateIconState(); UpdateTextIconState(); } } public string textIcon { get => m_TextIconElement?.text; set { if (m_TextIconElement == null) { m_IconElement?.RemoveFromHierarchy(); m_IconElement = null; m_OffIcon = null; m_OnIcon = null; m_TextIconElement = new TextElement(); m_TextIconElement.name = k_TextIconElementName; m_TextIconElement.AddToClassList(textIconClassName); var input = this.Q<VisualElement>(className: Toggle.inputUssClassName); if (m_TextElement != null) { m_TextElement.RemoveFromHierarchy(); input.Add(m_TextIconElement); input.Add(m_TextElement); } else { input.Add(m_TextIconElement); } } m_TextIconElement.text = OverlayUtilities.GetSignificantLettersForIcon(value); UpdateTextIconState(); } } public Texture2D icon { get => offIcon; set { CreateIconElement(); offIcon = onIcon = value; UpdateIconState(); } } public Texture2D onIcon { get => m_OnIcon; set { CreateIconElement(); m_OnIcon = value; UpdateIconState(); } } public Texture2D offIcon { get => m_OffIcon; set { CreateIconElement(); m_OffIcon = value; UpdateIconState(); } } public EditorToolbarToggle() : this(string.Empty, null, null) {} public EditorToolbarToggle(string text) : this(text, null, null) {} public EditorToolbarToggle(Texture2D icon) : this(string.Empty, icon, icon) {} public EditorToolbarToggle(Texture2D onIcon, Texture2D offIcon) : this(string.Empty, onIcon, offIcon) {} public EditorToolbarToggle(string text, Texture2D onIcon, Texture2D offIcon) { AddToClassList(ussClassName); this.onIcon = onIcon; this.offIcon = offIcon; this.text = text; UpdateIconState(); } public EditorToolbarToggle(string textIcon, string label) { AddToClassList(ussClassName); this.textIcon = textIcon; this.text = label; UpdateTextIconState(); } public override void SetValueWithoutNotify(bool newValue) { base.SetValueWithoutNotify(newValue); UpdateIcon(); } void UpdateIcon() { if (m_IconElement == null) return; m_IconElement.image = value ? onIcon : offIcon; } void UpdateIconState() { if (m_IconElement == null) return; if (icon == null && (text != null && text != string.Empty)) { if (!m_IconElement.ClassListContains(toggleNoIconClassName)) m_IconElement.AddToClassList(toggleNoIconClassName); } else if (icon && m_IconElement.ClassListContains(toggleNoIconClassName)) { m_IconElement.RemoveFromClassList(toggleNoIconClassName); } UpdateIcon(); } void UpdateTextIconState() { if (m_TextIconElement == null) return; if ((m_TextIconElement == null || string.IsNullOrEmpty(textIcon)) && (text != null && text != string.Empty)) { if (!m_TextIconElement.ClassListContains(toggleNoIconClassName)) m_TextIconElement.AddToClassList(toggleNoIconClassName); } else if (m_TextIconElement != null && m_TextIconElement.ClassListContains(toggleNoIconClassName)) { m_TextIconElement.RemoveFromClassList(toggleNoIconClassName); } } void CreateIconElement() { if (m_IconElement == null) { m_TextIconElement?.RemoveFromHierarchy(); m_TextIconElement = null; var input = this.Q<VisualElement>(className: Toggle.inputUssClassName); m_IconElement = new Image { scaleMode = ScaleMode.ScaleToFit }; m_IconElement.AddToClassList(iconClassName); if (m_TextElement != null) { m_TextElement.RemoveFromHierarchy(); input.Add(m_IconElement); input.Add(m_TextElement); } else { input.Add(m_IconElement); } } } } }
UnityCsReference/Modules/EditorToolbar/Controls/EditorToolbarToggle.cs/0
{ "file_path": "UnityCsReference/Modules/EditorToolbar/Controls/EditorToolbarToggle.cs", "repo_id": "UnityCsReference", "token_count": 3904 }
369
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License // #define QUICK_SEARCH_STORE using UnityEngine.UIElements; using UnityEditor.Toolbars; using UnityEditor.Connect; using UnityEngine; namespace UnityEditor.Search { [EditorToolbarElement("Editor Utility/Store", typeof(DefaultMainToolbar))] sealed class StoreButton : EditorToolbarDropdown { const string k_SearchStoreCommand = "OpenSearchStore"; const string k_OpenAssetStoreCommand = "OpenAssetStoreInBrowser"; public StoreButton() { icon = EditorGUIUtility.FindTexture("AssetStore Icon"); text = "Asset Store"; RegisterCallback<AttachToPanelEvent>(OnAttachedToPanel); RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel); clicked += ActivateAssetStoreMenu; } void OnAttachedToPanel(AttachToPanelEvent evt) { EditorApplication.delayCall += DelayInitialization; } void OnDetachFromPanel(DetachFromPanelEvent evt) { ShortcutManagement.ShortcutManager.instance.shortcutBindingChanged -= UpdateTooltip; } private void DelayInitialization() { UpdateTooltip(); style.display = CommandService.Exists(k_SearchStoreCommand) ? DisplayStyle.Flex : DisplayStyle.None; ShortcutManagement.ShortcutManager.instance.shortcutBindingChanged += UpdateTooltip; } private void UpdateTooltip() { tooltip = GetTooltipText(); } private void UpdateTooltip(ShortcutManagement.ShortcutBindingChangedEventArgs obj) { UpdateTooltip(); } private string GetTooltipText() { return L10n.Tr($"Asset Store"); } private void ActivateAssetStoreMenu() { var menu = new GenericMenu(); menu.AddItem(EditorGUIUtility.TrTextContent("Asset Store Web"), false, () => CommandService.Execute(k_OpenAssetStoreCommand)); menu.AddItem(EditorGUIUtility.TrTextContent("My Assets"), false, () => PackageManager.UI.PackageManagerWindow.SelectPackageAndPageStatic(pageId: PackageManager.UI.Internal.MyAssetsPage.k_Id)); menu.DropDown(worldBound, true); } } }
UnityCsReference/Modules/EditorToolbar/ToolbarElements/StoreButton.cs/0
{ "file_path": "UnityCsReference/Modules/EditorToolbar/ToolbarElements/StoreButton.cs", "repo_id": "UnityCsReference", "token_count": 948 }
370
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.Experimental.GraphView { internal class ElementResizer : MouseManipulator { private readonly ResizerDirection direction; private readonly VisualElement resizedElement; public ElementResizer(VisualElement resizedElement, ResizerDirection direction) { this.direction = direction; this.resizedElement = resizedElement; activators.Add(new ManipulatorActivationFilter() { button = MouseButton.LeftMouse }); } protected override void RegisterCallbacksOnTarget() { target.RegisterCallback<MouseDownEvent>(OnMouseDown); target.RegisterCallback<MouseUpEvent>(OnMouseUp); } protected override void UnregisterCallbacksFromTarget() { target.UnregisterCallback<MouseDownEvent>(OnMouseDown); target.UnregisterCallback<MouseUpEvent>(OnMouseUp); } Vector2 m_StartMouse; Vector2 m_StartSize; Vector2 m_MinSize; Vector2 m_MaxSize; Vector2 m_StartPosition; bool m_DragStarted = false; bool m_Active = false; void OnMouseDown(MouseDownEvent e) { if (m_Active) { e.StopImmediatePropagation(); return; } if (!CanStartManipulation(e)) return; // SGB-549: Prevent stealing capture from a child element. This shouldn't be necessary if children // elements call StopPropagation when they capture the mouse, but we can't be sure of that and thus // we are being a bit overprotective here. if (target.panel?.GetCapturingElement(PointerId.mousePointerId) != null) { return; } m_Active = true; VisualElement resizedTarget = resizedElement.parent; if (resizedTarget == null) return; VisualElement resizedBase = resizedTarget.parent; if (resizedBase == null) return; target.RegisterCallback<MouseMoveEvent>(OnMouseMove); e.StopPropagation(); target.CaptureMouse(); m_StartMouse = resizedBase.WorldToLocal(e.mousePosition); m_StartSize = new Vector2(resizedTarget.resolvedStyle.width, resizedTarget.resolvedStyle.height); m_StartPosition = new Vector2(resizedTarget.resolvedStyle.left, resizedTarget.resolvedStyle.top); bool minWidthDefined = resizedTarget.resolvedStyle.minWidth != StyleKeyword.Auto; bool maxWidthDefined = resizedTarget.resolvedStyle.maxWidth != StyleKeyword.None; bool minHeightDefined = resizedTarget.resolvedStyle.minHeight != StyleKeyword.Auto; bool maxHeightDefined = resizedTarget.resolvedStyle.maxHeight != StyleKeyword.None; m_MinSize = new Vector2( minWidthDefined ? resizedTarget.resolvedStyle.minWidth.value : Mathf.NegativeInfinity, minHeightDefined ? resizedTarget.resolvedStyle.minHeight.value : Mathf.NegativeInfinity); m_MaxSize = new Vector2( maxWidthDefined ? resizedTarget.resolvedStyle.maxWidth.value : Mathf.Infinity, maxHeightDefined ? resizedTarget.resolvedStyle.maxHeight.value : Mathf.Infinity); m_DragStarted = false; } void OnMouseMove(MouseMoveEvent e) { if (!m_Active) return; VisualElement resizedTarget = resizedElement.parent; VisualElement resizedBase = resizedTarget.parent; Vector2 mousePos = resizedBase.WorldToLocal(e.mousePosition); if (!m_DragStarted) { if (resizedTarget is IResizable) (resizedTarget as IResizable).OnStartResize(); m_DragStarted = true; } if (resizedTarget.isLayoutManual) { Rect layout = resizedTarget.layout; if ((direction & ResizerDirection.Right) != 0) { layout.width = Mathf.Clamp(m_StartSize.x + mousePos.x - m_StartMouse.x, m_MinSize.x, Mathf.Min(m_MaxSize.x, resizedBase.layout.xMax - layout.xMin)); } else if ((direction & ResizerDirection.Left) != 0) { float delta = mousePos.x - m_StartMouse.x; float previousLeft = layout.xMin; layout.xMin = Mathf.Clamp(delta + m_StartPosition.x, 0, resizedTarget.layout.xMax - m_MinSize.x); layout.width = resizedTarget.resolvedStyle.width + previousLeft - layout.xMin; } if ((direction & ResizerDirection.Bottom) != 0) { layout.height = Mathf.Clamp(m_StartSize.y + mousePos.y - m_StartMouse.y, m_MinSize.y, resizedBase.layout.yMax - layout.yMin); } else if ((direction & ResizerDirection.Top) != 0) { float delta = mousePos.y - m_StartMouse.y; float previousTop = layout.yMin; layout.yMin = Mathf.Clamp(delta + m_StartPosition.y, 0, m_StartSize.y - 1); layout.height = resizedTarget.resolvedStyle.height + previousTop - layout.yMin; } if (direction != 0) { resizedTarget.layout = layout; } } else { if ((direction & ResizerDirection.Right) != 0) { resizedTarget.style.width = Mathf.Clamp(m_StartSize.x + mousePos.x - m_StartMouse.x, m_MinSize.x, Mathf.Min(m_MaxSize.x, resizedBase.layout.xMax - resizedTarget.layout.xMin)); } else if ((direction & ResizerDirection.Left) != 0) { float delta = mousePos.x - m_StartMouse.x; float previousLeft = resizedTarget.style.left.value.value; resizedTarget.style.left = Mathf.Clamp(delta + m_StartPosition.x, 0, resizedTarget.layout.xMax - m_MinSize.x); resizedTarget.style.width = resizedTarget.resolvedStyle.width + previousLeft - resizedTarget.style.left.value.value; } if ((direction & ResizerDirection.Bottom) != 0) { resizedTarget.style.height = Mathf.Min(m_MaxSize.y, Mathf.Max(m_MinSize.y, m_StartSize.y + mousePos.y - m_StartMouse.y)); } else if ((direction & ResizerDirection.Top) != 0) { float delta = mousePos.y - m_StartMouse.y; float previousTop = resizedTarget.style.top.value.value; resizedTarget.style.top = Mathf.Clamp(delta + m_StartPosition.y, 0, m_StartSize.y - 1); resizedTarget.style.height = resizedTarget.resolvedStyle.height + previousTop - resizedTarget.style.top.value.value; } } e.StopPropagation(); } void OnMouseUp(MouseUpEvent e) { if (!CanStopManipulation(e)) return; if (m_Active) { VisualElement resizedTarget = resizedElement.parent; if (resizedTarget.style.width != m_StartSize.x || resizedTarget.style.height != m_StartSize.y) { if (resizedTarget is IResizable) (resizedTarget as IResizable).OnResized(); } target.UnregisterCallback<MouseMoveEvent>(OnMouseMove); target.ReleaseMouse(); e.StopPropagation(); m_Active = false; } } } }
UnityCsReference/Modules/GraphViewEditor/Elements/ElementResizer.cs/0
{ "file_path": "UnityCsReference/Modules/GraphViewEditor/Elements/ElementResizer.cs", "repo_id": "UnityCsReference", "token_count": 3978 }
371
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.Experimental.GraphView { public partial class StackNode : Node { private VisualElement m_ContentContainer; private VisualElement m_SeparatorContainer; private VisualElement m_PlaceholderContainer; private StackNodePlaceholder m_Placeholder; public VisualElement headerContainer { get; private set; } public override VisualElement contentContainer => m_ContentContainer; internal GraphView graphView { get; set; } private static CustomStyleProperty<float> s_SeparatorHeight = new CustomStyleProperty<float>("--separator-height"); private static CustomStyleProperty<float> s_SeparatorExtent = new CustomStyleProperty<float>("--separator-extent"); private float m_SeparatorHeight = 4f; private float separatorHeight => m_SeparatorHeight; private float m_SeparatorExtent = 15f; private float separatorExtent => m_SeparatorExtent; public StackNode() : base("UXML/GraphView/StackNode.uxml") { capabilities &= ~Capabilities.Groupable; VisualElement stackNodeContentContainerPlaceholder = this.Q("stackNodeContentContainerPlaceholder"); headerContainer = this.Q("stackNodeHeaderContainer"); m_SeparatorContainer = this.Q("stackSeparatorContainer"); m_PlaceholderContainer = this.Q("stackPlaceholderContainer"); m_PlaceholderContainer.Add(m_Placeholder = new StackNodePlaceholder("Spacebar to Add Node")); m_ContentContainer = new StackNodeContentContainer(); m_ContentContainer.name = "stackNodeContentContainer"; stackNodeContentContainerPlaceholder.Add(m_ContentContainer); ClearClassList(); AddToClassList("stack-node"); AddStyleSheetPath("StyleSheets/GraphView/StackNode.uss"); } [EventInterest(typeof(GeometryChangedEvent), typeof(DetachFromPanelEvent), typeof(AttachToPanelEvent))] protected override void HandleEventBubbleUp(EventBase evt) { base.HandleEventBubbleUp(evt); if (evt.eventTypeId == GeometryChangedEvent.TypeId()) { UpdateSeparators(); } else if (evt.eventTypeId == DetachFromPanelEvent.TypeId()) { graphView = null; } else if (evt.eventTypeId == AttachToPanelEvent.TypeId()) { graphView = GetFirstAncestorOfType<GraphView>(); if (graphView != null) { // Restore selections on children. foreach (var child in Children().OfType<GraphElement>()) { graphView.RestorePersitentSelectionForElement(child); } } } } private bool AcceptsElementInternal(GraphElement element, ref int proposedIndex, int maxIndex) { // TODO: we probably need a "Stackable" capability return element != null && !(element is Scope) && !(element is StackNode) && !(element is TokenNode) && !(element is Placemat) && (element.GetContainingScope() as Group) == null && AcceptsElement(element, ref proposedIndex, maxIndex); } protected virtual bool AcceptsElement(GraphElement element, ref int proposedIndex, int maxIndex) { return true; } public void AddElement(GraphElement element) { InsertElement(childCount, element); } public void InsertElement(int index, GraphElement element) { if (!AcceptsElementInternal(element, ref index, childCount)) { return; } Insert(index, element); OnChildAdded(element); if (graphView != null) { graphView.RestorePersitentSelectionForElement(element); } } public void RemoveElement(GraphElement element) { Remove(element); } protected override void OnCustomStyleResolved(ICustomStyle styles) { base.OnCustomStyleResolved(styles); int animDurationValue = 0; float heightValue = 0f; float extentValue = 0f; if (styles.TryGetValue(s_AnimationDuration, out animDurationValue)) m_AnimationDuration = animDurationValue; if (styles.TryGetValue(s_SeparatorHeight, out heightValue)) m_SeparatorHeight = heightValue; if (styles.TryGetValue(s_SeparatorExtent, out extentValue)) m_SeparatorExtent = extentValue; schedule.Execute(a => UpdateSeparators()); } private void UpdateSeparators() { int expectedSeparatorCount = childCount > 0 ? childCount + 1 : 0; // If there are missing separators then add them if (m_SeparatorContainer.childCount < expectedSeparatorCount) { for (int i = m_SeparatorContainer.childCount; i < expectedSeparatorCount; ++i) { var separator = new StackNodeSeparator { menuEvent = ExecuteOnSeparatorContextualMenuEvent }; separator.StretchToParentWidth(); m_SeparatorContainer.Add(separator); } } // If there are exceeding separators then remove them if (m_SeparatorContainer.childCount > expectedSeparatorCount) { for (int i = m_SeparatorContainer.childCount - 1; i >= expectedSeparatorCount; --i) { m_SeparatorContainer[i].RemoveFromHierarchy(); } } // Updates the geometry of each separator for (int i = 0; i < m_SeparatorContainer.childCount; ++i) { var separator = m_SeparatorContainer[i] as StackNodeSeparator; separator.extent = separatorExtent; separator.height = separatorHeight; float separatorCenterY = 0; // For the first separator, use the top of the first element if (i == 0) { separatorCenterY = separatorHeight / 2; } // .. for the other separators, use the spacing between the current and the next separators else if (i < m_SeparatorContainer.childCount - 1) { VisualElement element = this[i - 1]; VisualElement nextElement = this[i]; separatorCenterY = (nextElement.layout.yMin + element.layout.yMax) / 2; } // .. for the last separator, use the bottom of the container else { separatorCenterY = m_SeparatorContainer.layout.height - separatorHeight / 2; } separator.style.top = separatorCenterY - separator.resolvedStyle.height / 2; } } private void OnChildAdded(GraphElement element) { element.AddToClassList("stack-child-element"); // these capabilities should be set correctly on contruction of stackable nodes (in client/dependent code), // -- Since the module didn't have a way of identifying stackable nodes previously, we can provide some identity here. // TODO: Remove this once deps have an opportunity to use the flags. element.capabilities &= ~(Capabilities.Snappable | Capabilities.Stackable | Capabilities.Groupable); element.ResetPositionProperties(); element.RegisterCallback<DetachFromPanelEvent>(OnChildDetachedFromPanel); UpdatePlaceholderVisibility(); } private void OnChildRemoved(GraphElement element) { element.RemoveFromClassList("stack-child-element"); element.UnregisterCallback<DetachFromPanelEvent>(OnChildDetachedFromPanel); // Disable the animation temporarily if (m_InstantAdd == false) { m_InstantAdd = true; schedule.Execute(() => m_InstantAdd = false); } UpdatePlaceholderVisibility(); } private void UpdatePlaceholderVisibility() { if (childCount != 0) { m_Placeholder.RemoveFromHierarchy(); } else { if (m_Placeholder.parent == null) { m_PlaceholderContainer.Add(m_Placeholder); } } } private void OnChildDetachedFromPanel(DetachFromPanelEvent evt) { if (panel == null) return; GraphElement element = evt.target as GraphElement; OnChildRemoved(element); } private void ExecuteOnSeparatorContextualMenuEvent(ContextualMenuPopulateEvent evt, int separatorIndex) { if (evt.target is StackNodeSeparator) { OnSeparatorContextualMenuEvent(evt, separatorIndex); } evt.StopPropagation(); } protected virtual void OnSeparatorContextualMenuEvent(ContextualMenuPopulateEvent evt, int separatorIndex) { } public virtual int GetInsertionIndex(Vector2 worldPosition) { var ve = graphView.currentInsertLocation as VisualElement; if (ve == null) return -1; // Checking if it's one of our children if (this == ve.GetFirstAncestorOfType<StackNode>()) { InsertInfo insertInfo; graphView.currentInsertLocation.GetInsertInfo(worldPosition, out insertInfo); return insertInfo.index; } return -1; } public virtual void OnStartDragging(GraphElement ge) { var node = ge as Node; if (node != null) { ge.RemoveFromHierarchy(); graphView.AddElement(ge); // Reselect it because RemoveFromHierarchy unselected it ge.Select(graphView, true); } } public override void CollectElements(HashSet<GraphElement> collectedElementSet, Func<GraphElement, bool> conditionFunc) { base.CollectElements(collectedElementSet, conditionFunc); GraphView.CollectElements(Children().OfType<GraphElement>(), collectedElementSet, conditionFunc); } } }
UnityCsReference/Modules/GraphViewEditor/Elements/StackNode.cs/0
{ "file_path": "UnityCsReference/Modules/GraphViewEditor/Elements/StackNode.cs", "repo_id": "UnityCsReference", "token_count": 5063 }
372
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.Experimental.GraphView { public interface IEdgeConnectorListener { void OnDropOutsidePort(Edge edge, Vector2 position); void OnDrop(GraphView graphView, Edge edge); } public abstract class EdgeConnector : MouseManipulator { public abstract EdgeDragHelper edgeDragHelper { get; } } public class EdgeConnector<TEdge> : EdgeConnector where TEdge : Edge, new() { readonly EdgeDragHelper m_EdgeDragHelper; Edge m_EdgeCandidate; private bool m_Active; Vector2 m_MouseDownPosition; internal const float k_ConnectionDistanceTreshold = 10f; public EdgeConnector(IEdgeConnectorListener listener) { m_EdgeDragHelper = new EdgeDragHelper<TEdge>(listener); m_Active = false; activators.Add(new ManipulatorActivationFilter { button = MouseButton.LeftMouse }); } public override EdgeDragHelper edgeDragHelper => m_EdgeDragHelper; protected override void RegisterCallbacksOnTarget() { target.RegisterCallback<MouseDownEvent>(OnMouseDown); target.RegisterCallback<MouseMoveEvent>(OnMouseMove); target.RegisterCallback<MouseUpEvent>(OnMouseUp); target.RegisterCallback<KeyDownEvent>(OnKeyDown); target.RegisterCallback<MouseCaptureOutEvent>(OnCaptureOut); } protected override void UnregisterCallbacksFromTarget() { target.UnregisterCallback<MouseDownEvent>(OnMouseDown); target.UnregisterCallback<MouseMoveEvent>(OnMouseMove); target.UnregisterCallback<MouseUpEvent>(OnMouseUp); target.UnregisterCallback<KeyDownEvent>(OnKeyDown); } protected virtual void OnMouseDown(MouseDownEvent e) { if (m_Active) { e.StopImmediatePropagation(); return; } if (!CanStartManipulation(e)) { return; } var graphElement = target as Port; if (graphElement == null) { return; } m_MouseDownPosition = e.localMousePosition; m_EdgeCandidate = new TEdge(); m_EdgeDragHelper.draggedPort = graphElement; m_EdgeDragHelper.edgeCandidate = m_EdgeCandidate; if (m_EdgeDragHelper.HandleMouseDown(e)) { m_Active = true; target.CaptureMouse(); e.StopPropagation(); } else { m_EdgeDragHelper.Reset(); m_EdgeCandidate = null; } } void OnCaptureOut(MouseCaptureOutEvent e) { m_Active = false; if (m_EdgeCandidate != null) Abort(); } protected virtual void OnMouseMove(MouseMoveEvent e) { if (!m_Active) return; m_EdgeDragHelper.HandleMouseMove(e); m_EdgeCandidate.candidatePosition = e.mousePosition; m_EdgeCandidate.UpdateEdgeControl(); e.StopPropagation(); } protected virtual void OnMouseUp(MouseUpEvent e) { if (!m_Active || !CanStopManipulation(e)) return; if (CanPerformConnection(e.localMousePosition)) m_EdgeDragHelper.HandleMouseUp(e); else Abort(); m_Active = false; m_EdgeCandidate = null; target.ReleaseMouse(); e.StopPropagation(); } private void OnKeyDown(KeyDownEvent e) { if (e.keyCode != KeyCode.Escape || !m_Active) return; Abort(); m_Active = false; target.ReleaseMouse(); e.StopPropagation(); } void Abort() { var graphView = target?.GetFirstAncestorOfType<GraphView>(); graphView?.RemoveElement(m_EdgeCandidate); m_EdgeCandidate.input = null; m_EdgeCandidate.output = null; m_EdgeCandidate = null; m_EdgeDragHelper.Reset(); } bool CanPerformConnection(Vector2 mousePosition) { return Vector2.Distance(m_MouseDownPosition, mousePosition) > k_ConnectionDistanceTreshold; } } }
UnityCsReference/Modules/GraphViewEditor/Manipulators/EdgeConnector.cs/0
{ "file_path": "UnityCsReference/Modules/GraphViewEditor/Manipulators/EdgeConnector.cs", "repo_id": "UnityCsReference", "token_count": 2201 }
373
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEditor.Experimental.GraphView { public enum Orientation { Horizontal, Vertical } }
UnityCsReference/Modules/GraphViewEditor/Orientation.cs/0
{ "file_path": "UnityCsReference/Modules/GraphViewEditor/Orientation.cs", "repo_id": "UnityCsReference", "token_count": 98 }
374
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Runtime.CompilerServices; namespace Unity.Hierarchy { /// <summary> /// Represents an enumerable over the children of an <see cref="HierarchyNode"/>. /// </summary> public readonly struct HierarchyFlattenedNodeChildren { readonly HierarchyFlattened m_HierarchyFlattened; readonly HierarchyNode m_Node; readonly int m_Version; readonly int m_Count; internal HierarchyFlattenedNodeChildren(HierarchyFlattened hierarchyFlattened, in HierarchyNode node) { if (hierarchyFlattened == null) throw new ArgumentNullException(nameof(hierarchyFlattened)); if (node == HierarchyNode.Null) throw new ArgumentNullException(nameof(node)); if (!hierarchyFlattened.Contains(in node)) throw new InvalidOperationException($"node {node.Id}:{node.Version} not found"); m_HierarchyFlattened = hierarchyFlattened; m_Node = node; m_Version = hierarchyFlattened.Version; m_Count = m_HierarchyFlattened.GetChildrenCount(in m_Node); } /// <summary> /// Gets the number of children. /// </summary> public int Count { get { ThrowIfVersionChanged(); return m_Count; } } /// <summary> /// Gets the child at the specified index. /// </summary> /// <param name="index">The children index.</param> /// <returns>The child hierarchy node.</returns> public ref readonly HierarchyFlattenedNode this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (index < 0 || index >= m_Count) throw new ArgumentOutOfRangeException(nameof(index)); ThrowIfVersionChanged(); return ref m_HierarchyFlattened[index]; } } /// <summary> /// Gets the <see cref="HierarchyNode"/> enumerator. /// </summary> /// <returns>An enumerator.</returns> public Enumerator GetEnumerator() => new Enumerator(this, m_Node); [MethodImpl(MethodImplOptions.AggressiveInlining)] void ThrowIfVersionChanged() { if (m_Version != m_HierarchyFlattened.Version) throw new InvalidOperationException("HierarchyFlattened was modified."); } /// <summary> /// An enumerator of <see cref="HierarchyNode"/>. /// </summary> public struct Enumerator { readonly HierarchyFlattenedNodeChildren m_Enumerable; readonly HierarchyFlattened m_HierarchyFlattened; readonly HierarchyNode m_Node; int m_CurrentIndex; int m_ChildrenIndex; int m_ChildrenCount; internal Enumerator(HierarchyFlattenedNodeChildren enumerable, HierarchyNode node) { m_Enumerable = enumerable; m_HierarchyFlattened = enumerable.m_HierarchyFlattened; m_Node = node; m_CurrentIndex = -1; m_ChildrenIndex = 0; m_ChildrenCount = 0; } /// <summary> /// Get the current item being enumerated. /// </summary> public ref readonly HierarchyNode Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { m_Enumerable.ThrowIfVersionChanged(); return ref HierarchyFlattenedNode.GetNodeByRef(in m_HierarchyFlattened[m_CurrentIndex]); } } /// <summary> /// Move to next iterable value. /// </summary> /// <returns><see langword="true"/> if Current item is valid, <see langword="false"/> otherwise.</returns> public bool MoveNext() { m_Enumerable.ThrowIfVersionChanged(); if (m_CurrentIndex == -1) { var index = m_HierarchyFlattened.IndexOf(in m_Node); if (index == -1) return false; ref readonly var flatNode = ref m_HierarchyFlattened[index]; if (flatNode == HierarchyFlattenedNode.Null || flatNode.ChildrenCount <= 0) return false; if (index + 1 >= m_HierarchyFlattened.Count) return false; m_CurrentIndex = index + 1; m_ChildrenIndex = 0; m_ChildrenCount = flatNode.ChildrenCount; return true; } ref readonly var currentFlatNode = ref m_HierarchyFlattened[m_CurrentIndex]; if (m_ChildrenIndex + 1 >= m_ChildrenCount || currentFlatNode.NextSiblingOffset <= 0) { return false; } else { m_CurrentIndex += currentFlatNode.NextSiblingOffset; m_ChildrenIndex++; return true; } } } } }
UnityCsReference/Modules/HierarchyCore/Managed/HierarchyFlattenedNodeChildren.cs/0
{ "file_path": "UnityCsReference/Modules/HierarchyCore/Managed/HierarchyFlattenedNodeChildren.cs", "repo_id": "UnityCsReference", "token_count": 2739 }
375
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Runtime.InteropServices; using UnityEngine.Bindings; using UnityEngine.Internal; namespace Unity.Hierarchy { /// <summary> /// Represents a hierarchy node. /// </summary> [NativeType(Header = "Modules/HierarchyCore/Public/HierarchyNode.h")] [StructLayout(LayoutKind.Sequential)] public readonly struct HierarchyNode : IEquatable<HierarchyNode> { const int k_HierarchyNodeIdNull = 0; const int k_HierarchyNodeVersionNull = 0; static readonly HierarchyNode s_Null; readonly int m_Id; readonly int m_Version; /// <summary> /// Represents a hierarchy node that is null or invalid. /// </summary> public static ref readonly HierarchyNode Null => ref s_Null; /// <summary> /// The unique identification number of the hierarchy node. /// </summary> public int Id => m_Id; /// <summary> /// The version number of the hierarchy node. /// </summary> public int Version => m_Version; /// <summary> /// Creates a hierarchy node. /// </summary> public HierarchyNode() { m_Id = k_HierarchyNodeIdNull; m_Version = k_HierarchyNodeVersionNull; } [ExcludeFromDocs] public static bool operator ==(in HierarchyNode lhs, in HierarchyNode rhs) => lhs.Id == rhs.Id && lhs.Version == rhs.Version; [ExcludeFromDocs] public static bool operator !=(in HierarchyNode lhs, in HierarchyNode rhs) => !(lhs == rhs); [ExcludeFromDocs] public bool Equals(HierarchyNode other) => other.Id == Id && other.Version == Version; [ExcludeFromDocs] public override string ToString() => $"{nameof(HierarchyNode)}({(this == Null ? nameof(Null) : $"{Id}:{Version}")})"; [ExcludeFromDocs] public override bool Equals(object obj) => obj is HierarchyNode node && Equals(node); [ExcludeFromDocs] public override int GetHashCode() => HashCode.Combine(Id, Version); } }
UnityCsReference/Modules/HierarchyCore/ScriptBindings/HierarchyNode.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/HierarchyCore/ScriptBindings/HierarchyNode.bindings.cs", "repo_id": "UnityCsReference", "token_count": 893 }
376
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Runtime.InteropServices; using UnityEngine.Bindings; using UnityEngine.Scripting; using UnityEngine.TextCore.Text; namespace UnityEngine { [NativeHeader("Modules/IMGUI/GUIStyle.bindings.h")] partial class GUIStyleState { [NativeProperty("Background", false, TargetType.Function)] public extern Texture2D background { get; set; } [NativeProperty("textColor", false, TargetType.Field)] public extern Color textColor { get; set; } [NativeProperty("scaledBackgrounds", false, TargetType.Function)] public extern Texture2D[] scaledBackgrounds { get; set; } [FreeFunction(Name = "GUIStyleState_Bindings::Init", IsThreadSafe = true)] private static extern IntPtr Init(); [FreeFunction(Name = "GUIStyleState_Bindings::Cleanup", IsThreadSafe = true, HasExplicitThis = true)] private extern void Cleanup(); internal static class BindingsMarshaller { public static IntPtr ConvertToNative(GUIStyleState guiStyleState) => guiStyleState.m_Ptr; } } [RequiredByNativeCode] [NativeHeader("Modules/IMGUI/GUIStyle.bindings.h")] [NativeHeader("IMGUIScriptingClasses.h")] partial class GUIStyle { [NativeProperty("Name", false, TargetType.Function)] internal extern string rawName { get; set; } [NativeProperty("Font", false, TargetType.Function)] public extern Font font { get; set; } [NativeProperty("m_ImagePosition", false, TargetType.Field)] public extern ImagePosition imagePosition { get; set; } [NativeProperty("m_Alignment", false, TargetType.Field)] public extern TextAnchor alignment { get; set; } [NativeProperty("m_WordWrap", false, TargetType.Field)] public extern bool wordWrap { get; set; } [NativeProperty("m_Clipping", false, TargetType.Field)] public extern TextClipping clipping { get; set; } [NativeProperty("m_ContentOffset", false, TargetType.Field)] public extern Vector2 contentOffset { get; set; } [NativeProperty("m_FixedWidth", false, TargetType.Field)] public extern float fixedWidth { get; set; } [NativeProperty("m_FixedHeight", false, TargetType.Field)] public extern float fixedHeight { get; set; } [NativeProperty("m_StretchWidth", false, TargetType.Field)] public extern bool stretchWidth { get; set; } [NativeProperty("m_StretchHeight", false, TargetType.Field)] public extern bool stretchHeight { get; set; } [NativeProperty("m_FontSize", false, TargetType.Field)] public extern int fontSize { get; set; } [NativeProperty("m_FontStyle", false, TargetType.Field)] public extern FontStyle fontStyle { get; set; } [NativeProperty("m_RichText", false, TargetType.Field)] public extern bool richText { get; set; } [Obsolete("Don't use clipOffset - put things inside BeginGroup instead. This functionality will be removed in a later version.", false)] [NativeProperty("m_ClipOffset", false, TargetType.Field)] public extern Vector2 clipOffset { get; set; } [NativeProperty("m_ClipOffset", false, TargetType.Field)] internal extern Vector2 Internal_clipOffset { get; set; } [FreeFunction(Name = "GUIStyle_Bindings::Internal_Create", IsThreadSafe = true)] private static extern IntPtr Internal_Create([Unmarshalled] GUIStyle self); [FreeFunction(Name = "GUIStyle_Bindings::Internal_Copy", IsThreadSafe = true)] private static extern IntPtr Internal_Copy([Unmarshalled] GUIStyle self, GUIStyle other); [FreeFunction(Name = "GUIStyle_Bindings::Internal_Destroy", IsThreadSafe = true)] private static extern void Internal_Destroy(IntPtr self); [FreeFunction(Name = "GUIStyle_Bindings::GetStyleStatePtr", IsThreadSafe = true, HasExplicitThis = true)] private extern IntPtr GetStyleStatePtr(int idx); [FreeFunction(Name = "GUIStyle_Bindings::AssignStyleState", HasExplicitThis = true)] private extern void AssignStyleState(int idx, IntPtr srcStyleState); [FreeFunction(Name = "GUIStyle_Bindings::GetRectOffsetPtr", HasExplicitThis = true)] private extern IntPtr GetRectOffsetPtr(int idx); [FreeFunction(Name = "GUIStyle_Bindings::AssignRectOffset", HasExplicitThis = true)] private extern void AssignRectOffset(int idx, IntPtr srcRectOffset); [FreeFunction(Name = "GUIStyle_Bindings::Internal_Draw", HasExplicitThis = true)] private extern void Internal_Draw(Rect screenRect, GUIContent content, bool isHover, bool isActive, bool on, bool hasKeyboardFocus); [FreeFunction(Name = "GUIStyle_Bindings::Internal_Draw2", HasExplicitThis = true)] private extern void Internal_Draw2(Rect position, GUIContent content, int controlID, bool on); [FreeFunction(Name = "GUIStyle_Bindings::Internal_DrawCursor", HasExplicitThis = true)] private extern void Internal_DrawCursor(Rect position, GUIContent content, Vector2 pos, Color cursorColor); [FreeFunction(Name = "GUIStyle_Bindings::Internal_DrawWithTextSelection", HasExplicitThis = true)] private extern void Internal_DrawWithTextSelection(Rect screenRect, GUIContent content, bool isHover, bool isActive, bool on, bool hasKeyboardFocus, bool drawSelectionAsComposition, Vector2 cursorFirstPosition, Vector2 cursorLastPosition, Color cursorColor, Color selectionColor); [FreeFunction(Name = "GUIStyle_Bindings::Internal_CalcSize", HasExplicitThis = true)] internal extern Vector2 Internal_CalcSize(GUIContent content); [FreeFunction(Name = "GUIStyle_Bindings::Internal_CalcSizeWithConstraints", HasExplicitThis = true)] internal extern Vector2 Internal_CalcSizeWithConstraints(GUIContent content, Vector2 maxSize); [FreeFunction(Name = "GUIStyle_Bindings::Internal_CalcHeight", HasExplicitThis = true)] private extern float Internal_CalcHeight(GUIContent content, float width); [FreeFunction(Name = "GUIStyle_Bindings::Internal_CalcMinMaxWidth", HasExplicitThis = true)] private extern Vector2 Internal_CalcMinMaxWidth(GUIContent content); [FreeFunction(Name = "GUIStyle_Bindings::Internal_DrawPrefixLabel", HasExplicitThis = true)] private extern void Internal_DrawPrefixLabel(Rect position, GUIContent content, int controlID, bool on); [FreeFunction(Name = "GUIStyle_Bindings::Internal_DrawContent", HasExplicitThis = true)] internal extern void Internal_DrawContent(Rect screenRect, GUIContent content, bool isHover, bool isActive, bool on, bool hasKeyboardFocus, bool hasTextInput, bool drawSelectionAsComposition, Vector2 cursorFirst, Vector2 cursorLast, Color cursorColor, Color selectionColor, Color imageColor, float textOffsetX, float textOffsetY, float imageTopOffset, float imageLeftOffset, bool overflowX, bool overflowY); [FreeFunction(Name = "GUIStyle_Bindings::Internal_GetTextRectOffset", HasExplicitThis = true)] internal extern Vector2 Internal_GetTextRectOffset(Rect screenRect, GUIContent content, Vector2 textSize); [FreeFunction(Name = "GUIStyle_Bindings::SetMouseTooltip")] internal static extern void SetMouseTooltip(string tooltip, Rect screenRect); [FreeFunction(Name = "GUIStyle_Bindings::IsTooltipActive")] internal static extern bool IsTooltipActive(string tooltip); [FreeFunction(Name = "GUIStyle_Bindings::Internal_GetCursorFlashOffset")] private static extern float Internal_GetCursorFlashOffset(); [FreeFunction(Name = "GUIStyle::SetDefaultFont")] internal static extern void SetDefaultFont(Font font); [FreeFunction(Name = "GUIStyle_Bindings::Internal_DestroyTextGenerator")] internal static extern void Internal_DestroyTextGenerator(int meshInfoId); [FreeFunction(Name = "GUIStyle_Bindings::Internal_CleanupAllTextGenerator")] internal static extern void Internal_CleanupAllTextGenerator(); internal static class BindingsMarshaller { public static IntPtr ConvertToNative(GUIStyle guiStyle) => guiStyle.m_Ptr; } } }
UnityCsReference/Modules/IMGUI/GUIStyle.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/IMGUI/GUIStyle.bindings.cs", "repo_id": "UnityCsReference", "token_count": 2781 }
377
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEngine.Scripting; using UnityEngine.Bindings; using UnityEngine.Experimental.Rendering; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; namespace UnityEngine { [NativeHeader("Modules/ImageConversion/ScriptBindings/ImageConversion.bindings.h")] public static class ImageConversion { public static bool EnableLegacyPngGammaRuntimeLoadBehavior { get { return GetEnableLegacyPngGammaRuntimeLoadBehavior(); } set { SetEnableLegacyPngGammaRuntimeLoadBehavior(value); } } [NativeMethod(Name = "ImageConversionBindings::GetEnableLegacyPngGammaRuntimeLoadBehavior", IsFreeFunction = true, ThrowsException = false)] extern private static bool GetEnableLegacyPngGammaRuntimeLoadBehavior(); [NativeMethod(Name = "ImageConversionBindings::SetEnableLegacyPngGammaRuntimeLoadBehavior", IsFreeFunction = true, ThrowsException = false)] extern private static void SetEnableLegacyPngGammaRuntimeLoadBehavior(bool enable); [NativeMethod(Name = "ImageConversionBindings::EncodeToTGA", IsFreeFunction = true, ThrowsException = true)] extern public static byte[] EncodeToTGA(this Texture2D tex); [NativeMethod(Name = "ImageConversionBindings::EncodeToPNG", IsFreeFunction = true, ThrowsException = true)] extern public static byte[] EncodeToPNG(this Texture2D tex); [NativeMethod(Name = "ImageConversionBindings::EncodeToJPG", IsFreeFunction = true, ThrowsException = true)] extern public static byte[] EncodeToJPG(this Texture2D tex, int quality); public static byte[] EncodeToJPG(this Texture2D tex) { return tex.EncodeToJPG(75); } [NativeMethod(Name = "ImageConversionBindings::EncodeToEXR", IsFreeFunction = true, ThrowsException = true)] extern public static byte[] EncodeToEXR(this Texture2D tex, Texture2D.EXRFlags flags); public static byte[] EncodeToEXR(this Texture2D tex) { return EncodeToEXR(tex, Texture2D.EXRFlags.None); } [NativeMethod(Name = "ImageConversionBindings::LoadImage", IsFreeFunction = true)] extern public static bool LoadImage([NotNull] this Texture2D tex, byte[] data, bool markNonReadable); public static bool LoadImage(this Texture2D tex, byte[] data) { return LoadImage(tex, data, false); } [FreeFunctionAttribute("ImageConversionBindings::EncodeArrayToTGA", true)] extern public static byte[] EncodeArrayToTGA(System.Array array, GraphicsFormat format, uint width, uint height, uint rowBytes = 0); [FreeFunctionAttribute("ImageConversionBindings::EncodeArrayToPNG", true)] extern public static byte[] EncodeArrayToPNG(System.Array array, GraphicsFormat format, uint width, uint height, uint rowBytes = 0); [FreeFunctionAttribute("ImageConversionBindings::EncodeArrayToJPG", true)] extern public static byte[] EncodeArrayToJPG(System.Array array, GraphicsFormat format, uint width, uint height, uint rowBytes = 0, int quality = 75); [FreeFunctionAttribute("ImageConversionBindings::EncodeArrayToEXR", true)] extern public static byte[] EncodeArrayToEXR(System.Array array, GraphicsFormat format, uint width, uint height, uint rowBytes = 0, Texture2D.EXRFlags flags = Texture2D.EXRFlags.None); public static NativeArray<byte> EncodeNativeArrayToTGA<T>(NativeArray<T> input, GraphicsFormat format, uint width, uint height, uint rowBytes = 0) where T : struct { unsafe { var size = input.Length * UnsafeUtility.SizeOf<T>(); var result = UnsafeEncodeNativeArrayToTGA(NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks<T>(input), ref size, format, width, height, rowBytes); var output = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(result, size, Allocator.Persistent); var safety = AtomicSafetyHandle.Create(); NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref output, safety); AtomicSafetyHandle.SetAllowReadOrWriteAccess(safety, true); return output; } } public static NativeArray<byte> EncodeNativeArrayToPNG<T>(NativeArray<T> input, GraphicsFormat format, uint width, uint height, uint rowBytes = 0) where T : struct { unsafe { var size = input.Length * UnsafeUtility.SizeOf<T>(); var result = UnsafeEncodeNativeArrayToPNG(NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks<T>(input), ref size, format, width, height, rowBytes); var output = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(result, size, Allocator.Persistent); var safety = AtomicSafetyHandle.Create(); NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref output, safety); AtomicSafetyHandle.SetAllowReadOrWriteAccess(safety, true); return output; } } public static NativeArray<byte> EncodeNativeArrayToJPG<T>(NativeArray<T> input, GraphicsFormat format, uint width, uint height, uint rowBytes = 0, int quality = 75) where T : struct { unsafe { var size = input.Length * UnsafeUtility.SizeOf<T>(); var result = UnsafeEncodeNativeArrayToJPG(NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks<T>(input), ref size, format, width, height, rowBytes, quality); var output = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(result, size, Allocator.Persistent); var safety = AtomicSafetyHandle.Create(); NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref output, safety); AtomicSafetyHandle.SetAllowReadOrWriteAccess(safety, true); return output; } } public static NativeArray<byte> EncodeNativeArrayToEXR<T>(NativeArray<T> input, GraphicsFormat format, uint width, uint height, uint rowBytes = 0, Texture2D.EXRFlags flags = Texture2D.EXRFlags.None) where T : struct { unsafe { var size = input.Length * UnsafeUtility.SizeOf<T>(); var result = UnsafeEncodeNativeArrayToEXR(NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks<T>(input), ref size, format, width, height, rowBytes, flags); var output = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(result, size, Allocator.Persistent); var safety = AtomicSafetyHandle.Create(); NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref output, safety); AtomicSafetyHandle.SetAllowReadOrWriteAccess(safety, true); return output; } } [FreeFunctionAttribute("ImageConversionBindings::UnsafeEncodeNativeArrayToTGA", true)] unsafe extern static void* UnsafeEncodeNativeArrayToTGA(void* array, ref int sizeInBytes, GraphicsFormat format, uint width, uint height, uint rowBytes = 0); [FreeFunctionAttribute("ImageConversionBindings::UnsafeEncodeNativeArrayToPNG", true)] unsafe extern static void* UnsafeEncodeNativeArrayToPNG(void* array, ref int sizeInBytes, GraphicsFormat format, uint width, uint height, uint rowBytes = 0); [FreeFunctionAttribute("ImageConversionBindings::UnsafeEncodeNativeArrayToJPG", true)] unsafe extern static void* UnsafeEncodeNativeArrayToJPG(void* array, ref int sizeInBytes, GraphicsFormat format, uint width, uint height, uint rowBytes = 0, int quality = 75); [FreeFunctionAttribute("ImageConversionBindings::UnsafeEncodeNativeArrayToEXR", true)] unsafe extern static void* UnsafeEncodeNativeArrayToEXR(void* array, ref int sizeInBytes, GraphicsFormat format, uint width, uint height, uint rowBytes = 0, Texture2D.EXRFlags flags = Texture2D.EXRFlags.None); [FreeFunctionAttribute("ImageConversionBindings::LoadImageAtPathInternal", true)] unsafe extern static void* LoadImageAtPathInternal(string path, ref int width, ref int height, ref int rowBytes, ref GraphicsFormat format); unsafe internal static NativeArray<byte> LoadImageDataAtPath(string path, ref int width, ref int height, ref int rowBytes, ref GraphicsFormat format) { var buffer = LoadImageAtPathInternal(path, ref width, ref height, ref rowBytes, ref format); var size = height * rowBytes; var output = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(buffer, size, Allocator.Persistent); var safety = AtomicSafetyHandle.Create(); NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref output, safety); AtomicSafetyHandle.SetAllowReadOrWriteAccess(safety, true); return output; } } }
UnityCsReference/Modules/ImageConversion/ScriptBindings/ImageConversion.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/ImageConversion/ScriptBindings/ImageConversion.bindings.cs", "repo_id": "UnityCsReference", "token_count": 3480 }
378
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using Unity.IntegerTime; namespace UnityEngine.InputForUI { /// <summary> /// Event provider based on InputEvent. /// Provides some but not all event types. /// Has to be used in conjunction with InputManager or InputSystem provider. /// </summary> internal class InputEventPartialProvider : IEventProviderImpl { // This provider doesn't support multiplayer private const int kDefaultPlayerId = 0; private UnityEngine.Event _ev = new UnityEngine.Event(); private OperatingSystemFamily _operatingSystemFamily; private KeyEvent.ButtonsState _keyboardButtonsState; internal EventModifiers _eventModifiers; // Use InputEvent to generate tab navigation events. // When Tab is pressed, a NavivationMove event will be emitted between the KeyEvent and the TextInputEvent. // This field is false by default because the InputSystemProvider uses a InputEventPartialProvider and // doesn't expect tab navigation events to come from it by default. internal bool _sendNavigationEventOnTabKey; public void Initialize() { _operatingSystemFamily = SystemInfo.operatingSystemFamily; _keyboardButtonsState.Reset(); _eventModifiers.Reset(); } public void Shutdown() { } public void Update() { var count = UnityEngine.Event.GetEventCount(); for (var i = 0; i < count; ++i) { UnityEngine.Event.GetEventAtIndex(i, _ev); UpdateEventModifiers(_ev); switch (_ev.type) { case EventType.KeyDown or EventType.KeyUp: if (_ev.keyCode != KeyCode.None) { // We can assume it's an event from a keyboard at this point. EventProvider.Dispatch(Event.From(ToKeyEvent(_ev))); if (_sendNavigationEventOnTabKey) SendNextOrPreviousNavigationEventOnTabKeyDownEvent(_ev); } // Trust InputEvent character, which has already been filtered else if (_ev.character != '\0') { EventProvider.Dispatch(Event.From(ToTextInputEvent(_ev))); } break; case EventType.ValidateCommand or EventType.ExecuteCommand: EventProvider.Dispatch(Event.From(ToCommandEvent(_ev))); break; } } } public void OnFocusChanged(bool focus) { if (!focus) { // Reset all key states on focus lost _eventModifiers.Reset(); _keyboardButtonsState.Reset(); } } public bool RequestCurrentState(Event.Type type) { switch (type) { case Event.Type.KeyEvent: EventProvider.Dispatch(Event.From(new KeyEvent { type = KeyEvent.Type.State, keyCode = KeyCode.None, buttonsState = _keyboardButtonsState, timestamp = (DiscreteTime)Time.timeAsRational, eventSource = EventSource.Keyboard, playerId = kDefaultPlayerId, eventModifiers = _eventModifiers })); return true; default: return false; } } // Not used public uint playerCount => 0; private DiscreteTime GetTimestamp(in UnityEngine.Event ev) { return (DiscreteTime)Time.timeAsRational; } private void UpdateEventModifiers(in UnityEngine.Event ev) { // Some event modifiers are mapped directly from IMGUI event modifiers. // But IMGUI doesn't have separate Left/Right key modifiers, so we use key codes to restore them. _eventModifiers.SetPressed(EventModifiers.Modifiers.CapsLock, ev.capsLock); _eventModifiers.SetPressed(EventModifiers.Modifiers.FunctionKey, ev.functionKey); _eventModifiers.SetPressed(EventModifiers.Modifiers.Numeric, ev.numeric); // TODO no numlock in EventModifiers? // Not every event we get here will be a key event. // Use key events to actually set modifiers as they have more fidelity (we can separate between LeftCtrl/RightCtrl). if (ev.isKey && ev.keyCode != KeyCode.None) { var pressed = ev.type == EventType.KeyDown; switch (ev.keyCode) { case KeyCode.LeftShift: _eventModifiers.SetPressed(EventModifiers.Modifiers.LeftShift, pressed); break; case KeyCode.RightShift: _eventModifiers.SetPressed(EventModifiers.Modifiers.RightShift, pressed); break; case KeyCode.LeftControl: _eventModifiers.SetPressed(EventModifiers.Modifiers.LeftCtrl, pressed); break; case KeyCode.RightControl: _eventModifiers.SetPressed(EventModifiers.Modifiers.RightCtrl, pressed); break; case KeyCode.LeftAlt: _eventModifiers.SetPressed(EventModifiers.Modifiers.LeftAlt, pressed); break; case KeyCode.RightAlt: _eventModifiers.SetPressed(EventModifiers.Modifiers.RightAlt, pressed); break; case KeyCode.LeftMeta: _eventModifiers.SetPressed(EventModifiers.Modifiers.LeftMeta, pressed); break; case KeyCode.RightMeta: _eventModifiers.SetPressed(EventModifiers.Modifiers.RightMeta, pressed); break; case KeyCode.Numlock: _eventModifiers.SetPressed(EventModifiers.Modifiers.Numlock, pressed); break; default: break; } } // We're not guaranteed to get KeyUp event during application losing focus, like try pressing Ctrl+K in editor game view, Ctrl key up will not arrive, // or some other key sequence that leads to editor loosing focus, on focus regain keys will not be reset. // But ev.modifiers are polled at a time of creation of the event and they do work correctly ... // But they are lossy and can't separate between left/right shift. // So we use some of them to _unset_ our modifiers until a better way is found. // Moreover, on MacOS we're not getting KeyDown events for modifier keys being pressed, // so we also force-set modifiers if they're not being set otherwise. if (ev.shift != _eventModifiers.IsPressed(EventModifiers.Modifiers.Shift)) _eventModifiers.SetPressed(EventModifiers.Modifiers.Shift, ev.shift); if (ev.control != _eventModifiers.IsPressed(EventModifiers.Modifiers.Ctrl)) _eventModifiers.SetPressed(EventModifiers.Modifiers.Ctrl, ev.control); if (ev.alt != _eventModifiers.IsPressed(EventModifiers.Modifiers.Alt)) _eventModifiers.SetPressed(EventModifiers.Modifiers.Alt, ev.alt); if (ev.command != _eventModifiers.IsPressed(EventModifiers.Modifiers.Meta)) _eventModifiers.SetPressed(EventModifiers.Modifiers.Meta, ev.command); } private KeyEvent ToKeyEvent(in UnityEngine.Event ev) { // handle keyboard var oldState = _keyboardButtonsState.IsPressed(ev.keyCode); var newState = ev.type == EventType.KeyDown; _keyboardButtonsState.SetPressed(ev.keyCode, newState); return new KeyEvent { type = newState ? (oldState ? KeyEvent.Type.KeyRepeated : KeyEvent.Type.KeyPressed) : KeyEvent.Type.KeyReleased, keyCode = ev.keyCode, // TODO this needs to be layout independent, expose physical keys in InputEvent buttonsState = _keyboardButtonsState, timestamp = GetTimestamp(ev), eventSource = EventSource.Keyboard, playerId = kDefaultPlayerId, eventModifiers = _eventModifiers }; } private TextInputEvent ToTextInputEvent(in UnityEngine.Event ev) { return new TextInputEvent() { character = ev.character, timestamp = GetTimestamp(ev), eventSource = EventSource.Keyboard, playerId = kDefaultPlayerId, eventModifiers = _eventModifiers }; } private void SendNextOrPreviousNavigationEventOnTabKeyDownEvent(in UnityEngine.Event ev) { if (_ev.type == EventType.KeyDown && _ev.keyCode == KeyCode.Tab) { EventProvider.Dispatch(Event.From(new NavigationEvent { type = NavigationEvent.Type.Move, direction = _ev.shift ? NavigationEvent.Direction.Previous : NavigationEvent.Direction.Next, timestamp = GetTimestamp(_ev), eventSource = EventSource.Keyboard, playerId = kDefaultPlayerId, eventModifiers = _eventModifiers })); } } private IDictionary<string, CommandEvent.Command> _IMGUICommandToInputForUICommandType = new Dictionary<string, CommandEvent.Command> { {"Cut", CommandEvent.Command.Cut}, {"Copy", CommandEvent.Command.Copy}, {"Paste", CommandEvent.Command.Paste}, {"SelectAll", CommandEvent.Command.SelectAll}, {"DeselectAll", CommandEvent.Command.DeselectAll}, {"InvertSelection", CommandEvent.Command.InvertSelection}, {"Duplicate", CommandEvent.Command.Duplicate}, {"Rename", CommandEvent.Command.Rename}, {"Delete", CommandEvent.Command.Delete}, {"SoftDelete", CommandEvent.Command.SoftDelete}, {"Find", CommandEvent.Command.Find}, {"SelectChildren", CommandEvent.Command.SelectChildren}, {"SelectPrefabRoot", CommandEvent.Command.SelectPrefabRoot}, {"UndoRedoPerformed", CommandEvent.Command.UndoRedoPerformed}, {"OnLostFocus", CommandEvent.Command.OnLostFocus}, {"NewKeyboardFocus", CommandEvent.Command.NewKeyboardFocus}, {"ModifierKeysChanged", CommandEvent.Command.ModifierKeysChanged}, {"EyeDropperUpdate", CommandEvent.Command.EyeDropperUpdate}, {"EyeDropperClicked", CommandEvent.Command.EyeDropperClicked}, {"EyeDropperCancelled", CommandEvent.Command.EyeDropperCancelled}, {"ColorPickerChanged", CommandEvent.Command.ColorPickerChanged}, {"FrameSelected", CommandEvent.Command.FrameSelected}, {"FrameSelectedWithLock", CommandEvent.Command.FrameSelectedWithLock} }; private CommandEvent ToCommandEvent(in UnityEngine.Event ev) { if (!_IMGUICommandToInputForUICommandType.TryGetValue(ev.commandName, out var cmd)) Debug.LogWarning($"Unsupported command name '{ev.commandName}'"); return new CommandEvent() { type = ev.type == EventType.ValidateCommand ? CommandEvent.Type.Validate : CommandEvent.Type.Execute, command = cmd, timestamp = GetTimestamp(ev), eventSource = EventSource.Unspecified, playerId = kDefaultPlayerId, eventModifiers = _eventModifiers }; } } }
UnityCsReference/Modules/InputForUI/Provider/InputEventPartialProvider.cs/0
{ "file_path": "UnityCsReference/Modules/InputForUI/Provider/InputEventPartialProvider.cs", "repo_id": "UnityCsReference", "token_count": 6043 }
379
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEditor.Licensing.UI.Data.Events.Base; namespace UnityEditor.Licensing.UI.Data.Events; [Serializable] class LicenseOfflineValidityEndingNotification : NotificationWithDetails<LicenseOfflineValidityEndingNotificationDetails[]> { } [Serializable] class LicenseOfflineValidityEndingNotificationDetails { public string entitlementGroupId; public string productName; public string endDate; }
UnityCsReference/Modules/Licensing/UI/Data/Events/LicenseOfflineValidityEndingNotification.cs/0
{ "file_path": "UnityCsReference/Modules/Licensing/UI/Data/Events/LicenseOfflineValidityEndingNotification.cs", "repo_id": "UnityCsReference", "token_count": 164 }
380
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor.Licensing.UI.Data.Events; using UnityEditor.Licensing.UI.Data.Events.Base; using UnityEditor.Licensing.UI.Events.Text; using UnityEditor.Licensing.UI.Helper; using UnityEngine; namespace UnityEditor.Licensing.UI.Events.Handlers; class LicenseUpdateHandler : INotificationHandler { readonly INativeApiWrapper m_NativeApiWrapper; readonly ILicenseLogger m_LicenseLogger; readonly IModalWrapper m_ModalWrapper; LicenseUpdateNotification m_Notification; public LicenseUpdateHandler(INativeApiWrapper nativeApiWrapper, ILicenseLogger licenseLogger, IModalWrapper modalWrapper, string jsonNotification) { m_NativeApiWrapper = nativeApiWrapper; m_LicenseLogger = licenseLogger; m_ModalWrapper = modalWrapper; m_Notification = m_NativeApiWrapper.CreateObjectFromJson<LicenseUpdateNotification>(jsonNotification); } public void HandleUI() { // revoke if (m_Notification.HasAnyReason(NotificationReasons.k_EntitlementGroupRevoked)) { m_ModalWrapper.ShowLicenseRevokedWindow(m_NativeApiWrapper, m_LicenseLogger, m_Notification); } // assigned if (m_Notification.HasAnyReason(NotificationReasons.k_EntitlementGroupAdded)) { LogMessage(NotificationReasons.k_EntitlementGroupAdded); } // removed if (m_Notification.HasAnyReason(NotificationReasons.k_EntitlementGroupRemoved)) { m_ModalWrapper.ShowLicenseRemovedWindow(m_NativeApiWrapper, m_LicenseLogger, m_Notification); } // returned if (m_Notification.HasAnyReason(NotificationReasons.k_EntitlementGroupReturned)) { m_ModalWrapper.ShowLicenseReturnedWindow(m_NativeApiWrapper, m_LicenseLogger, m_Notification); } } public void HandleBatchmode() { // revoke if (m_Notification.HasAnyReason(NotificationReasons.k_EntitlementGroupRevoked)) { LogMessage(NotificationReasons.k_EntitlementGroupRevoked); } // assigned if (m_Notification.HasAnyReason(NotificationReasons.k_EntitlementGroupAdded)) { LogMessage(NotificationReasons.k_EntitlementGroupAdded); } // removed if (m_Notification.HasAnyReason(NotificationReasons.k_EntitlementGroupRemoved)) { LogMessage(NotificationReasons.k_EntitlementGroupRemoved); } // returned if (m_Notification.HasAnyReason(NotificationReasons.k_EntitlementGroupReturned)) { LogMessage(NotificationReasons.k_EntitlementGroupReturned); } } void LogMessage(string reason) { var productNames = m_Notification.GetProductNamesWithReason(reason); var message = string.Empty; var tag = string.Empty; switch (reason) { case NotificationReasons.k_EntitlementGroupAdded: message = Helper.Utils.GetDescriptionMessageForProducts(productNames, LicenseTrStrings.LicenseAddedDescription, LicenseTrStrings.LicensesAddedDescription); tag = LicenseTrStrings.LicenseAddedTag; break; case NotificationReasons.k_EntitlementGroupRemoved: { message = BuildLicenseRemovedText(m_NativeApiWrapper.HasUiEntitlement(), m_Notification); tag = LicenseTrStrings.LicenseRemovedTag; break; } case NotificationReasons.k_EntitlementGroupRevoked: message = Helper.Utils.GetDescriptionMessageForProducts(productNames, LicenseTrStrings.LicenseRevokedDescription, LicenseTrStrings.LicensesRevokedDescription); tag = LicenseTrStrings.LicenseRevokedTag; break; case NotificationReasons.k_EntitlementGroupReturned: message = BuildLicenseReturnedText(m_NativeApiWrapper.HasUiEntitlement(), m_Notification); tag = LicenseTrStrings.LicenseReturnedTag; break; } m_LicenseLogger.DebugLogNoStackTrace(message, tag: tag); } public static string BuildLicenseRemovedText(bool hasUiEntitlement, LicenseUpdateNotification notification) { var productNames = notification.GetProductNamesWithReason(NotificationReasons.k_EntitlementGroupRemoved); return hasUiEntitlement ? Helper.Utils.GetDescriptionMessageForProducts(productNames, LicenseTrStrings.RemovedDescriptionOneLicenseWithUiEntitlement, LicenseTrStrings.RemovedDescriptionManyLicensesWithUiEntitlement) : Helper.Utils.GetDescriptionMessageForProducts(productNames, LicenseTrStrings.RemovedDescriptionOneLicenseNoUiEntitlement, LicenseTrStrings.RemovedDescriptionManyLicensesNoUiEntitlement); } public static string BuildLicenseReturnedText(bool hasUiEntitlement, LicenseUpdateNotification notification) { var productNames = notification.GetProductNamesWithReason(NotificationReasons.k_EntitlementGroupReturned); return hasUiEntitlement ? Helper.Utils.GetDescriptionMessageForProducts(productNames, LicenseTrStrings.ReturnedDescriptionOneLicenseWithUiEntitlement, LicenseTrStrings.ReturnedDescriptionManyLicensesWithUiEntitlement) : Helper.Utils.GetDescriptionMessageForProducts(productNames, LicenseTrStrings.ReturnedDescriptionOneLicenseNoUiEntitlement, LicenseTrStrings.ReturnedDescriptionManyLicensesNoUiEntitlement); } }
UnityCsReference/Modules/Licensing/UI/Events/Handlers/LicenseUpdateHandler.cs/0
{ "file_path": "UnityCsReference/Modules/Licensing/UI/Events/Handlers/LicenseUpdateHandler.cs", "repo_id": "UnityCsReference", "token_count": 2416 }
381
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor.Licensing.UI.Data.Events; using UnityEditor.Licensing.UI.Events.Buttons; using UnityEditor.Licensing.UI.Events.Text; using UnityEditor.Licensing.UI.Helper; namespace UnityEditor.Licensing.UI.Events.Windows; class LicenseReturnedWindow: TemplateLicenseEventWindow { public static void ShowWindow(INativeApiWrapper nativeApiWrapper, ILicenseLogger licenseLogger, object notification) { s_NativeApiWrapper = nativeApiWrapper; s_LicenseLogger = licenseLogger; s_Notification = notification as LicenseUpdateNotification; TemplateLicenseEventWindow.ShowWindow<LicenseReturnedWindow>(LicenseTrStrings.ReturnedWindowTitle, true); } public void CreateGUI() { s_Root = new LicenseReturnedWindowContents(s_NativeApiWrapper.HasUiEntitlement(), (LicenseUpdateNotification)s_Notification, new EventsButtonFactory(s_NativeApiWrapper, Close), s_LicenseLogger); rootVisualElement.Add(s_Root); } }
UnityCsReference/Modules/Licensing/UI/Events/Windows/LicenseReturnedWindow.cs/0
{ "file_path": "UnityCsReference/Modules/Licensing/UI/Events/Windows/LicenseReturnedWindow.cs", "repo_id": "UnityCsReference", "token_count": 408 }
382
// 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.Internal; using UnityEngine.Assertions; using System; using System.Collections.Generic; using System.Reflection; using JetBrains.Annotations; namespace UnityEditor { /// <summary> /// This provides Localization function. /// </summary> public static class L10n { static object lockObject = new object(); static Dictionary<Assembly, string> s_GroupNames = new Dictionary<Assembly, string>(128); private readonly struct LocKey : IEquatable<LocKey> { [NotNull] public readonly string defaultString; [NotNull] public readonly string groupName; public LocKey(string _defaultString, string _groupName) { defaultString = _defaultString ?? string.Empty; groupName = _groupName ?? string.Empty; } public bool Equals(LocKey other) { return defaultString == other.defaultString && groupName == other.groupName; } public override bool Equals(object obj) { return obj is LocKey other && Equals(other); } public override int GetHashCode() { unchecked { return (defaultString.GetHashCode() * 397) ^ groupName.GetHashCode(); } } } static Dictionary<LocKey, string> s_LocalizedStringCache = new Dictionary<LocKey, string>(10 << 10); internal static void ClearCache() { lock (lockObject) s_LocalizedStringCache.Clear(); } internal static string GetGroupName(System.Reflection.Assembly assembly) { if (assembly == null) return null; lock (lockObject) { if (!s_GroupNames.TryGetValue(assembly, out var name)) { var attrobjs = assembly.GetCustomAttributes(typeof(LocalizationAttribute), true /* inherit */); if (attrobjs.Length > 0 && attrobjs[0] != null) { var locAttr = (LocalizationAttribute)attrobjs[0]; string locGroupName = locAttr.locGroupName; if (locGroupName == null) locGroupName = assembly.GetName().Name; name = locGroupName; s_GroupNames[assembly] = name; } else { s_GroupNames[assembly] = null; } } return name; } } /// <summary> /// Get the translation for the given argument. /// <param name="str">The original string to be translated.</Param> /// </Summary> public static string Tr(string str) { return Tr(str, Assembly.GetCallingAssembly()); } internal static string Tr(string str, object context) { return Tr(str, context?.GetType().Assembly); } internal static string Tr(string str, Assembly groupAssembly) { if (!LocalizationDatabase.enableEditorLocalization) return str; if (string.IsNullOrEmpty(str)) return str; lock (lockObject) { var groupName = GetGroupName(groupAssembly); var key = new LocKey(str, groupName); if (s_LocalizedStringCache.TryGetValue(key, out var localized)) return localized; localized = (groupName != null) ? LocalizationDatabase.GetLocalizedStringWithGroupName(str, groupName) : LocalizationDatabase.GetLocalizedString(str); s_LocalizedStringCache[key] = localized; return localized; } } /// <summary> /// Get the translation array for the given argument array. /// <param name="str_list">The original strings to be translated.</Param> /// </Summary> public static string[] Tr(string[] str_list) { var res = new string[str_list.Length]; for (var i = 0; i < res.Length; ++i) res[i] = Tr(str_list[i]); return res; } /// <summary> /// Get the translation for the given argument. /// <param name="str">The original string to be translated.</Param> /// <param name="groupName">The specified group name for the translation.</Param> /// </Summary> public static string Tr(string str, string groupName) { var new_str = LocalizationDatabase.GetLocalizedStringWithGroupName(str, groupName); return new_str; } [ExcludeFromDocs] public static string TrPath(string path) { string[] separatingChars = { "/" }; var result = new System.Text.StringBuilder(256); var items = path.Split(separatingChars, System.StringSplitOptions.RemoveEmptyEntries); for (var i = 0; i < items.Length; ++i) { result.Append(Tr(items[i])); if (i < items.Length - 1) result.Append("/"); } return result.ToString(); } [ExcludeFromDocs] public static GUIContent TextContent(string text, string tooltip = null, Texture icon = null) { if (!LocalizationDatabase.enableEditorLocalization) return EditorGUIUtility.TrTextContent(text, tooltip, icon); var groupName = GetGroupName(Assembly.GetCallingAssembly()); if (groupName != null) { var new_text = LocalizationDatabase.GetLocalizedStringWithGroupName(text, groupName); var new_tooltip = LocalizationDatabase.GetLocalizedStringWithGroupName(tooltip, groupName); var gc = new GUIContent(new_text); gc.tooltip = new_tooltip; gc.image = icon; return gc; } else { return EditorGUIUtility.TrTextContent(text, tooltip, icon); } } [ExcludeFromDocs] public static GUIContent TextContent(string text, string tooltip, string iconName) { if (!LocalizationDatabase.enableEditorLocalization) return EditorGUIUtility.TrTextContent(text, tooltip, iconName); var groupName = GetGroupName(Assembly.GetCallingAssembly()); if (groupName != null) { var new_text = LocalizationDatabase.GetLocalizedStringWithGroupName(text, groupName); var new_tooltip = LocalizationDatabase.GetLocalizedStringWithGroupName(tooltip, groupName); var gc = new GUIContent(new_text); gc.tooltip = new_tooltip; gc.image = EditorGUIUtility.LoadIconRequired(iconName); return gc; } else { return EditorGUIUtility.TrTextContent(text, tooltip, iconName); } } [ExcludeFromDocs] public static GUIContent TextContent(string text, Texture icon) { if (!LocalizationDatabase.enableEditorLocalization) return EditorGUIUtility.TrTextContentWithIcon(text, icon); var groupName = GetGroupName(Assembly.GetCallingAssembly()); if (groupName != null) { var new_text = LocalizationDatabase.GetLocalizedStringWithGroupName(text, groupName); var gc = new GUIContent(new_text); gc.image = icon; return gc; } else { return EditorGUIUtility.TrTextContentWithIcon(text, icon); } } [ExcludeFromDocs] public static GUIContent TextContentWithIcon(string text, Texture icon) { if (!LocalizationDatabase.enableEditorLocalization) return EditorGUIUtility.TrTextContentWithIcon(text, icon); var groupName = GetGroupName(Assembly.GetCallingAssembly()); if (groupName != null) { var new_text = LocalizationDatabase.GetLocalizedStringWithGroupName(text, groupName); var gc = new GUIContent(new_text); gc.image = icon; return gc; } else { return EditorGUIUtility.TrTextContentWithIcon(text, icon); } } [ExcludeFromDocs] public static GUIContent TextContentWithIcon(string text, string iconName) { if (!LocalizationDatabase.enableEditorLocalization) return EditorGUIUtility.TextContentWithIcon(text, iconName); var groupName = GetGroupName(Assembly.GetCallingAssembly()); if (groupName != null) { var new_text = LocalizationDatabase.GetLocalizedStringWithGroupName(text, groupName); var gc = new GUIContent(new_text); gc.image = EditorGUIUtility.LoadIconRequired(iconName); return gc; } else { return EditorGUIUtility.TextContentWithIcon(text, iconName); } } [ExcludeFromDocs] public static GUIContent TextContentWithIcon(string text, string tooltip, string iconName) { if (!LocalizationDatabase.enableEditorLocalization) return EditorGUIUtility.TrTextContentWithIcon(text, tooltip, iconName); var groupName = GetGroupName(Assembly.GetCallingAssembly()); if (groupName != null) { var new_text = LocalizationDatabase.GetLocalizedStringWithGroupName(text, groupName); var new_tooltip = LocalizationDatabase.GetLocalizedStringWithGroupName(tooltip, groupName); var gc = new GUIContent(new_text); gc.tooltip = new_tooltip; gc.image = EditorGUIUtility.LoadIconRequired(iconName); return gc; } else { return EditorGUIUtility.TrTextContentWithIcon(text, tooltip, iconName); } } [ExcludeFromDocs] public static GUIContent TextContentWithIcon(string text, string tooltip, Texture icon) { if (!LocalizationDatabase.enableEditorLocalization) return EditorGUIUtility.TrTextContentWithIcon(text, tooltip, icon); var groupName = GetGroupName(Assembly.GetCallingAssembly()); if (groupName != null) { var new_text = LocalizationDatabase.GetLocalizedStringWithGroupName(text, groupName); var new_tooltip = LocalizationDatabase.GetLocalizedStringWithGroupName(tooltip, groupName); var gc = new GUIContent(new_text); gc.tooltip = new_tooltip; gc.image = icon; return gc; } else { return EditorGUIUtility.TrTextContentWithIcon(text, tooltip, icon); } } [ExcludeFromDocs] public static GUIContent TextContentWithIcon(string text, string tooltip, MessageType messageType) { if (!LocalizationDatabase.enableEditorLocalization) return EditorGUIUtility.TrTextContentWithIcon(text, tooltip, messageType); var groupName = GetGroupName(Assembly.GetCallingAssembly()); if (groupName != null) { var new_text = LocalizationDatabase.GetLocalizedStringWithGroupName(text, groupName); var new_tooltip = LocalizationDatabase.GetLocalizedStringWithGroupName(tooltip, groupName); var gc = new GUIContent(new_text); gc.tooltip = new_tooltip; gc.image = EditorGUIUtility.GetHelpIcon(messageType); return gc; } else { return EditorGUIUtility.TrTextContentWithIcon(text, tooltip, messageType); } } [ExcludeFromDocs] public static GUIContent TextContentWithIcon(string text, MessageType messageType) { if (!LocalizationDatabase.enableEditorLocalization) return EditorGUIUtility.TrTextContentWithIcon(text, messageType); var groupName = GetGroupName(Assembly.GetCallingAssembly()); if (groupName != null) { var new_text = LocalizationDatabase.GetLocalizedStringWithGroupName(text, groupName); var gc = new GUIContent(new_text); gc.image = EditorGUIUtility.GetHelpIcon(messageType); return gc; } else { return EditorGUIUtility.TrTextContentWithIcon(text, messageType); } } [ExcludeFromDocs] public static GUIContent IconContent(string iconName, string tooltip = null) { if (!LocalizationDatabase.enableEditorLocalization) return EditorGUIUtility.TrIconContent(iconName, tooltip); var groupName = GetGroupName(Assembly.GetCallingAssembly()); if (groupName != null) { var new_tooltip = LocalizationDatabase.GetLocalizedStringWithGroupName(tooltip, groupName); var gc = new GUIContent(); gc.tooltip = new_tooltip; gc.image = EditorGUIUtility.LoadIconRequired(iconName); return gc; } else { return EditorGUIUtility.TrIconContent(iconName, tooltip); } } [ExcludeFromDocs] public static GUIContent IconContent(Texture icon, string tooltip = null) { if (!LocalizationDatabase.enableEditorLocalization) return EditorGUIUtility.TrIconContent(icon, tooltip); var groupName = GetGroupName(Assembly.GetCallingAssembly()); if (groupName != null) { var new_tooltip = LocalizationDatabase.GetLocalizedStringWithGroupName(tooltip, groupName); var gc = new GUIContent(); gc.tooltip = new_tooltip; gc.image = icon; return gc; } else { return EditorGUIUtility.TrIconContent(icon, tooltip); } } [ExcludeFromDocs] public static GUIContent TempContent(string t) { if (!LocalizationDatabase.enableEditorLocalization) return EditorGUIUtility.TempContent(t); var groupName = GetGroupName(Assembly.GetCallingAssembly()); if (groupName != null) { var new_t = LocalizationDatabase.GetLocalizedStringWithGroupName(t, groupName); return EditorGUIUtility.TempContent(new_t); } else { return EditorGUIUtility.TempContent(t); } } [ExcludeFromDocs] public static GUIContent[] TempContent(string[] texts) { if (!LocalizationDatabase.enableEditorLocalization) return EditorGUIUtility.TempContent(texts); var groupName = GetGroupName(Assembly.GetCallingAssembly()); if (groupName != null) { GUIContent[] retval = new GUIContent[texts.Length]; for (int i = 0; i < texts.Length; i++) { var new_t = LocalizationDatabase.GetLocalizedStringWithGroupName(texts[i], groupName); retval[i] = new GUIContent(new_t); } return retval; } else { return EditorGUIUtility.TempContent(texts); } } [ExcludeFromDocs] public static GUIContent[] TempContent(string[] texts, string[] tooltips) { if (!LocalizationDatabase.enableEditorLocalization) return EditorGUIUtility.TempContent(texts, tooltips); var groupName = GetGroupName(Assembly.GetCallingAssembly()); if (groupName != null) { GUIContent[] retval = new GUIContent[texts.Length]; for (int i = 0; i < texts.Length; i++) { var new_t = LocalizationDatabase.GetLocalizedStringWithGroupName(texts[i], groupName); var new_tooltip = LocalizationDatabase.GetLocalizedStringWithGroupName(tooltips[i], groupName); retval[i] = new GUIContent(new_t, new_tooltip); } return retval; } else { return EditorGUIUtility.TempContent(texts); } } } internal static class LocalizationGroupStack { static Stack<string> s_GroupNameStack; public static void Push(string groupName) { if (s_GroupNameStack == null) s_GroupNameStack = new Stack<string>(); if (s_GroupNameStack.Count >= 16) Assert.IsTrue(false); // check the leak. s_GroupNameStack.Push(groupName); LocalizationDatabase.SetContextGroupName(groupName); } public static void Pop() { if (s_GroupNameStack == null || s_GroupNameStack.Count <= 0) Assert.IsTrue(false); s_GroupNameStack.Pop(); if (s_GroupNameStack.Count > 0) { string top = s_GroupNameStack.Peek(); LocalizationDatabase.SetContextGroupName(top); } else LocalizationDatabase.SetContextGroupName(null); } } /// <summary> /// This provides an auto dispose Localization system. /// This can be called recursively. /// </summary> public class LocalizationGroup : IDisposable { string m_LocGroupName; bool m_Pushed = false; /// <summary> /// a current group name for the localization. /// </summary> public string locGroupName { get { return m_LocGroupName; } } /// <summary> /// Default constructor. /// </summary> public LocalizationGroup() { initialize(Assembly.GetCallingAssembly()); } /// <summary> /// constructor. /// <param name="behaviour">group name will become the name of Assembly the behaviour belongs to.</param> /// </summary> public LocalizationGroup(Behaviour behaviour) { if (behaviour != null) { System.Type type = behaviour.GetType(); initialize(type.Assembly); } } /// <summary> /// constructor. /// <param name="type">group name will become the name of Assembly the type belongs to.</param> /// </summary> public LocalizationGroup(System.Type type) { initialize(type.Assembly); } /// <summary> /// constructor. /// <param name="obj">group name will become the name of Assembly the obj belongs to.</param> /// </summary> public LocalizationGroup(System.Object obj) { if (obj == null) return; initialize(obj.GetType().Assembly); } void initialize(System.Reflection.Assembly assembly) { string groupName = L10n.GetGroupName(assembly); LocalizationGroupStack.Push(groupName); m_Pushed = true; m_LocGroupName = groupName; } /// <summary> /// dispose current state. /// </summary> public void Dispose() { if (m_Pushed) LocalizationGroupStack.Pop(); } } } namespace UnityEditor.Localization.Editor { /// <summary> /// This provides Localization function for Packages. /// </summary> [System.Obsolete("Localization has been deprecated. Please use UnityEditor.L10n instead", true)] public static class Localization { /// <summary> /// get proper translation for the given argument. /// </summary> [System.Obsolete("Obsolete msg (UnityUpgradable) -> UnityEditor.L10n.Tr(*)", true)] public static string Tr(string str) { if (!LocalizationDatabase.enableEditorLocalization) return str; var assembly = Assembly.GetCallingAssembly(); object[] attrobjs = assembly.GetCustomAttributes(typeof(LocalizationAttribute), true /* inherit */); if (attrobjs != null && attrobjs.Length > 0 && attrobjs[0] != null) { LocalizationAttribute locAttr = (LocalizationAttribute)attrobjs[0]; string locGroupName = locAttr.locGroupName; if (locGroupName == null) locGroupName = assembly.GetName().Name; var new_str = LocalizationDatabase.GetLocalizedStringWithGroupName(str, locGroupName); return new_str; } return str; } } /// <summary> /// This provides an auto dispose Localization system. /// This can be called recursively. /// </summary> [System.Obsolete("LocalizationGroup has been deprecated. Please use UnityEditor.LocalizationGroup instead", true)] public class LocalizationGroup : IDisposable { string m_LocGroupName; bool m_Pushed = false; /// <summary> /// a current group name for the localization. /// </summary> public string locGroupName { get { return m_LocGroupName; } } /// <summary> /// Default constructor. /// </summary> public LocalizationGroup() { initialize(Assembly.GetCallingAssembly()); } /// <summary> /// constructor. /// <param name="behaviour">group name will become the name of Assembly the behaviour belongs to.</param> /// </summary> public LocalizationGroup(Behaviour behaviour) { if (behaviour != null) { System.Type type = behaviour.GetType(); initialize(type.Assembly); } } /// <summary> /// constructor. /// <param name="type">group name will become the name of Assembly the type belongs to.</param> /// </summary> public LocalizationGroup(System.Type type) { initialize(type.Assembly); } /// <summary> /// constructor. /// <param name="obj">group name will become the name of Assembly the obj belongs to.</param> /// </summary> public LocalizationGroup(System.Object obj) { if (obj == null) return; initialize(obj.GetType().Assembly); } void initialize(System.Reflection.Assembly assembly) { string groupName = null; object[] attrobjs = assembly.GetCustomAttributes(typeof(LocalizationAttribute), true /* inherit */); if (attrobjs != null && attrobjs.Length > 0 && attrobjs[0] != null) // focus on only the first. { LocalizationAttribute locAttr = (LocalizationAttribute)attrobjs[0]; groupName = locAttr.locGroupName; if (groupName == null) groupName = assembly.GetName().Name; } LocalizationGroupStack.Push(groupName); m_Pushed = true; m_LocGroupName = groupName; } /// <summary> /// dispose current state. /// </summary> public void Dispose() { if (m_Pushed) LocalizationGroupStack.Pop(); } } }
UnityCsReference/Modules/LocalizationEditor/LocalizationDatabase.cs/0
{ "file_path": "UnityCsReference/Modules/LocalizationEditor/LocalizationDatabase.cs", "repo_id": "UnityCsReference", "token_count": 11623 }
383
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Linq; using UnityEditor.PackageManager.Requests; using UnityEngine; namespace UnityEditor.PackageManager { public static partial class Client { public static ListRequest List(bool offlineMode, bool includeIndirectDependencies) { long operationId; var status = List(out operationId, offlineMode, includeIndirectDependencies); return new ListRequest(operationId, status); } public static ListRequest List(bool offlineMode) { return List(offlineMode, false); } public static ListRequest List() { return List(false, false); } public static AddRequest Add(string identifier) { if (string.IsNullOrWhiteSpace(identifier)) throw new ArgumentException("Package identifier cannot be null, empty or whitespace", nameof(identifier)); long operationId; var status = Add(out operationId, identifier); return new AddRequest(operationId, status); } public static AddAndRemoveRequest AddAndRemove(string[] packagesToAdd = null, string[] packagesToRemove = null) { packagesToAdd = packagesToAdd ?? Array.Empty<string>(); packagesToRemove = packagesToRemove ?? Array.Empty<string>(); if (packagesToAdd.Length == 0 && packagesToRemove.Length == 0) { throw new ArgumentException("No packages provided to add or remove"); } if (packagesToAdd.Any(string.IsNullOrWhiteSpace)) { throw new ArgumentException("Packages to add cannot contain null, empty or whitespace values", nameof(packagesToAdd)); } if (packagesToRemove.Any(string.IsNullOrWhiteSpace)) { throw new ArgumentException("Packages to remove cannot contain null, empty or whitespace values", nameof(packagesToRemove)); } long operationId; var status = AddAndRemove(out operationId, packagesToAdd, packagesToRemove); return new AddAndRemoveRequest(operationId, status); } internal static AddScopedRegistryRequest AddScopedRegistry(string registryName, string url, string[] scopes) { if (string.IsNullOrWhiteSpace(registryName)) throw new ArgumentException("Registry name cannot be null, empty or whitespace", nameof(registryName)); long operationId; var status = AddScopedRegistry(out operationId, registryName, url, scopes); return new AddScopedRegistryRequest(operationId, status); } public static ClearCacheRequest ClearCache() { long operationId; var status = ClearCache(out operationId); return new ClearCacheRequest(operationId, status); } internal static ClearCacheRootRequest ClearCacheRoot() { long operationId; var status = ClearCacheRoot(out operationId); return new ClearCacheRootRequest(operationId, status); } public static EmbedRequest Embed(string packageName) { if (string.IsNullOrWhiteSpace(packageName)) throw new ArgumentException("Package name cannot be null, empty or whitespace", nameof(packageName)); if (!PackageInfo.IsPackageRegistered(packageName)) throw new InvalidOperationException($"Cannot embed package [{packageName}] because it is not registered in the Asset Database."); long operationId; var status = Embed(out operationId, packageName); return new EmbedRequest(operationId, status); } internal static GetRegistriesRequest GetRegistries() { long operationId; var status = GetRegistries(out operationId); return new GetRegistriesRequest(operationId, status); } internal static GetCacheRootRequest GetCacheRoot() { long operationId; var status = GetCacheRoot(out operationId, ConfigSource.Unknown); return new GetCacheRootRequest(operationId, status); } internal static GetCacheRootRequest GetDefaultCacheRoot() { long operationId; var status = GetCacheRoot(out operationId, ConfigSource.Default); return new GetCacheRootRequest(operationId, status); } internal static ListBuiltInPackagesRequest ListBuiltInPackages() { long operationId; var status = ListBuiltInPackages(out operationId); return new ListBuiltInPackagesRequest(operationId, status); } public static RemoveRequest Remove(string packageName) { if (string.IsNullOrWhiteSpace(packageName)) throw new ArgumentException("Package name cannot be null, empty or whitespace", nameof(packageName)); long operationId; var status = Remove(out operationId, packageName); return new RemoveRequest(operationId, status, packageName); } internal static RemoveScopedRegistryRequest RemoveScopedRegistry(string registryId) { if (string.IsNullOrWhiteSpace(registryId)) throw new ArgumentException("Registry ID cannot be null, empty or whitespace", nameof(registryId)); long operationId; var status = RemoveScopedRegistry(out operationId, registryId); return new RemoveScopedRegistryRequest(operationId, status); } public static SearchRequest Search(string packageIdOrName, bool offlineMode) { if (string.IsNullOrWhiteSpace(packageIdOrName)) throw new ArgumentException("Package id or name cannot be null, empty or whitespace", nameof(packageIdOrName)); long operationId; var status = GetPackageInfo(out operationId, packageIdOrName, offlineMode); return new SearchRequest(operationId, status, packageIdOrName); } public static SearchRequest Search(string packageIdOrName) { return Search(packageIdOrName, false); } public static SearchRequest SearchAll(bool offlineMode) { long operationId; var status = GetPackageInfo(out operationId, string.Empty, offlineMode); return new SearchRequest(operationId, status, string.Empty); } public static SearchRequest SearchAll() { return SearchAll(false); } internal static PerformSearchRequest Search(SearchOptions options) { long operationId; var status = Search(out operationId, options); return new PerformSearchRequest(operationId, status); } internal static SetCacheRootRequest SetCacheRoot(string newPath) { long operationId; var status = SetCacheRoot(out operationId, newPath); return new SetCacheRootRequest(operationId, status); } [System.Obsolete("ResetToEditorDefaults is deprecated and will be removed in a later version.", false)] public static ResetToEditorDefaultsRequest ResetToEditorDefaults() { long operationId; var status = ResetToEditorDefaults(out operationId); return new ResetToEditorDefaultsRequest(operationId, status); } public static PackRequest Pack(string packageFolder, string targetFolder) { if (string.IsNullOrWhiteSpace(packageFolder)) throw new ArgumentException("Package folder cannot be null, empty or whitespace", nameof(packageFolder)); if (string.IsNullOrWhiteSpace(targetFolder)) throw new ArgumentException("Target folder cannot be null, empty or whitespace", nameof(targetFolder)); long operationId; var status = Pack(out operationId, packageFolder, targetFolder); return new PackRequest(operationId, status); } internal static UpdateScopedRegistryRequest UpdateScopedRegistry(string registryId, UpdateScopedRegistryOptions options) { if (string.IsNullOrWhiteSpace(registryId)) throw new ArgumentException("Registry ID cannot be null, empty or whitespace", nameof(registryId)); long operationId; var status = UpdateScopedRegistry(out operationId, registryId, options); return new UpdateScopedRegistryRequest(operationId, status); } } }
UnityCsReference/Modules/PackageManager/Editor/Managed/Client.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManager/Editor/Managed/Client.cs", "repo_id": "UnityCsReference", "token_count": 3488 }
384
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Runtime.InteropServices; using UnityEngine; using UnityEngine.Bindings; using RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute; namespace UnityEditor.PackageManager { [Serializable] [StructLayout(LayoutKind.Sequential)] [RequiredByNativeCode] [NativeAsStruct] public sealed class PackOperationResult { [SerializeField] [NativeName("tarballPath")] private string m_TarballPath = ""; internal PackOperationResult() {} public string tarballPath { get { return m_TarballPath; } } } }
UnityCsReference/Modules/PackageManager/Editor/Managed/PackOperationResult.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManager/Editor/Managed/PackOperationResult.cs", "repo_id": "UnityCsReference", "token_count": 254 }
385
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; namespace UnityEditor.PackageManager.Requests { [Serializable] public sealed partial class ClearCacheRequest : Request { /// <summary> /// Constructor to support serialization /// </summary> private ClearCacheRequest() : base() { } internal ClearCacheRequest(long operationId, NativeStatusCode initialStatus) : base(operationId, initialStatus) { } } }
UnityCsReference/Modules/PackageManager/Editor/Managed/Requests/ClearCacheRequest.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManager/Editor/Managed/Requests/ClearCacheRequest.cs", "repo_id": "UnityCsReference", "token_count": 243 }
386
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; namespace UnityEditor.PackageManager.Requests { [Serializable] internal sealed partial class UpdateScopedRegistryRequest : Request<RegistryInfo> { /// <summary> /// Constructor to support serialization /// </summary> private UpdateScopedRegistryRequest() : base() { } internal UpdateScopedRegistryRequest(long operationId, NativeStatusCode initialStatus) : base(operationId, initialStatus) { } protected override RegistryInfo GetResult() { return GetOperationData(Id); } } }
UnityCsReference/Modules/PackageManager/Editor/Managed/Requests/UpdateScopedRegistryRequest.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManager/Editor/Managed/Requests/UpdateScopedRegistryRequest.cs", "repo_id": "UnityCsReference", "token_count": 309 }
387
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; using UnityEditor.UIElements; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.PackageManager.UI.Internal { internal class ExtendableToolbarMenu : ToolbarWindowMenu, IToolbarMenuElement, IMenu { [Serializable] public new class UxmlSerializedData : ToolbarWindowMenu.UxmlSerializedData { public override object CreateInstance() => new ExtendableToolbarMenu(); } private bool m_NeedRefresh; private List<MenuDropdownItem> m_BuiltInItems; private List<MenuDropdownItem> m_DropdownItems; public DropdownMenu menu { get; private set; } private IResourceLoader m_ResourceLoader; private void ResolveDependencies() { m_ResourceLoader = ServicesContainer.instance.Resolve<IResourceLoader>(); } public ExtendableToolbarMenu() { ResolveDependencies(); m_BuiltInItems = new List<MenuDropdownItem>(); m_DropdownItems = new List<MenuDropdownItem>(); menu = new DropdownMenu(); clicked += OnClicked; m_NeedRefresh = true; } private void OnClicked() { RefreshDropdown(); this.ShowMenu(); } public void RefreshDropdown() { if (m_NeedRefresh || m_DropdownItems.Any(item => item.needRefresh)) { m_BuiltInItems.Sort(ExtensionManager.CompareExtensions); m_DropdownItems.Sort(ExtensionManager.CompareExtensions); var newDropdownMenu = new DropdownMenu(); foreach (var item in m_BuiltInItems.Concat(m_DropdownItems)) { if (item.insertSeparatorBefore) newDropdownMenu.AppendSeparator(); newDropdownMenu.AppendAction(item.text, a => { item.action?.Invoke(); }, item.statusCallback, item.userData); item.needRefresh = false; } menu = newDropdownMenu; m_NeedRefresh = false; } } public MenuDropdownItem AddBuiltInDropdownItem() { m_BuiltInItems.Add(new MenuDropdownItem()); m_NeedRefresh = true; return m_BuiltInItems.Last(); } public IMenuDropdownItem AddDropdownItem() { m_DropdownItems.Add(new MenuDropdownItem()); m_NeedRefresh = true; return m_DropdownItems.Last(); } public void Remove(MenuDropdownItem item) { m_DropdownItems.Remove(item); m_NeedRefresh = true; } public void ShowInputDropdown(InputDropdownArgs args) { var rect = GUIUtility.GUIToScreenRect(worldBound); // GUIToScreenRect calculates screen space coordinates in relation to contextual menu // which is the last active view. Since we know the exact offset of contextual menu in // relation to package manager we can compensate this by subtracting contextual menu origin. rect.y -= worldBound.yMax; var dropdown = new GenericInputDropdown(m_ResourceLoader, PackageManagerWindow.instance, args) { position = rect }; DropdownContainer.ShowDropdown(dropdown); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Extensions/ExtendableToolbarMenu.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Extensions/ExtendableToolbarMenu.cs", "repo_id": "UnityCsReference", "token_count": 1589 }
388
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.PackageManager.UI.Internal { internal class PackageExtensionAction : IPackageActionButton, IPackageActionMenu { private IWindow m_Window; private bool m_NeedRefresh; public IEnumerable<PackageActionDropdownItem> visibleDropdownItems => m_DropdownItems.Where(item => item.visible); private List<PackageActionDropdownItem> m_DropdownItems; public DropdownButton dropdownButton { get; } private Action<PackageSelectionArgs> m_Action; public Action<PackageSelectionArgs> action { get => m_Action; set { m_Action = value; if (value != null) dropdownButton.clicked += OnAction; else dropdownButton.clicked -= OnAction; } } public string text { get => dropdownButton.text; set => dropdownButton.text = value; } public string tooltip { get => dropdownButton.tooltip; set => dropdownButton.tooltip = value; } private int m_Priority; public int priority { get => m_Priority; set { if (m_Priority == value) return; m_Priority = value; onPriorityChanged?.Invoke(); } } public Texture2D icon { set => dropdownButton.SetIcon(value); } private bool m_Visible; public bool visible { get => m_Visible; set { if (m_Visible == value) return; m_Visible = value; UIUtils.SetElementDisplay(dropdownButton, value); onVisibleChanged?.Invoke(); } } public bool enabled { get => dropdownButton.enabledSelf; set => dropdownButton.SetEnabled(value); } public event Action onVisibleChanged; public event Action onPriorityChanged; public PackageExtensionAction(IWindow window) { m_Window = window; m_DropdownItems = new List<PackageActionDropdownItem>(); dropdownButton = new DropdownButton(); dropdownButton.onBeforeShowDropdown += OnBeforeShowDropdown; m_Visible = true; m_NeedRefresh = true; } private void OnBeforeShowDropdown() { if (m_NeedRefresh || m_DropdownItems.Any(d => d.needRefresh)) { m_DropdownItems.Sort(ExtensionManager.CompareExtensions); var newDropdownMenu = new DropdownMenu(); foreach (var item in visibleDropdownItems) { if (item.insertSeparatorBefore) newDropdownMenu.AppendSeparator(); newDropdownMenu.AppendAction(item.text, a => { item.action?.Invoke(m_Window.activeSelection); }, item.statusCallback); item.needRefresh = false; } dropdownButton.menu = newDropdownMenu; m_NeedRefresh = false; } } public IPackageActionDropdownItem AddDropdownItem() { var result = new PackageActionDropdownItem(); result.onVisibleChanged += RefreshDropdownIcon; m_DropdownItems.Add(result); RefreshDropdownIcon(); m_NeedRefresh = true; return result; } private void RefreshDropdownIcon() { var anyDropdownItemsVisible = visibleDropdownItems.Any(); if (anyDropdownItemsVisible && dropdownButton.menu == null) dropdownButton.menu = new DropdownMenu(); else if (!anyDropdownItemsVisible && dropdownButton.menu != null) dropdownButton.menu = null; } private void OnAction() { m_Action?.Invoke(m_Window.activeSelection); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Extensions/PackageExtensionAction.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Extensions/PackageExtensionAction.cs", "repo_id": "UnityCsReference", "token_count": 2107 }
389
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; namespace UnityEditor.PackageManager.UI.Internal { [Serializable] internal class AssetStoreDownloadInfo { public string categoryName; public string packageName; public string publisherName; public long productId; public string key; public string url; public long uploadId; public string[] destination => new string[] { publisherName.Replace(".", ""), categoryName.Replace(".", ""), packageName.Replace(".", "") }; } internal partial class JsonParser { public AssetStoreDownloadInfo ParseDownloadInfo(IDictionary<string, object> rawInfo) { if (rawInfo?.Any() != true) return null; try { var download = rawInfo.GetDictionary("result").GetDictionary("download"); return new AssetStoreDownloadInfo { categoryName = download.GetString("filename_safe_category_name"), packageName = download.GetString("filename_safe_package_name"), publisherName = download.GetString("filename_safe_publisher_name"), productId = download.GetStringAsLong("id"), key = download.GetString("key"), url = download.GetString("url"), uploadId = download.GetStringAsLong("upload_id") }; } catch (Exception) { return null; } } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/AssetStore/AssetStoreDownloadInfo.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/AssetStore/AssetStoreDownloadInfo.cs", "repo_id": "UnityCsReference", "token_count": 827 }
390
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace UnityEditor.PackageManager.UI.Internal { [Serializable] internal class AssetStoreVersionList : BaseVersionList { [SerializeField] private List<AssetStorePackageVersion> m_Versions; public override IPackageVersion latest => m_Versions.Count > 0 ? m_Versions[^1] : null; [SerializeField] private int m_ImportAvailableIndex; public override IPackageVersion importAvailable => m_ImportAvailableIndex < 0 ? null : m_Versions[m_ImportAvailableIndex]; [SerializeField] private int m_ImportedIndex; public override IPackageVersion imported => m_ImportedIndex < 0 ? null : m_Versions[m_ImportedIndex]; [SerializeField] private int m_RecommendedIndex = -1; public override IPackageVersion recommended => m_RecommendedIndex < 0 ? null : m_Versions[m_RecommendedIndex]; public override IPackageVersion primary => imported ?? importAvailable ?? latest; public AssetStoreVersionList(AssetStoreProductInfo productInfo, AssetStoreLocalInfo localInfo = null, AssetStoreImportedPackage importedPackage = null, AssetStoreUpdateInfo updateInfo = null) { m_Versions = new List<AssetStorePackageVersion>(); CreateAndAddToSortedVersions(productInfo, localInfo, importedPackage, localInfo?.uploadId); CreateAndAddToSortedVersions(productInfo, localInfo, importedPackage, importedPackage?.uploadId); CreateAndAddToSortedVersions(productInfo, localInfo, importedPackage, updateInfo?.recommendedUploadId); if (m_Versions.Count == 0) m_Versions.Add(new AssetStorePackageVersion(productInfo)); m_ImportAvailableIndex = localInfo == null ? -1 : m_Versions.FindIndex(v => v.uploadId == localInfo.uploadId); m_ImportedIndex = importedPackage == null ? -1 : m_Versions.FindIndex(v => v.uploadId == importedPackage.uploadId); m_RecommendedIndex = updateInfo == null ? -1 : m_Versions.FindIndex(v => v.uploadId == updateInfo.recommendedUploadId); } private void CreateAndAddToSortedVersions(AssetStoreProductInfo productInfo, AssetStoreLocalInfo localInfo, AssetStoreImportedPackage importedPackage, long? uploadId) { if (uploadId == null) return; var insertIndex = m_Versions.Count; for (var i = 0; i < m_Versions.Count; i++) { var version = m_Versions[i]; // We need to check duplicates here because it's possible that for localInfo, importedPackage and updateInfo to have the same uploadId if (version.uploadId == uploadId) return; if (version.uploadId < uploadId) continue; insertIndex = i; break; } m_Versions.Insert(insertIndex, new AssetStorePackageVersion ( productInfo, uploadId.Value, localInfo: uploadId == localInfo?.uploadId ? localInfo : null, importedPackage: uploadId == importedPackage?.uploadId ? importedPackage : null )); } public override IEnumerator<IPackageVersion> GetEnumerator() { return m_Versions.Cast<IPackageVersion>().GetEnumerator(); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/AssetStore/AssetStoreVersionList.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/AssetStore/AssetStoreVersionList.cs", "repo_id": "UnityCsReference", "token_count": 1412 }
391
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; namespace UnityEditor.PackageManager.UI.Internal { [Serializable] internal class PlayModeDownloadState : ScriptableSingleton<PlayModeDownloadState> { [SerializeField] public bool skipShowDialog; } [InitializeOnLoad] internal static class PlayModeDownload { private static readonly string k_DefaultGotItButtonText = L10n.Tr("Got it"); private static readonly string k_DefaultCancelButtonText = L10n.Tr("Cancel"); static PlayModeDownload() { if (!PlayModeDownloadState.instance.skipShowDialog) EditorApplication.playModeStateChanged += PlayModeStateChanged; } private static void PlayModeStateChanged(PlayModeStateChange state) { if (PlayModeDownloadState.instance.skipShowDialog) return; if (state == PlayModeStateChange.ExitingEditMode) { var assetStoreDownloadManager = ServicesContainer.instance.Resolve<IAssetStoreDownloadManager>(); var applicationProxy = ServicesContainer.instance.Resolve<IApplicationProxy>(); if (assetStoreDownloadManager.IsAnyDownloadInProgress()) { var title = L10n.Tr("Package download in progress"); var message = L10n.Tr("Please note that entering Play Mode while Unity is downloading a package may impact performance"); var accept = applicationProxy.DisplayDialog("enterPlayModeWhenDownloadInProgress", title, message, k_DefaultGotItButtonText, k_DefaultCancelButtonText); if (accept) { SetSkipDialog(); } else { EditorApplication.isPlaying = false; } } } } private static void SetSkipDialog() { PlayModeDownloadState.instance.skipShowDialog = true; // Checking for this event is no longer needed EditorApplication.playModeStateChanged -= PlayModeStateChanged; } public static bool CanBeginDownload() { if (!EditorApplication.isPlaying || PlayModeDownloadState.instance.skipShowDialog) return true; var applicationProxy = ServicesContainer.instance.Resolve<IApplicationProxy>(); var title = L10n.Tr("Play Mode in progress"); var message = L10n.Tr("Please note that making changes in the Package Manager while in Play Mode may impact performance."); var accept = applicationProxy.DisplayDialog("startDownloadWhenInPlayMode", title, message, k_DefaultGotItButtonText, k_DefaultCancelButtonText); if (accept) SetSkipDialog(); return accept; } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Common/PlayModeDownload.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Common/PlayModeDownload.cs", "repo_id": "UnityCsReference", "token_count": 1289 }
392
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Collections.Generic; using System.Linq; namespace UnityEditor.PackageManager.UI.Internal; internal class CancelDownloadAction : PackageAction { private readonly IPackageOperationDispatcher m_OperationDispatcher; private readonly IAssetStoreDownloadManager m_AssetStoreDownloadManager; private readonly IApplicationProxy m_Application; public CancelDownloadAction(IPackageOperationDispatcher operationDispatcher, IAssetStoreDownloadManager assetStoreDownloadManager, IApplicationProxy application) { m_OperationDispatcher = operationDispatcher; m_AssetStoreDownloadManager = assetStoreDownloadManager; m_Application = application; } public override Icon icon => Icon.Cancel; protected override bool TriggerActionImplementation(IList<IPackageVersion> versions) { m_OperationDispatcher.AbortDownload(versions.Select(v => v.package)); PackageManagerWindowAnalytics.SendEvent("abortDownload", versions); return true; } protected override bool TriggerActionImplementation(IPackageVersion version) { m_OperationDispatcher.AbortDownload(version.package); PackageManagerWindowAnalytics.SendEvent("abortDownload", version); return true; } public override bool IsVisible(IPackageVersion version) { if (version?.HasTag(PackageTag.LegacyFormat) != true) return false; var operation = m_AssetStoreDownloadManager.GetDownloadOperation(version.package.product?.id); return operation?.isProgressVisible == true; } public override string GetTooltip(IPackageVersion version, bool isInProgress) { return string.Format(L10n.Tr("Click to cancel the download of this {0}."), version.GetDescriptor()); } public override string GetText(IPackageVersion version, bool isInProgress) => L10n.Tr("Cancel"); public override bool IsInProgress(IPackageVersion version) => false; internal class DisableIfResumeRequestSent : DisableCondition { private static readonly string k_Tooltip = L10n.Tr("A resume request has been sent. You cannot cancel this download until it is resumed."); public DisableIfResumeRequestSent(IAssetStoreDownloadManager downloadManager, IPackageVersion version) { active = downloadManager.GetDownloadOperation(version?.package.product?.id).state == DownloadState.ResumeRequested; tooltip = k_Tooltip; } } protected override IEnumerable<DisableCondition> GetAllTemporaryDisableConditions() { yield return new DisableIfCompiling(m_Application); } protected override IEnumerable<DisableCondition> GetAllDisableConditions(IPackageVersion version) { yield return new DisableIfResumeRequestSent(m_AssetStoreDownloadManager, version); } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/Actions/CancelDownloadAction.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/Actions/CancelDownloadAction.cs", "repo_id": "UnityCsReference", "token_count": 965 }
393
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Collections.Generic; using System.Linq; namespace UnityEditor.PackageManager.UI.Internal; internal class RemoveImportedAction : PackageAction { private readonly IPackageOperationDispatcher m_OperationDispatcher; private readonly IApplicationProxy m_Application; public RemoveImportedAction(IPackageOperationDispatcher operationDispatcher, IApplicationProxy application) { m_OperationDispatcher = operationDispatcher; m_Application = application; } protected override bool TriggerActionImplementation(IPackageVersion version) { m_OperationDispatcher.RemoveImportedAssets(version.package); PackageManagerWindowAnalytics.SendEvent("removeImported", version); return true; } protected override bool TriggerActionImplementation(IList<IPackageVersion> versions) { if (!m_Application.DisplayDialog("removeMultiImported", L10n.Tr("Removing imported packages"), L10n.Tr("Remove all assets from these packages?\nAny changes you made to the assets will be lost."), L10n.Tr("Remove"), L10n.Tr("Cancel"))) return false; m_OperationDispatcher.RemoveImportedAssets(versions); PackageManagerWindowAnalytics.SendEvent("removeImported", versions); return true; } public override bool IsVisible(IPackageVersion version) { return version?.importedAssets?.Any() == true; } public override string GetTooltip(IPackageVersion version, bool isInProgress) { if (isInProgress) return k_InProgressGenericTooltip; return string.Format(L10n.Tr("Remove this {0}'s imported assets from your project."), version.GetDescriptor()); } public override string GetText(IPackageVersion version, bool isInProgress) { return L10n.Tr("Remove assets from project"); } public override string GetMultiSelectText(IPackageVersion version, bool isInProgress) { return L10n.Tr("Remove"); } public override bool IsInProgress(IPackageVersion version) => false; protected override IEnumerable<DisableCondition> GetAllTemporaryDisableConditions() { yield return new DisableIfCompiling(m_Application); } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/Actions/RemoveImportedAction.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/Actions/RemoveImportedAction.cs", "repo_id": "UnityCsReference", "token_count": 826 }
394
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEditor.PackageManager.UI.Internal { internal enum PackageProgress { None = 0, Refreshing, Downloading, Pausing, Resuming, Installing, Resetting, Removing } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/PackageProgress.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/PackageProgress.cs", "repo_id": "UnityCsReference", "token_count": 168 }
395
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace UnityEditor.PackageManager.UI.Internal; [Serializable] internal class InProjectPage : SimplePage { public const string k_Id = "InProject"; public override string id => k_Id; public override string displayName => L10n.Tr("In Project"); public override Icon icon => Icon.InProjectPage; [SerializeField] private PageFilters.Status[] m_SupportedStatusFilters = Array.Empty<PageFilters.Status>(); public override IEnumerable<PageFilters.Status> supportedStatusFilters => m_SupportedStatusFilters; public override RefreshOptions refreshOptions => RefreshOptions.UpmList | RefreshOptions.ImportedAssets | RefreshOptions.LocalInfo; public override PageCapability capability => PageCapability.DynamicEntitlementStatus | PageCapability.SupportLocalReordering; public InProjectPage(IPackageDatabase packageDatabase) : base(packageDatabase) {} public override bool ShouldInclude(IPackage package) { return package != null && !package.versions.All(v => v.HasTag(PackageTag.BuiltIn)) && (package.progress == PackageProgress.Installing || package.versions.installed != null || package.versions.Any(v => v.importedAssets?.Any() == true)); } public override string GetGroupName(IPackage package) { if (package.product != null) return L10n.Tr("Packages - Asset Store"); var version = package.versions.primary; if (version.HasTag(PackageTag.Unity)) return version.HasTag(PackageTag.Feature) ? L10n.Tr("Features") : L10n.Tr("Packages - Unity"); return string.IsNullOrEmpty(version.author) ? L10n.Tr("Packages - Other") : string.Format(L10n.Tr("Packages - {0}"), version.author); } public override bool RefreshSupportedStatusFiltersOnEntitlementPackageChange() { var oldSupportedStatusFilters = m_SupportedStatusFilters; m_SupportedStatusFilters = visualStates.Any(v => m_PackageDatabase.GetPackage(v.packageUniqueId)?.hasEntitlements == true) ? new[] { PageFilters.Status.SubscriptionBased } : Array.Empty<PageFilters.Status>(); return !m_SupportedStatusFilters.SequenceEqual(oldSupportedStatusFilters); } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Pages/PageTypes/InProjectPage.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Pages/PageTypes/InProjectPage.cs", "repo_id": "UnityCsReference", "token_count": 815 }
396
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEditorInternal; using UnityEngine; using System.Diagnostics.CodeAnalysis; using UnityEngine.Networking; namespace UnityEditor.PackageManager.UI.Internal { internal interface IApplicationProxy : IService { event Action<bool> onInternetReachabilityChange; event Action onFinishCompiling; event Action<PlayModeStateChange> onPlayModeStateChanged; event Action update; string userAppDataPath { get; } bool isInternetReachable { get; } bool isBatchMode { get; } bool isUpmRunning { get; } bool isCompiling { get; } string unityVersion { get; } string shortUnityVersion { get; } string docsUrlWithShortUnityVersion { get; } bool isDeveloperBuild { get; } void OpenURL(string url); void RevealInFinder(string path); string OpenFilePanelWithFilters(string title, string directory, string[] filters); string OpenFolderPanel(string title, string folder); bool DisplayDialog(string idForAnalytics, string title, string message, string ok, string cancel = ""); int DisplayDialogComplex(string idForAnalytics, string title, string message, string ok, string cancel, string alt); void CheckUrlValidity(string uri, Action success, Action failure); } [Serializable] [ExcludeFromCodeCoverage] internal class ApplicationProxy : BaseService<IApplicationProxy>, IApplicationProxy { [SerializeField] private bool m_CheckingCompilation = false; [SerializeField] private bool m_IsInternetReachable; [SerializeField] private double m_LastInternetCheck; public event Action<bool> onInternetReachabilityChange = delegate {}; public event Action onFinishCompiling = delegate {}; public event Action<PlayModeStateChange> onPlayModeStateChanged = delegate {}; public event Action update = delegate {}; public string userAppDataPath => InternalEditorUtility.userAppDataFolder; public bool isInternetReachable => m_IsInternetReachable; public bool isBatchMode => Application.isBatchMode; public bool isUpmRunning => !EditorApplication.isPackageManagerDisabled; public bool isCompiling { get { var result = EditorApplication.isCompiling; if (result && !m_CheckingCompilation) { EditorApplication.update -= CheckCompilationStatus; EditorApplication.update += CheckCompilationStatus; m_CheckingCompilation = true; } return result; } } public string unityVersion => Application.unityVersion; public string shortUnityVersion { get { var unityVersionParts = Application.unityVersion.Split('.'); return $"{unityVersionParts[0]}.{unityVersionParts[1]}"; } } public const string k_UnityDocsUrl = "https://docs.unity3d.com/"; public string docsUrlWithShortUnityVersion => $"{k_UnityDocsUrl}{shortUnityVersion}/"; public bool isDeveloperBuild => Unsupported.IsDeveloperBuild(); public override void OnEnable() { m_IsInternetReachable = Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork; m_LastInternetCheck = EditorApplication.timeSinceStartup; EditorApplication.update += OnUpdate; EditorApplication.playModeStateChanged += PlayModeStateChanged; } public override void OnDisable() { EditorApplication.update -= OnUpdate; EditorApplication.playModeStateChanged -= PlayModeStateChanged; } private void PlayModeStateChanged(PlayModeStateChange state) { onPlayModeStateChanged?.Invoke(state); } private void OnUpdate() { CheckInternetReachability(); update?.Invoke(); } private void CheckInternetReachability() { if (EditorApplication.timeSinceStartup - m_LastInternetCheck < 2.0) return; m_LastInternetCheck = EditorApplication.timeSinceStartup; var isInternetReachable = Application.internetReachability != NetworkReachability.NotReachable; if (isInternetReachable != m_IsInternetReachable) { m_IsInternetReachable = isInternetReachable; onInternetReachabilityChange?.Invoke(m_IsInternetReachable); } } private void CheckCompilationStatus() { if (EditorApplication.isCompiling) return; m_CheckingCompilation = false; EditorApplication.update -= CheckCompilationStatus; onFinishCompiling(); } // Eventually we want a better way of opening urls, to be further addressed in https://jira.unity3d.com/browse/PAX-2592 public void OpenURL(string url) { Application.OpenURL(url); } public void RevealInFinder(string path) { EditorUtility.RevealInFinder(path); } public string OpenFilePanelWithFilters(string title, string directory, string[] filters) { return EditorUtility.OpenFilePanelWithFilters(title, directory, filters); } public string OpenFolderPanel(string title, string folder) { return EditorUtility.OpenFolderPanel(title, folder, string.Empty); } public bool DisplayDialog(string idForAnalytics, string title, string message, string ok, string cancel = "") { var result = EditorUtility.DisplayDialog(title, message, ok, cancel); PackageManagerDialogAnalytics.SendEvent(idForAnalytics, title, message, result ? ok : cancel); return result; } public int DisplayDialogComplex(string idForAnalytics, string title, string message, string ok, string cancel, string alt) { var result = EditorUtility.DisplayDialogComplex(title, message, ok, cancel, alt); PackageManagerDialogAnalytics.SendEvent(idForAnalytics, title, message, result == 1 ? cancel : (result == 2 ? alt : ok)); return result; } public void CheckUrlValidity(string uri, Action success, Action failure) { var request = UnityWebRequest.Head(uri); var operation = request.SendWebRequest(); try { operation.completed += _ => { if (request.responseCode is >= 200 and < 300) success?.Invoke(); else failure?.Invoke(); }; } catch (InvalidOperationException e) { if (e.Message != "Insecure connection not allowed") throw e; } } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Proxies/ApplicationProxy.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Proxies/ApplicationProxy.cs", "repo_id": "UnityCsReference", "token_count": 3041 }
397
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEditor.PackageManager.Requests; namespace UnityEditor.PackageManager.UI.Internal { [Serializable] internal abstract class UpmBaseOperation : IOperation { public abstract event Action<IOperation, UIError> onOperationError; public abstract event Action<IOperation> onOperationSuccess; public abstract event Action<IOperation> onOperationFinalized; public abstract event Action<IOperation> onOperationProgress; public virtual string packageName { get { if (!string.IsNullOrEmpty(m_PackageIdOrName)) return m_PackageIdOrName.Split(new[] { '@' }, 2)[0]; return string.Empty; } } [SerializeField] protected string m_PackageIdOrName = string.Empty; public virtual string packageIdOrName => m_PackageIdOrName; public virtual long productId => 0; public string packageUniqueId => packageName; [SerializeField] protected long m_Timestamp = 0; public long timestamp { get { return m_Timestamp; } } [SerializeField] protected long m_LastSuccessTimestamp = 0; public long lastSuccessTimestamp { get { return m_LastSuccessTimestamp; } } [SerializeField] protected bool m_OfflineMode = false; public bool isOfflineMode { get { return m_OfflineMode; } } [SerializeField] protected bool m_LogErrorInConsole = false; public bool logErrorInConsole { get => m_LogErrorInConsole; set => m_LogErrorInConsole = value; } public abstract bool isInProgress { get; } public bool isInPause => false; public bool isProgressVisible => false; public bool isProgressTrackable => false; public float progressPercentage => 0; // Each type of operation can have an operation specific human readable error message. // This message should be user friendly and not as technical as the error we receive from the UPM Client. protected virtual string operationErrorMessage => string.Empty; public abstract RefreshOptions refreshOptions { get; } [NonSerialized] protected IClientProxy m_ClientProxy; [NonSerialized] protected IApplicationProxy m_Application; public void ResolveDependencies(IClientProxy clientProxy, IApplicationProxy applicationProxy) { m_ClientProxy = clientProxy; m_Application = applicationProxy; } } [Serializable] internal abstract class UpmBaseOperation<T> : UpmBaseOperation where T : Request { public override event Action<IOperation, UIError> onOperationError = delegate {}; public override event Action<IOperation> onOperationFinalized = delegate {}; public override event Action<IOperation> onOperationSuccess = delegate {}; public override event Action<IOperation> onOperationProgress = delegate {}; public virtual event Action<T> onProcessResult = delegate {}; [SerializeField] protected T m_Request; [SerializeField] protected bool m_IsCompleted; public override bool isInProgress { get { return m_Request != null && m_Request.Id != 0 && !m_IsCompleted; } } protected abstract T CreateRequest(); protected void Start() { if (isInProgress) { Debug.LogError(L10n.Tr("[Package Manager Window] Unable to start the operation again while it's in progress. " + "Please cancel the operation before re-start or wait until the operation is completed.")); return; } if (!isOfflineMode) m_Timestamp = DateTime.Now.Ticks; // Usually the timestamp for an offline operation is the last success timestamp of its online equivalence (to indicate the freshness of the data) // But in the rare case where we start an offline operation before an online one, we use the start timestamp of the editor instead of 0, // because we consider a `0` refresh timestamp as `not initialized`/`no refreshes have been done`. else if (m_Timestamp == 0) m_Timestamp = DateTime.Now.Ticks - (long)(EditorApplication.timeSinceStartup * TimeSpan.TicksPerSecond); if (!m_Application.isUpmRunning) { EditorApplication.delayCall += () => { OnError(new UIError(UIErrorCode.UpmError_ServerNotRunning, L10n.Tr("UPM server is not running"))); Cancel(); }; return; } try { m_Request = CreateRequest(); } catch (ArgumentException e) { OnError(new UIError(UIErrorCode.UpmError_ServerNotRunning, e.Message)); return; } m_IsCompleted = false; EditorApplication.update += Progress; } public void Cancel() { OnFinalize(); m_Request = null; } // Common progress code for all classes protected void Progress() { m_IsCompleted = m_Request.IsCompleted; if (m_IsCompleted) { if (m_Request.Status == StatusCode.Success) OnSuccess(); else if (m_Request.Status >= StatusCode.Failure) OnError(new UIError(m_Request.Error)); else Debug.LogError(string.Format(L10n.Tr("[Package Manager Window] Unsupported progress state {0}."), m_Request.Status)); OnFinalize(); } } public void RestoreProgress() { if (isInProgress) EditorApplication.update += Progress; } private void OnError(UIError error) { if (logErrorInConsole && !error.HasAttribute(UIError.Attribute.DetailInConsole)) { var consoleErrorMessage = operationErrorMessage ?? string.Empty; if (error.operationErrorCode >= 500 && error.operationErrorCode < 600) { if (!string.IsNullOrEmpty(consoleErrorMessage)) consoleErrorMessage += " "; consoleErrorMessage += L10n.Tr("An error occurred, likely on the server. Please try again later."); } if (!string.IsNullOrEmpty(error.message)) consoleErrorMessage += !string.IsNullOrEmpty(consoleErrorMessage) ? $"\n{error.message}" : error.message; Debug.LogError(string.Format(L10n.Tr("[Package Manager Window] {0}"), consoleErrorMessage)); error.attribute |= UIError.Attribute.DetailInConsole; } onOperationError?.Invoke(this, error); PackageManagerOperationErrorAnalytics.SendEvent(GetType().Name, error); } private void OnSuccess() { onProcessResult?.Invoke(m_Request); m_LastSuccessTimestamp = m_Timestamp; onOperationSuccess?.Invoke(this); } private void OnFinalize() { EditorApplication.update -= Progress; onOperationFinalized?.Invoke(this); onOperationError = delegate {}; onOperationFinalized = delegate {}; onOperationSuccess = delegate {}; onOperationProgress = delegate {}; onProcessResult = delegate {}; } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Upm/UpmBaseOperation.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Upm/UpmBaseOperation.cs", "repo_id": "UnityCsReference", "token_count": 3331 }
398
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEditor.Scripting.ScriptCompilation; namespace UnityEditor.PackageManager.UI.Internal { [Serializable] internal class UpmVersionList : BaseVersionList, ISerializationCallbackReceiver { [SerializeField] private List<UpmPackageVersion> m_Versions; [SerializeField] private int m_NumUnloadedVersions; public override int numUnloadedVersions => m_NumUnloadedVersions; public override IEnumerable<IPackageVersion> key { get { var installed = this.installed; var resolvedLifecycleVersion = this.resolvedLifecycleVersion; var resolvedLifecycleNextVersion = this.resolvedLifecycleNextVersion; // if installed is experimental, return all versions higher than it if (installed?.HasTag(PackageTag.Experimental) == true) return m_Versions.Where(v => v == resolvedLifecycleVersion || v == resolvedLifecycleNextVersion || v.version >= installed.version).Cast<IPackageVersion>(); var recommended = this.recommended; var keyVersions = new HashSet<IPackageVersion>(); if (recommended != null) keyVersions.Add(recommended); if (installed != null) keyVersions.Add(installed); if (resolvedLifecycleVersion != null) { keyVersions.Add(resolvedLifecycleVersion); // if the lifecycle.version is Release Candidate for this Editor version, still need to check if the release version is available // and add that if (resolvedLifecycleVersion.HasTag(PackageTag.ReleaseCandidate) && resolvedLifecycleVersion.version?.HasPreReleaseVersionTag() == true) { var latestReleasePatchOfUnityLifecycleVersion = m_Versions.LastOrDefault(v => !v.HasTag(PackageTag.PreRelease | PackageTag.ReleaseCandidate | PackageTag.Experimental) && (v.version?.IsPatchOf(resolvedLifecycleVersion.version) == true || v.version?.IsMajorMinorPatchEqualTo(resolvedLifecycleVersion.version) == true)); if (latestReleasePatchOfUnityLifecycleVersion != null) keyVersions.Add(latestReleasePatchOfUnityLifecycleVersion); } } // if no version is set but installed is release, check if there exists a patch of it to add else if (installed?.HasTag(PackageTag.Release) == true) { var latestReleasePatchOfInstalled = m_Versions.LastOrDefault(v => v.HasTag(PackageTag.Release) && v.version?.IsPatchOf(installed.version) == true); if (latestReleasePatchOfInstalled != null) keyVersions.Add(latestReleasePatchOfInstalled); } // now add the proper Pre-Release version to key versions; latestUnityLifecycleNextVersion takes priority if (resolvedLifecycleNextVersion != null) keyVersions.Add(resolvedLifecycleNextVersion); // if nextVersion is not set but the installed version is Pre-Release, add the latest iteration on it to key versions else if (installed?.HasTag(PackageTag.PreRelease) == true) { var keyPreRelease = m_Versions.LastOrDefault(v => v.HasTag(PackageTag.PreRelease) && (v.version?.IsHigherPreReleaseIterationOf(installed.version) == true)); if (keyPreRelease != null) keyVersions.Add(keyPreRelease); } if (!keyVersions.Any()) keyVersions.Add(primary); return keyVersions.OrderBy(v => v.version); } } [SerializeField] private int m_InstalledIndex; public override IPackageVersion installed => m_InstalledIndex < 0 ? null : m_Versions[m_InstalledIndex]; [SerializeField] private string m_LifecycleVersionString; private SemVersion? m_LifecycleVersion; internal string lifecycleVersionString => m_LifecycleVersionString; // the lifeCycle version from the Editor manifest, if it exists public override IPackageVersion lifecycleVersion { get { return m_LifecycleVersion == null ? null : m_Versions.FirstOrDefault(v => !v.HasTag(PackageTag.Custom | PackageTag.Local | PackageTag.Git) && v.version == m_LifecycleVersion); } } // the latest patch of lifecycle version if it exists, or the exact // version if version is set to a pre-release private IPackageVersion resolvedLifecycleVersion { get { // if it has a -pre tag in the version, it's a Release Candidate, and we must return the exact version which matches, not a // higher patch or iteration if (m_LifecycleVersion?.HasPreReleaseVersionTag() == true) return m_Versions.LastOrDefault(v => v.HasTag(PackageTag.ReleaseCandidate) && v.version == m_LifecycleVersion); // otherwise, it's either Release or tagged as Release Candidate because Editor is in Alpha or Beta, and we should // take the latest patch of it else return m_Versions.LastOrDefault(v => !v.HasTag(PackageTag.PreRelease | PackageTag.Experimental) && ((v.version?.IsPatchOf(m_LifecycleVersion) == true) || v.version == m_LifecycleVersion)); } } [SerializeField] private string m_LifecycleNextVersionString; private SemVersion? m_LifecycleNextVersion; internal string lifecycleNextVersion => m_LifecycleNextVersionString; private IPackageVersion resolvedLifecycleNextVersion { get { return m_Versions.LastOrDefault(v => v.version?.IsEqualOrPatchOf(m_LifecycleNextVersion) == true); } } public void OnBeforeSerialize() { // do nothing } public void OnAfterDeserialize() { SemVersionParser.TryParse(m_LifecycleVersionString, out m_LifecycleVersion); SemVersionParser.TryParse(m_LifecycleNextVersionString, out m_LifecycleNextVersion); } public override IPackageVersion latest => m_Versions.LastOrDefault(); public override IPackageVersion recommended { get { var installed = this.installed; if (installed != null && installed.HasTag(PackageTag.VersionLocked)) return installed; if (m_Versions.Any(v => v.availableRegistry != RegistryType.UnityRegistry)) return latest; // for Unity packages, we should only recommend versions that have been tested with the Editor; // this means they have to be either the lifecycle version or nextVersion in the manifest // lifecycle version will take precedence over nextVersion var resolvedLifecycleVersion = this.resolvedLifecycleVersion; var resolvedLifecycleNextVersion = this.resolvedLifecycleNextVersion; var recommendedLifecycleVersion = resolvedLifecycleVersion; if (installed == null) return recommendedLifecycleVersion ?? resolvedLifecycleNextVersion; // nextVersion, since in pre-release, will only be recommended if it's higher than the installed else { var useNextVersion = resolvedLifecycleNextVersion != null && resolvedLifecycleNextVersion.version > installed.version; return recommendedLifecycleVersion ?? (useNextVersion ? resolvedLifecycleNextVersion : null); } } } public override IPackageVersion primary => installed ?? recommended ?? latest; public override bool isNonLifecycleVersionInstalled => CheckIsNonLifecycleVersionInstalled(installed, lifecycleVersion); // If the user installs a local, git or embedded package with the same version string as the lifecycle version, it is consider as a non lifecycle version // We also consider that installation as the `lifecycle` version. Patches of lifecycle version are also considered lifecycle version. // We might change this behaviour later internal static bool CheckIsNonLifecycleVersionInstalled(IPackageVersion installed, IPackageVersion lifecycleVersion) { return installed != null && lifecycleVersion != null && (installed.HasTag(PackageTag.Custom | PackageTag.Git) || installed.version?.IsEqualOrPatchOf(lifecycleVersion.version) != true); } public override bool hasLifecycleVersion => m_LifecycleVersion != null || m_LifecycleNextVersion != null; public override IPackageVersion GetUpdateTarget(IPackageVersion version) { if (version?.isInstalled == true && version != recommended) return key.LastOrDefault() ?? version; return version; } // This function is only used to update the object, not to actually perform the add operation public void AddInstalledVersion(UpmPackageVersion newVersion) { if (m_InstalledIndex >= 0) { m_Versions[m_InstalledIndex].SetInstalled(false); if (m_Versions[m_InstalledIndex].HasTag(PackageTag.InstalledFromPath)) m_Versions.RemoveAt(m_InstalledIndex); } newVersion.SetInstalled(true); m_InstalledIndex = AddToSortedVersions(m_Versions, newVersion); } private static int AddToSortedVersions(List<UpmPackageVersion> sortedVersions, UpmPackageVersion versionToAdd) { for (var i = 0; i < sortedVersions.Count; ++i) { if (versionToAdd.version != null && (sortedVersions[i].version?.CompareTo(versionToAdd.version) ?? -1) < 0) continue; // note that the difference between this and the previous function is that // two upm package versions could have the the same version but different package id if (sortedVersions[i].packageId == versionToAdd.packageId) { sortedVersions[i] = versionToAdd; return i; } sortedVersions.Insert(i, versionToAdd); return i; } sortedVersions.Add(versionToAdd); return sortedVersions.Count - 1; } public UpmVersionList(PackageInfo searchInfo, PackageInfo installedInfo, RegistryType availableRegistry, Dictionary<string, PackageInfo> extraVersions = null) { // We prioritize searchInfo over installedInfo, because searchInfo is fetched from the server // while installedInfo sometimes only contain local data var mainInfo = searchInfo ?? installedInfo; if (mainInfo != null) { var mainVersion = new UpmPackageVersion(mainInfo, mainInfo == installedInfo, availableRegistry); m_Versions = mainInfo.versions.compatible.Select(v => { SemVersion? version; SemVersionParser.TryParse(v, out version); return new UpmPackageVersion(mainInfo, false, version, mainVersion.displayName, availableRegistry); }).ToList(); AddToSortedVersions(m_Versions, mainVersion); if (mainInfo != installedInfo && installedInfo != null) AddInstalledVersion(new UpmPackageVersion(installedInfo, true, availableRegistry)); } m_InstalledIndex = m_Versions.FindIndex(v => v.isInstalled); var recommendedVersion = mainInfo?.unityLifecycle?.recommendedVersion; if (string.IsNullOrEmpty(recommendedVersion)) recommendedVersion = mainInfo?.unityLifecycle?.version; SetLifecycleVersions(recommendedVersion, mainInfo?.unityLifecycle?.nextVersion); UpdateExtraPackageInfos(extraVersions, availableRegistry); m_NumUnloadedVersions = 0; } public UpmVersionList(IEnumerable<UpmPackageVersion> versions, string unityLifecycleInfoVersion = null, string unityLifecycleInfoNextVersion = null, int numUnloadedVersions = 0) { m_Versions = versions?.ToList() ?? new List<UpmPackageVersion>(); m_InstalledIndex = m_Versions.FindIndex(v => v.isInstalled); SetLifecycleVersions(unityLifecycleInfoVersion, unityLifecycleInfoNextVersion); m_NumUnloadedVersions = numUnloadedVersions; } private void UpdateExtraPackageInfos(Dictionary<string, PackageInfo> extraVersions, RegistryType availableRegistry) { if (extraVersions?.Any() != true) return; foreach (var version in m_Versions.Where(v => !v.isFullyFetched)) if (extraVersions.TryGetValue(version.version.ToString(), out var packageInfo)) version.UpdatePackageInfo(packageInfo, availableRegistry); } private void SetLifecycleVersions(string unityLifecycleInfoVersion, string unityLifecycleInfoNextVersion) { m_LifecycleVersionString = unityLifecycleInfoVersion; m_LifecycleNextVersionString = unityLifecycleInfoNextVersion; if (!string.IsNullOrEmpty(m_LifecycleVersionString)) SemVersionParser.TryParse(m_LifecycleVersionString, out m_LifecycleVersion); if (!string.IsNullOrEmpty(m_LifecycleNextVersionString)) SemVersionParser.TryParse(m_LifecycleNextVersionString, out m_LifecycleNextVersion); } public override IEnumerator<IPackageVersion> GetEnumerator() { return m_Versions.Cast<IPackageVersion>().GetEnumerator(); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Upm/UpmVersionList.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Upm/UpmVersionList.cs", "repo_id": "UnityCsReference", "token_count": 6268 }
399
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine.UIElements; namespace UnityEditor.PackageManager.UI.Internal { internal class TextFieldPlaceholder : Label { private TextField m_ParentTextField; public TextFieldPlaceholder(TextField textField, string placeholderText = null) { if (textField == null) throw new ArgumentNullException("textField"); AddToClassList("placeholder"); text = placeholderText ?? string.Empty; textField.Add(this); pickingMode = PickingMode.Ignore; UIUtils.SetElementDisplay(this, string.IsNullOrEmpty(textField.value)); textField.RegisterCallback<ChangeEvent<string>>(OnTextFieldChange); m_ParentTextField = textField; } private void OnTextFieldChange(ChangeEvent<string> evt) { UIUtils.SetElementDisplay(this, string.IsNullOrEmpty(evt.newValue)); } public void OnDisable() { m_ParentTextField.UnregisterCallback<ChangeEvent<string>>(OnTextFieldChange); m_ParentTextField.Remove(this); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/Common/TextFieldPlaceholder.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/Common/TextFieldPlaceholder.cs", "repo_id": "UnityCsReference", "token_count": 529 }
400
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEditor.PackageManager.UI.Internal { internal class CheckUpdateFoldout : MultiSelectFoldout { private readonly IAssetStoreCache m_AssetStoreCache; private readonly IBackgroundFetchHandler m_BackgroundFetchHandler; public CheckUpdateFoldout(IPageManager pageManager, IAssetStoreCache assetStoreCache, IBackgroundFetchHandler backgroundFetchHandler) : base(new DeselectAction(pageManager, "deselectCheckUpdate")) { m_AssetStoreCache = assetStoreCache; m_BackgroundFetchHandler = backgroundFetchHandler; headerTextTemplate = L10n.Tr("Checking update for {0}..."); } public override bool AddPackageVersion(IPackageVersion version) { var product = version.package.product; if(product == null) return false; if (m_AssetStoreCache.GetLocalInfo(product.id) != null && m_AssetStoreCache.GetUpdateInfo(product.id) == null) { m_BackgroundFetchHandler.PushToCheckUpdateStack(product.id); return base.AddPackageVersion(version); } return false; } } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/MultiSelect/CheckUpdateFoldout.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/MultiSelect/CheckUpdateFoldout.cs", "repo_id": "UnityCsReference", "token_count": 541 }
401
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Linq; using UnityEngine.UIElements; namespace UnityEditor.PackageManager.UI.Internal { internal class PackageDetailsBody : VisualElement { [Serializable] public new class UxmlSerializedData : VisualElement.UxmlSerializedData { public override object CreateInstance() => new PackageDetailsBody(); } private IResourceLoader m_ResourceLoader; private IPackageDatabase m_PackageDatabase; private IPackageOperationDispatcher m_OperationDispatcher; private IProjectSettingsProxy m_SettingsProxy; private IPackageManagerPrefs m_PackageManagerPrefs; private ISelectionProxy m_Selection; private IAssetDatabaseProxy m_AssetDatabase; private IApplicationProxy m_Application; private IIOProxy m_IOProxy; private IAssetStoreCache m_AssetStoreCache; private IPageManager m_PageManager; private IUpmCache m_UpmCache; private IUnityConnectProxy m_UnityConnect; private IPackageLinkFactory m_PackageLinkFactory; private PackageDetailsTabView m_TabView; private void ResolveDependencies() { var container = ServicesContainer.instance; m_ResourceLoader = container.Resolve<IResourceLoader>(); m_SettingsProxy = container.Resolve<IProjectSettingsProxy>(); m_PackageDatabase = container.Resolve<IPackageDatabase>(); m_OperationDispatcher = container.Resolve<IPackageOperationDispatcher>(); m_PackageManagerPrefs = container.Resolve<IPackageManagerPrefs>(); m_Selection = container.Resolve<ISelectionProxy>(); m_AssetDatabase = container.Resolve<IAssetDatabaseProxy>(); m_Application = container.Resolve<IApplicationProxy>(); m_IOProxy = container.Resolve<IIOProxy>(); m_AssetStoreCache = container.Resolve<IAssetStoreCache>(); m_PageManager = container.Resolve<IPageManager>(); m_UpmCache = container.Resolve<IUpmCache>(); m_UnityConnect = container.Resolve<IUnityConnectProxy>(); m_PackageLinkFactory = container.Resolve<IPackageLinkFactory>(); } private IPackageVersion m_Version; public PackageDetailsBody() { ResolveDependencies(); m_TabView = new PackageDetailsTabView() { name = "packageDetailsTabView" }; Add(m_TabView); m_TabView.onTabSwitched += OnTabSwitched; AddTabs(); } public void AddTabs() { // The following list of tabs are added in the order we want them to be shown to the users. m_TabView.AddTab(new PackageDetailsDescriptionTab(m_UnityConnect, m_ResourceLoader, m_PackageManagerPrefs)); m_TabView.AddTab(new PackageDetailsOverviewTab(m_UnityConnect, m_ResourceLoader)); m_TabView.AddTab(new PackageDetailsReleasesTab(m_UnityConnect)); m_TabView.AddTab(new PackageDetailsImportedAssetsTab(m_UnityConnect, m_IOProxy, m_PackageManagerPrefs)); m_TabView.AddTab(new PackageDetailsVersionsTab(m_UnityConnect, m_ResourceLoader, m_Application, m_PackageManagerPrefs, m_PackageDatabase, m_OperationDispatcher, m_PageManager, m_SettingsProxy, m_UpmCache, m_PackageLinkFactory)); m_TabView.AddTab(new PackageDetailsDependenciesTab(m_UnityConnect, m_ResourceLoader, m_PackageDatabase)); m_TabView.AddTab(new FeatureDependenciesTab(m_UnityConnect, m_ResourceLoader, m_PackageDatabase, m_PackageManagerPrefs, m_Application)); m_TabView.AddTab(new PackageDetailsSamplesTab(m_UnityConnect, m_ResourceLoader, m_PackageDatabase, m_Selection, m_AssetDatabase, m_Application, m_IOProxy)); m_TabView.AddTab(new PackageDetailsImagesTab(m_UnityConnect, m_AssetStoreCache)); } public void OnEnable() { m_PackageDatabase.onPackagesChanged += RefreshDependencies; m_PageManager.onVisualStateChange += RefreshVersionsHistory; // restore after domain reload m_TabView.SelectTab(m_PackageManagerPrefs.selectedPackageDetailsTabIdentifier); } public void OnDisable() { m_PackageDatabase.onPackagesChanged -= RefreshDependencies; m_PageManager.onVisualStateChange -= RefreshVersionsHistory; } public void Refresh(IPackage package, IPackageVersion version) { m_Version = version; RefreshTabs(); } private void RefreshTabs() { m_TabView.RefreshAllTabs(m_Version); } private void RefreshDependencies() { m_TabView.RefreshTabs(new[] { FeatureDependenciesTab.k_Id, PackageDetailsDependenciesTab.k_Id }, m_Version); } private void RefreshDependencies(bool _) { RefreshDependencies(); } private void RefreshDependencies(PackagesChangeArgs _) { RefreshDependencies(); } public void OnTabSwitched(PackageDetailsTabElement oldSelection, PackageDetailsTabElement newSelection) { m_PackageManagerPrefs.selectedPackageDetailsTabIdentifier = newSelection.id; } private void RefreshVersionsHistory(VisualStateChangeArgs args) { if (!args.page.isActivePage) return; var newVisualState = args.visualStates.FirstOrDefault(state => state.packageUniqueId == m_Version?.package.uniqueId); if (newVisualState?.userUnlocked == true && m_PageManager.activePage.GetSelection()?.Count == 1) m_TabView.RefreshTab(PackageDetailsVersionsTab.k_Id, m_Version); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageDetailsBody.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageDetailsBody.cs", "repo_id": "UnityCsReference", "token_count": 2442 }
402
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Linq; using UnityEngine.UIElements; namespace UnityEditor.PackageManager.UI.Internal { internal class PackageDetailsVersionsTab : PackageDetailsTabElement { public const string k_Id = "versions"; private readonly VisualElement m_Container; private readonly VisualElement m_VersionHistoryList; private readonly VisualElement m_VersionsToolbar; private readonly Button m_VersionsShowOthersButton; private IPackageVersion m_Version; private readonly IResourceLoader m_ResourceLoader; private readonly IApplicationProxy m_ApplicationProxy; private readonly IPackageManagerPrefs m_PackageManagerPrefs; private readonly IPackageDatabase m_PackageDatabase; private readonly IPackageOperationDispatcher m_OperationDispatcher; private readonly IPageManager m_PageManager; private readonly IProjectSettingsProxy m_SettingsProxy; private readonly IUpmCache m_UpmCache; private readonly IPackageLinkFactory m_PackageLinkFactory; public PackageDetailsVersionsTab(IUnityConnectProxy unityConnect, IResourceLoader resourceLoader, IApplicationProxy applicationProxy, IPackageManagerPrefs packageManagerPrefs, IPackageDatabase packageDatabase, IPackageOperationDispatcher operationDispatcher, IPageManager pageManager, IProjectSettingsProxy settingsProxy, IUpmCache upmCache, IPackageLinkFactory packageLinkFactory) : base(unityConnect) { m_Id = k_Id; m_DisplayName = L10n.Tr("Version History"); m_ResourceLoader = resourceLoader; m_ApplicationProxy = applicationProxy; m_PackageManagerPrefs = packageManagerPrefs; m_PackageDatabase = packageDatabase; m_OperationDispatcher = operationDispatcher; m_PageManager = pageManager; m_SettingsProxy = settingsProxy; m_UpmCache = upmCache; m_PackageLinkFactory = packageLinkFactory; m_Container = new VisualElement { name = "versionsTab" }; m_ContentContainer.Add(m_Container); m_VersionHistoryList = new VisualElement { name = "versionsList" }; m_Container.Add(m_VersionHistoryList); m_VersionsToolbar = new VisualElement { name = "versionsToolbar" }; m_Container.Add(m_VersionsToolbar); m_VersionsShowOthersButton = new Button { name = "versionsShowAllButton", text = L10n.Tr("See other versions") }; m_VersionsToolbar.Add(m_VersionsShowOthersButton); m_VersionsShowOthersButton.clickable.clicked += ShowOthersVersion; } private void ShowOthersVersion() { if (m_Version?.package == null) return; m_UpmCache.SetLoadAllVersions(m_Version.package.uniqueId, true); PackageManagerWindowAnalytics.SendEvent("seeAllVersions", m_Version.package.uniqueId); Refresh(m_Version); } public override bool IsValid(IPackageVersion version) { return version != null && version.HasTag(PackageTag.UpmFormat) && !version.HasTag(PackageTag.Feature | PackageTag.BuiltIn | PackageTag.Placeholder); } protected override void RefreshContent(IPackageVersion version) { m_Version = version; if (m_Version?.uniqueId != m_PackageManagerPrefs.packageDisplayedInVersionHistoryTab) { m_PackageManagerPrefs.ClearExpandedVersionHistoryItems(); m_PackageManagerPrefs.packageDisplayedInVersionHistoryTab = m_Version?.uniqueId; } foreach (var historyItem in m_VersionHistoryList.Children().OfType<PackageDetailsVersionHistoryItem>()) historyItem.StopSpinner(); m_VersionHistoryList.Clear(); var versions = m_Version?.package?.versions; if (versions == null) { UIUtils.SetElementDisplay(m_Container, false); return; } var seeVersionsToolbar = versions.numUnloadedVersions > 0 && (m_SettingsProxy.seeAllPackageVersions || m_Version.availableRegistry != RegistryType.UnityRegistry || m_Version.package.versions.installed?.HasTag(PackageTag.Experimental) == true); UIUtils.SetElementDisplay(m_VersionsToolbar, seeVersionsToolbar); var latestVersion = m_Version.package?.versions.latest; var primaryVersion = m_Version.package?.versions.primary; var multipleVersionsVisible = versions.Skip(1).Any(); foreach (var v in versions.Reverse()) { PackageAction action; if (primaryVersion?.isInstalled ?? false) { if (v == primaryVersion) action = new RemoveAction(m_OperationDispatcher, m_ApplicationProxy, m_PackageManagerPrefs, m_PackageDatabase, m_PageManager); else action = new UpdateAction(m_OperationDispatcher, m_ApplicationProxy, m_PackageDatabase, m_PageManager, false); } else action = new AddAction(m_OperationDispatcher, m_ApplicationProxy, m_PackageDatabase); var isExpanded = m_PackageManagerPrefs.IsVersionHistoryItemExpanded(v.uniqueId); var isLatest = v == latestVersion; var versionHistoryItem = new PackageDetailsVersionHistoryItem(m_ResourceLoader, m_PackageDatabase, m_OperationDispatcher, m_UpmCache, m_ApplicationProxy, m_PackageLinkFactory, v, multipleVersionsVisible, isLatest, isExpanded, action); versionHistoryItem.onToggleChanged += expanded => m_PackageManagerPrefs.SetVersionHistoryItemExpanded(versionHistoryItem.version?.uniqueId, expanded); m_VersionHistoryList.Add(versionHistoryItem); } UIUtils.SetElementDisplay(m_Container, true); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageDetailsTabs/PackageDetailsVersionsTab.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageDetailsTabs/PackageDetailsVersionsTab.cs", "repo_id": "UnityCsReference", "token_count": 2741 }
403
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEditor; namespace UnityEditorInternal { [ExcludeFromPreset] public sealed class PackageManifestImporter : AssetImporter { } public sealed class PackageManifest : TextAsset { private PackageManifest() {} private PackageManifest(string text) {} } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageManifest.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageManifest.cs", "repo_id": "UnityCsReference", "token_count": 157 }
404
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; using UnityEngine.UIElements; namespace UnityEditor.PackageManager.UI.Internal { internal class ScopedRegistriesSettings : VisualElement { private static readonly string k_AddNewScopedRegistryText = L10n.Tr("New Scoped Registry"); private const string k_SelectedRegistryClass = "selectedRegistry"; private const string k_NewRegistryClass = "newRegistry"; private const string k_SelectedScopeClass = "selectedScope"; private string k_EditRegistryName = L10n.Tr("Edit Registry Name"); private string k_EditRegistryUrl = L10n.Tr("Edit Registry URL"); private string k_EditRegistryScopes = L10n.Tr("Edit Registry Scopes"); private string k_AddNewRegistryDraft = L10n.Tr("Add New Registry Draft"); private string k_RemoveRegistry = L10n.Tr("Remove registry"); private string k_RegistrySelectionChange = L10n.Tr("Registry Selection Change"); [Serializable] internal new class UxmlSerializedData : VisualElement.UxmlSerializedData { public override object CreateInstance() => new ScopedRegistriesSettings(); } private Dictionary<string, Label> m_RegistryLabels = new Dictionary<string, Label>(); internal IReadOnlyDictionary<string, Label> registryLabels => m_RegistryLabels; private Label m_NewScopedRegistryLabel; internal RegistryInfoDraft draft => m_SettingsProxy.registryInfoDraft; private IResourceLoader m_ResourceLoader; private IProjectSettingsProxy m_SettingsProxy; private IApplicationProxy m_ApplicationProxy; private IUpmCache m_UpmCache; private IUpmRegistryClient m_UpmRegistryClient; private void ResolveDependencies() { var container = ServicesContainer.instance; m_ResourceLoader = container.Resolve<IResourceLoader>(); m_SettingsProxy = container.Resolve<IProjectSettingsProxy>(); m_ApplicationProxy = container.Resolve<IApplicationProxy>(); m_UpmCache = container.Resolve<IUpmCache>(); m_UpmRegistryClient = container.Resolve<IUpmRegistryClient>(); } public ScopedRegistriesSettings() { ResolveDependencies(); var root = m_ResourceLoader.GetTemplate("ScopedRegistriesSettings.uxml"); Add(root); cache = new VisualElementCache(root); scopedRegistriesInfoBox.Q<Button>().clickable.clicked += () => { m_ApplicationProxy.OpenURL($"https://docs.unity3d.com/{m_ApplicationProxy.shortUnityVersion}/Documentation/Manual/upm-scoped.html#security"); }; applyRegistriesButton.clickable.clicked += ApplyChanges; revertRegistriesButton.clickable.clicked += RevertChanges; registryNameTextField.RegisterValueChangedCallback(OnRegistryNameChanged); registryUrlTextField.RegisterValueChangedCallback(OnRegistryUrlChanged); m_NewScopedRegistryLabel = new Label(); m_NewScopedRegistryLabel.AddToClassList(k_NewRegistryClass); m_NewScopedRegistryLabel.OnLeftClick(() => OnRegistryLabelClicked(null)); addRegistryButton.clickable.clicked += AddRegistryClicked; removeRegistryButton.clickable.clicked += RemoveRegistryClicked; addScopeButton.clickable.clicked += AddScopeClicked; removeScopeButton.clickable.clicked += RemoveScopeClicked; m_UpmRegistryClient.onRegistriesModified += OnRegistriesModified; m_UpmRegistryClient.onRegistryOperationError += OnRegistryOperationError; Undo.undoRedoEvent -= OnUndoRedoPerformed; Undo.undoRedoEvent += OnUndoRedoPerformed; // on domain reload, it's not guaranteed that the settings have // reloaded the draft object yet- need to wait and do this when // initialization has finished if (draft.IsReady()) { UpdateRegistryList(); UpdateRegistryDetails(); } else { m_SettingsProxy.onInitializationFinished += OnSettingsInitialized; } } private void OnUndoRedoPerformed(in UndoRedoInfo info) { if (EditorWindow.HasOpenInstances<ProjectSettingsWindow>()) { draft.SetModifiedAfterUndo(); // check if the old state makes sense- does it still exist in the list of registries // if not, put it into a new draft, since it was deleted at some point prior if (!string.IsNullOrEmpty(draft.original?.name) && !m_SettingsProxy.scopedRegistries.Any(a => a.name == draft.original?.name)) { draft.SetOriginalRegistryInfo(null, true); m_SettingsProxy.isUserAddingNewScopedRegistry = true; } UpdateRegistryList(); UpdateRegistryDetails(); RefreshScopeSelection(); RefreshButtonState(draft.original == null, draft.hasUnsavedChanges); } } private void OnSettingsInitialized() { UpdateRegistryList(); UpdateRegistryDetails(); } private void AddRegistryClicked() { if (draft.original == null) return; if (!ShowUnsavedChangesDialog()) return; draft.RegisterWithOriginalOnUndo(k_AddNewRegistryDraft); m_SettingsProxy.isUserAddingNewScopedRegistry = true; draft.SetOriginalRegistryInfo(null); UpdateRegistryList(); UpdateRegistryDetails(); registryNameTextField.Q("unity-text-input").Focus(); } private bool AnyPackageInstalledFromRegistry(string registryName) { if (string.IsNullOrEmpty(registryName)) return false; if (!m_UpmCache.installedPackageInfos.Any()) m_UpmCache.SetInstalledPackageInfos(PackageInfo.GetAllRegisteredPackages()); return m_UpmCache.installedPackageInfos.Any(p => p.registry?.name == registryName); } private void RemoveRegistryClicked() { if (draft.original != null) { string message; if (AnyPackageInstalledFromRegistry(draft.original.name)) { message = L10n.Tr("There are packages in your project that are from this scoped registry, please remove them before removing the scoped registry."); m_ApplicationProxy.DisplayDialog("cannotDeleteScopedRegistry", L10n.Tr("Cannot delete scoped registry"), message, L10n.Tr("Ok")); return; } message = L10n.Tr("You are about to delete a scoped registry, are you sure you want to continue?"); var deleteRegistry = m_ApplicationProxy.isBatchMode || m_ApplicationProxy.DisplayDialog("deleteScopedRegistry", L10n.Tr("Deleting a scoped registry"), message, L10n.Tr("Ok"), L10n.Tr("Cancel")); if (deleteRegistry) { draft.RegisterWithOriginalOnUndo(k_RemoveRegistry); m_UpmRegistryClient.RemoveRegistry(draft.original.name); } } else { if (!ShowUnsavedChangesDialog()) return; m_SettingsProxy.isUserAddingNewScopedRegistry = false; RevertChanges(); } } private void AddScopeClicked() { var textField = CreateScopeTextField(); scopesList.Add(textField); textField.Q("unity-text-input").Focus(); removeScopeButton.SetEnabled(scopesList.childCount > 1); OnRegistryScopesChanged(); RefreshScopeSelection(); } private void RemoveScopeClicked() { if (scopesList.childCount <= 1) return; if (draft.selectedScopeIndex >= 0 && draft.selectedScopeIndex < scopesList.childCount) { scopesList.RemoveAt(draft.selectedScopeIndex); removeScopeButton.SetEnabled(scopesList.childCount > 1); OnRegistryScopesChanged(); RefreshScopeSelection(); } } private void ApplyChanges() { if (draft.isUrlOrScopesUpdated && AnyPackageInstalledFromRegistry(draft.original.name) && !m_ApplicationProxy.DisplayDialog("updateScopedRegistry", L10n.Tr("Updating a scoped registry"), L10n.Tr("There are packages in your project that are from this scoped registry, updating the URL or the scopes could result in errors in your project. Are you sure you want to continue?"), L10n.Tr("Ok"), L10n.Tr("Cancel"))) return; if (draft.Validate()) { var scopes = draft.sanitizedScopes.ToArray(); if (draft.original != null) m_UpmRegistryClient.UpdateRegistry(draft.original.name, draft.name, draft.url, scopes); else m_UpmRegistryClient.AddRegistry(draft.name, draft.url, scopes); } else { RefreshErrorBox(); } } private void RevertChanges() { draft.RevertChanges(); if (draft.original != null) GetRegistryLabel(draft.original.name).text = draft.original.name; else { m_NewScopedRegistryLabel.text = k_AddNewScopedRegistryText; var lastScopedRegistry = m_SettingsProxy.scopedRegistries.LastOrDefault(); if (lastScopedRegistry != null) { m_SettingsProxy.SelectRegistry(lastScopedRegistry.name); m_SettingsProxy.isUserAddingNewScopedRegistry = false; } } UpdateRegistryList(); UpdateRegistryDetails(); } private Label GetRegistryLabel(string registryName) { if (string.IsNullOrEmpty(registryName)) return m_NewScopedRegistryLabel; return m_RegistryLabels.TryGetValue(registryName, out var label) ? label : null; } private void OnRegistryNameChanged(ChangeEvent<string> evt) { draft.RegisterOnUndo(k_EditRegistryName); draft.name = evt.newValue; RefreshButtonState(draft.original == null, draft.hasUnsavedChanges); RefreshSelectedLabelText(); } private void OnRegistryUrlChanged(ChangeEvent<string> evt) { draft.RegisterOnUndo(k_EditRegistryUrl); draft.url = evt.newValue; RefreshButtonState(draft.original == null, draft.hasUnsavedChanges); RefreshSelectedLabelText(); } private void OnRegistryScopesChanged(ChangeEvent<string> evt = null) { draft.RegisterOnUndo(k_EditRegistryScopes); draft.SetScopes(scopesList.Children().Cast<TextField>().Select(textField => textField.value)); RefreshButtonState(draft.original == null, draft.hasUnsavedChanges); RefreshSelectedLabelText(); } private void OnRegistryLabelClicked(string registryName) { if (draft.original?.name == registryName) return; if (!ShowUnsavedChangesDialog()) return; draft.RegisterWithOriginalOnUndo(k_RegistrySelectionChange); GetRegistryLabel(draft.original?.name)?.EnableInClassList(k_SelectedRegistryClass, false); m_SettingsProxy.SelectRegistry(registryName); GetRegistryLabel(registryName).EnableInClassList(k_SelectedRegistryClass, true); removeRegistryButton.SetEnabled(canEditSelectedRegistry); UpdateRegistryDetails(); } private void OnRegistriesModified() { UpdateRegistryList(); UpdateRegistryDetails(); RefreshScopeSelection(); } private void OnRegistryOperationError(string name, UIError error) { if ((draft.original?.name ?? draft.name) == name) { draft.errorMessage = error.message; RefreshErrorBox(); } } // Returns false if there are unsaved changes and the user choose to cancel the current operation // Otherwise returns true private bool ShowUnsavedChangesDialog() { if (!draft.hasUnsavedChanges) return true; var discardChanges = m_ApplicationProxy.isBatchMode || m_ApplicationProxy.DisplayDialog("discardUnsavedRegistryChanges", L10n.Tr("Discard unsaved changes"), L10n.Tr("You have unsaved changes which would be lost if you continue this operation. Do you want to continue and discard unsaved changes?"), L10n.Tr("Continue"), L10n.Tr("Cancel")); if (discardChanges) RevertChanges(); return discardChanges; } private TextField CreateScopeTextField(string scope = null) { var scopeTextField = new TextField(); if (!string.IsNullOrEmpty(scope)) scopeTextField.value = scope; scopeTextField.RegisterValueChangedCallback(OnRegistryScopesChanged); scopeTextField.RegisterCallback<FocusEvent>(OnScopeTextFieldFocus); return scopeTextField; } private void OnScopeTextFieldFocus(FocusEvent e) { var textField = e.target as TextField; if (textField != null) { var previousIndex = draft.selectedScopeIndex; var scopeIndex = textField.parent.IndexOf(textField); if (previousIndex == scopeIndex) return; draft.selectedScopeIndex = scopeIndex; RefreshScopeSelection(); } } private void RefreshScopeSelection() { var selectedIndex = draft.selectedScopeIndex; selectedIndex = Math.Min(Math.Max(0, selectedIndex), scopesList.childCount - 1); draft.selectedScopeIndex = selectedIndex; for (var i = 0; i < scopesList.childCount; i++) scopesList[i].EnableInClassList(k_SelectedScopeClass, i == selectedIndex); } internal void UpdateRegistryList() { registriesList.Clear(); m_RegistryLabels.Clear(); foreach (var registryInfo in m_SettingsProxy.scopedRegistries) { if (m_RegistryLabels.ContainsKey(registryInfo.name)) { // Workaround because registries are keyed by registryInfo.name rather than registryInfo.id. // Without this, the UI just fails to render and there's an uncaught // ArgumentException error logged in the console due to a duplicate key error // thrown by m_RegistryLabels.Add below. UnityEngine.Debug.LogWarning( string.Format( L10n.Tr("Unable to display a scoped registry named {0} defined in a UPM configuration file: an existing scoped registry has the same name in your project manifest. Rename one of the conflicting scoped registries if you want to see them all in the Scoped Registry list."), registryInfo.name) ); continue; } var label = new Label(registryInfo.name); label.OnLeftClick(() => OnRegistryLabelClicked(registryInfo.name)); var isSelected = draft.original?.name == registryInfo.name; if (isSelected) { label.AddToClassList(k_SelectedRegistryClass); label.text = GetLabelText(draft); } m_RegistryLabels.Add(registryInfo.name, label); registriesList.Add(label); } // draft.original == null indicates the new scoped registry is selected no matter what reason is it // isUserAddingNewScopedRegistry: the user specifically added the `adding new scoped registry` label. The value would be false // when you open the settings page with 0 scoped registry in the manifest.json var showAddNewScopedRegistryLabel = draft.original == null || m_SettingsProxy.isUserAddingNewScopedRegistry; if (showAddNewScopedRegistryLabel) { m_NewScopedRegistryLabel.EnableInClassList(k_SelectedRegistryClass, draft.original == null); m_NewScopedRegistryLabel.text = GetLabelText(draft, true); registriesList.Add(m_NewScopedRegistryLabel); } addRegistryButton.SetEnabled(!showAddNewScopedRegistryLabel); removeRegistryButton.SetEnabled(registriesList.childCount > 0 && !(showAddNewScopedRegistryLabel && registriesList.childCount == 1) && canEditSelectedRegistry); } private void UpdateRegistryDetails() { registriesRightContainer.SetEnabled(canEditSelectedRegistry); registryNameTextField.SetValueWithoutNotify(draft.name ?? string.Empty); registryUrlTextField.SetValueWithoutNotify(draft.url ?? string.Empty); scopesList.Clear(); foreach (var scope in draft.scopes) scopesList.Add(CreateScopeTextField(scope)); if (scopesList.childCount > 0) RefreshScopeSelection(); removeScopeButton.SetEnabled(scopesList.childCount > 1); RefreshButtonText(draft.original == null); RefreshButtonState(draft.original == null, draft.hasUnsavedChanges); RefreshErrorBox(); } private void RefreshButtonText(bool isAddNewRegistry) { revertRegistriesButton.text = isAddNewRegistry ? L10n.Tr("Cancel") : L10n.Tr("Revert"); applyRegistriesButton.text = isAddNewRegistry ? L10n.Tr("Save") : L10n.Tr("Apply"); } private void RefreshButtonState(bool isAddNewRegistry, bool hasUnsavedChanges) { revertRegistriesButton.SetEnabled(isAddNewRegistry || hasUnsavedChanges); applyRegistriesButton.SetEnabled(hasUnsavedChanges); } private void RefreshSelectedLabelText() { var label = draft.original != null ? GetRegistryLabel(draft.original.name) : m_NewScopedRegistryLabel; if (label != null) label.text = GetLabelText(draft); } private void RefreshErrorBox() { scopedRegistryErrorBox.text = draft.errorMessage; UIUtils.SetElementDisplay(scopedRegistryErrorBox, !string.IsNullOrEmpty(scopedRegistryErrorBox.text)); } private static string GetLabelText(RegistryInfoDraft draft, bool newScopedRegistry = false) { if (newScopedRegistry || draft.original == null) return (draft.original != null || string.IsNullOrEmpty(draft.name)) ? k_AddNewScopedRegistryText : $"* {draft.name}"; else return draft.hasUnsavedChanges ? $"* {draft.name}" : draft.name; } private VisualElementCache cache { get; set; } private bool canEditSelectedRegistry { get { // Disallow editing existing registries defined in User or Global UPM configuration files for now return draft.original == null || draft.original.configSource == ConfigSource.Project; } } private HelpBox scopedRegistriesInfoBox => cache.Get<HelpBox>("scopedRegistriesInfoBox"); private HelpBox scopedRegistryErrorBox => cache.Get<HelpBox>("scopedRegistryErrorBox"); internal VisualElement registriesList => cache.Get<VisualElement>("registriesList"); internal VisualElement registriesRightContainer => cache.Get<VisualElement>("registriesRightContainer"); internal TextField registryNameTextField => cache.Get<TextField>("registryNameTextField"); internal TextField registryUrlTextField => cache.Get<TextField>("registryUrlTextField"); internal VisualElement scopesList => cache.Get<VisualElement>("scopesList"); internal Button addRegistryButton => cache.Get<Button>("addRegistryButton"); internal Button removeRegistryButton => cache.Get<Button>("removeRegistryButton"); internal Button addScopeButton => cache.Get<Button>("addScopeButton"); internal Button removeScopeButton => cache.Get<Button>("removeScopeButton"); internal Button revertRegistriesButton => cache.Get<Button>("revertRegistriesButton"); internal Button applyRegistriesButton => cache.Get<Button>("applyRegistriesButton"); } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/ScopedRegistriesSettings.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/ScopedRegistriesSettings.cs", "repo_id": "UnityCsReference", "token_count": 9442 }
405
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Linq; using UnityEngine.UIElements; namespace UnityEditor.PackageManager.UI.Internal { internal class PackageToolBarError : VisualElement { public PackageToolBarError() { } public bool Refresh(IPackage package, IPackageVersion version) { var operationError = version?.errors?.FirstOrDefault(e => e.HasAttribute(UIError.Attribute.Clearable)) ?? package?.errors?.FirstOrDefault(e => e.HasAttribute(UIError.Attribute.Clearable)); if (operationError == null) { ClearError(); return false; } SetError(operationError.message, operationError.HasAttribute(UIError.Attribute.Warning) ? PackageState.Warning : PackageState.Error); return true; } private void SetError(string message, PackageState state) { switch (state) { case PackageState.Error: AddToClassList("error"); break; case PackageState.Warning: AddToClassList("warning"); break; default: break; } tooltip = message; UIUtils.SetElementDisplay(this, true); } private void ClearError() { UIUtils.SetElementDisplay(this, false); tooltip = string.Empty; ClearClassList(); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/ToolBar/PackageToolBarError.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/ToolBar/PackageToolBarError.cs", "repo_id": "UnityCsReference", "token_count": 770 }
406
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using System.Collections.Generic; using UnityEditorInternal; using UnityEditor.EditorTools; namespace UnityEditor { class CollisionModuleUI : ModuleUI { enum CollisionTypes { Plane = 0, World = 1 } enum CollisionModes { Mode3D = 0, Mode2D = 1 } enum PlaneVizType { Grid, Solid } SerializedProperty m_Type; SerializedProperty m_Planes; SerializedMinMaxCurve m_Dampen; SerializedMinMaxCurve m_Bounce; SerializedMinMaxCurve m_LifetimeLossOnCollision; SerializedProperty m_MinKillSpeed; SerializedProperty m_MaxKillSpeed; SerializedProperty m_RadiusScale; SerializedProperty m_CollidesWith; SerializedProperty m_CollidesWithDynamic; SerializedProperty m_MaxCollisionShapes; SerializedProperty m_Quality; SerializedProperty m_VoxelSize; SerializedProperty m_CollisionMessages; SerializedProperty m_CollisionMode; SerializedProperty m_ColliderForce; SerializedProperty m_MultiplyColliderForceByCollisionAngle; SerializedProperty m_MultiplyColliderForceByParticleSpeed; SerializedProperty m_MultiplyColliderForceByParticleSize; ReorderableList m_PlanesList; static PlaneVizType m_PlaneVisualizationType = PlaneVizType.Solid; static float m_ScaleGrid = 1.0f; static bool s_VisualizeBounds = false; internal static PrefColor s_CollisionBoundsColor = new PrefColor("Particle System/Collision Bounds", 0.0f, 1.0f, 0.0f, 1.0f); static readonly string s_UndoCollisionPlaneString = L10n.Tr("Modified Collision Plane Transform"); class Texts { public GUIContent lifetimeLoss = EditorGUIUtility.TrTextContent("Lifetime Loss", "When particle collides, it will lose this fraction of its Start Lifetime"); public GUIContent planes = EditorGUIUtility.TrTextContent("Planes", "Planes are defined by assigning a reference to a transform. This transform can be any transform in the scene and can be animated. Multiple planes can be used. Note: the Y-axis is used as the plane normal."); public GUIContent createPlane = EditorGUIUtility.TrTextContent("", "Create an empty GameObject and assign it as a plane."); public GUIContent minKillSpeed = EditorGUIUtility.TrTextContent("Min Kill Speed", "When particles collide and their speed is lower than this value, they are killed."); public GUIContent maxKillSpeed = EditorGUIUtility.TrTextContent("Max Kill Speed", "When particles collide and their speed is higher than this value, they are killed."); public GUIContent dampen = EditorGUIUtility.TrTextContent("Dampen", "When particle collides, it will lose this fraction of its speed. Unless this is set to 0.0, particle will become slower after collision."); public GUIContent bounce = EditorGUIUtility.TrTextContent("Bounce", "When particle collides, the bounce is scaled with this value. The bounce is the upwards motion in the plane normal direction."); public GUIContent radiusScale = EditorGUIUtility.TrTextContent("Radius Scale", "Scale particle bounds by this amount to get more precise collisions."); public GUIContent visualization = EditorGUIUtility.TrTextContent("Visualization", "Only used for visualizing the planes: Wireframe or Solid."); public GUIContent scalePlane = EditorGUIUtility.TrTextContent("Scale Plane", "Resizes the visualization planes."); public GUIContent visualizeBounds = EditorGUIUtility.TrTextContent("Visualize Bounds", "Render the collision bounds of the particles."); public GUIContent collidesWith = EditorGUIUtility.TrTextContent("Collides With", "Collides the particles with colliders included in the layermask."); public GUIContent collidesWithDynamic = EditorGUIUtility.TrTextContent("Enable Dynamic Colliders", "Should particles collide with dynamic objects?"); public GUIContent maxCollisionShapes = EditorGUIUtility.TrTextContent("Max Collision Shapes", "How many collision shapes can be considered for particle collisions. Excess shapes will be ignored. Terrains take priority."); public GUIContent quality = EditorGUIUtility.TrTextContent("Collision Quality", "Quality of world collisions. Medium and low quality are approximate and may leak particles."); public GUIContent voxelSize = EditorGUIUtility.TrTextContent("Voxel Size", "Size of voxels in the collision cache. Smaller values improve accuracy but require higher memory usage and are less efficient."); public GUIContent collisionMessages = EditorGUIUtility.TrTextContent("Send Collision Messages", "Send collision callback messages."); public GUIContent collisionType = EditorGUIUtility.TrTextContent("Type", "Collide with a list of Planes, or the Physics World."); public GUIContent collisionMode = EditorGUIUtility.TrTextContent("Mode", "Use 3D Physics or 2D Physics."); public GUIContent colliderForce = EditorGUIUtility.TrTextContent("Collider Force", "Control the strength of particle forces on colliders."); public GUIContent multiplyColliderForceByCollisionAngle = EditorGUIUtility.TrTextContent("Multiply by Collision Angle", "Should the force be proportional to the angle of the particle collision? A particle collision directly along the collision normal produces all the specified force whilst collisions away from the collision normal produce less force."); public GUIContent multiplyColliderForceByParticleSpeed = EditorGUIUtility.TrTextContent("Multiply by Particle Speed", "Should the force be proportional to the particle speed?"); public GUIContent multiplyColliderForceByParticleSize = EditorGUIUtility.TrTextContent("Multiply by Particle Size", "Should the force be proportional to the particle size?"); public GUIContent sceneTools = EditorGUIUtility.TrTextContent("Scene Tools"); public GUIContent[] collisionTypes = new GUIContent[] { EditorGUIUtility.TrTextContent("Planes"), EditorGUIUtility.TrTextContent("World") }; public GUIContent[] collisionModes = new GUIContent[] { EditorGUIUtility.TrTextContent("3D"), EditorGUIUtility.TrTextContent("2D") }; public GUIContent[] qualitySettings = new GUIContent[] { EditorGUIUtility.TrTextContent("High"), EditorGUIUtility.TrTextContent("Medium (Static Colliders)"), EditorGUIUtility.TrTextContent("Low (Static Colliders)") }; public GUIContent[] planeVizTypes = new GUIContent[] { EditorGUIUtility.TrTextContent("Grid"), EditorGUIUtility.TrTextContent("Solid") }; } private static Texts s_Texts; [EditorTool("Transform Collider", typeof(ParticleSystem))] class CollisionModuleTransformTool : EditorTool { private HashSet<Transform> m_ScenePlanes = new HashSet<Transform>(); private static Transform s_SelectedTransform; // static to ensure there is only one selected Transform across multiple particle systems public override GUIContent toolbarIcon { get { return EditorGUIUtility.TrIconContent("TransformTool", "Collision module plane editing mode."); } } public override bool IsAvailable() { foreach (var t in targets) { var ps = t as ParticleSystem; if (ps == null) continue; var collision = ps.collision; if (collision.enabled && collision.type == ParticleSystemCollisionType.Planes) return true; } return false; } public override void OnToolGUI(EditorWindow window) { var firstTransform = SyncScenePlanes(); if (m_ScenePlanes.Count == 0) return; // Clear invalid selection (ie when selecting other system) if (s_SelectedTransform != null) { if (!m_ScenePlanes.Contains(s_SelectedTransform)) s_SelectedTransform = null; } // Always try to select first collider if no selection exists if (s_SelectedTransform == null) s_SelectedTransform = firstTransform; Event evt = Event.current; Color origCol = Handles.color; Color col = new Color(1, 1, 1, 0.5F); bool isPlaying = EditorApplication.isPlaying; foreach (var transform in m_ScenePlanes) { Vector3 position = transform.position; Quaternion rotation = transform.rotation; Vector3 right = rotation * Vector3.right; Vector3 up = rotation * Vector3.up; Vector3 forward = rotation * Vector3.forward; bool isPlayingAndStatic = isPlaying && transform.gameObject.isStatic; if (ReferenceEquals(s_SelectedTransform, transform)) { EditorGUI.BeginChangeCheck(); var newPosition = transform.position; var newRotation = transform.rotation; using (new EditorGUI.DisabledScope(isPlayingAndStatic)) { if (isPlayingAndStatic) Handles.ShowSceneViewLabel(position, Handles.s_StaticLabel); Handles.TransformHandle(ref newPosition, ref newRotation); } if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(transform, s_UndoCollisionPlaneString); transform.position = newPosition; transform.rotation = newRotation; ParticleSystemEditorUtils.PerformCompleteResimulation(); } } else { float handleSize = HandleUtility.GetHandleSize(position) * 0.6f; 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; Handles.FreeMoveHandle(position, handleSize, Vector3.zero, Handles.RectangleHandleCap); // Detect selected plane (similar to TreeEditor) if (oldEventType == EventType.MouseDown && evt.type == EventType.Used) { s_SelectedTransform = transform; oldEventType = EventType.Used; GUIUtility.hotControl = 0; // Reset hot control or the FreeMoveHandle will prevent input to the new Handles. (case 873514) } } Handles.color = col; Color color = Handles.s_ColliderHandleColor * 0.9f; if (isPlayingAndStatic) color.a *= 0.2f; if (m_PlaneVisualizationType == PlaneVizType.Grid) { DrawGrid(position, right, forward, up, color); } else { DrawSolidPlane(position, rotation, color, Color.yellow); } } Handles.color = origCol; } private Transform SyncScenePlanes() { m_ScenePlanes.Clear(); Transform firstTransform = null; foreach (var t in targets) { var ps = t as ParticleSystem; if (ps == null) continue; if (ps.collision.type != ParticleSystemCollisionType.Planes) continue; for (int planeIndex = 0; planeIndex < ps.collision.planeCount; planeIndex++) { var transform = ps.collision.GetPlane(planeIndex); if (transform != null) { m_ScenePlanes.Add(transform); if (firstTransform == null) firstTransform = transform; } } } return firstTransform; } } public CollisionModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "CollisionModule", displayName) { m_ToolTip = "Allows you to specify multiple collision planes that the particle can collide with."; } private bool editingPlanes { get { return EditorToolManager.activeTool is CollisionModuleTransformTool; } } protected override void Init() { // Already initialized? if (m_Type != null) return; if (s_Texts == null) s_Texts = new Texts(); m_Type = GetProperty("type"); m_Planes = GetProperty("m_Planes"); m_Dampen = new SerializedMinMaxCurve(this, s_Texts.dampen, "m_Dampen"); m_Dampen.m_AllowCurves = false; m_Bounce = new SerializedMinMaxCurve(this, s_Texts.bounce, "m_Bounce"); m_Bounce.m_AllowCurves = false; m_LifetimeLossOnCollision = new SerializedMinMaxCurve(this, s_Texts.lifetimeLoss, "m_EnergyLossOnCollision"); m_LifetimeLossOnCollision.m_AllowCurves = false; m_MinKillSpeed = GetProperty("minKillSpeed"); m_MaxKillSpeed = GetProperty("maxKillSpeed"); m_RadiusScale = GetProperty("radiusScale"); m_PlaneVisualizationType = (PlaneVizType)EditorPrefs.GetInt("PlaneColisionVizType", (int)PlaneVizType.Solid); m_ScaleGrid = EditorPrefs.GetFloat("ScalePlaneColision", 1f); s_VisualizeBounds = EditorPrefs.GetBool("VisualizeBounds", false); m_CollidesWith = GetProperty("collidesWith"); m_CollidesWithDynamic = GetProperty("collidesWithDynamic"); m_MaxCollisionShapes = GetProperty("maxCollisionShapes"); m_Quality = GetProperty("quality"); m_VoxelSize = GetProperty("voxelSize"); m_CollisionMessages = GetProperty("collisionMessages"); m_CollisionMode = GetProperty("collisionMode"); m_ColliderForce = GetProperty("colliderForce"); m_MultiplyColliderForceByCollisionAngle = GetProperty("multiplyColliderForceByCollisionAngle"); m_MultiplyColliderForceByParticleSpeed = GetProperty("multiplyColliderForceByParticleSpeed"); m_MultiplyColliderForceByParticleSize = GetProperty("multiplyColliderForceByParticleSize"); m_PlanesList = new ReorderableList(m_Planes.m_SerializedObject, m_Planes, true, false, true, true); m_PlanesList.headerHeight = 0; m_PlanesList.drawElementCallback = DrawPlaneElementCallback; m_PlanesList.elementHeight = kReorderableListElementHeight; m_PlanesList.onAddCallback = OnAddPlaneElementCallback; } override public void OnInspectorGUI(InitialModuleUI initial) { EditorGUI.BeginChangeCheck(); CollisionTypes type = (CollisionTypes)GUIPopup(s_Texts.collisionType, m_Type, s_Texts.collisionTypes); if (EditorGUI.EndChangeCheck()) ToolManager.RefreshAvailableTools(); if (type == CollisionTypes.Plane) DoListOfPlanesGUI(); else GUIPopup(s_Texts.collisionMode, m_CollisionMode, s_Texts.collisionModes); GUIMinMaxCurve(s_Texts.dampen, m_Dampen); GUIMinMaxCurve(s_Texts.bounce, m_Bounce); GUIMinMaxCurve(s_Texts.lifetimeLoss, m_LifetimeLossOnCollision); GUIFloat(s_Texts.minKillSpeed, m_MinKillSpeed); GUIFloat(s_Texts.maxKillSpeed, m_MaxKillSpeed); GUIFloat(s_Texts.radiusScale, m_RadiusScale); if (type == CollisionTypes.World) { GUIPopup(s_Texts.quality, m_Quality, s_Texts.qualitySettings); EditorGUI.indentLevel++; GUILayerMask(s_Texts.collidesWith, m_CollidesWith); GUIInt(s_Texts.maxCollisionShapes, m_MaxCollisionShapes); if (m_Quality.intValue == 0) GUIToggle(s_Texts.collidesWithDynamic, m_CollidesWithDynamic); else GUIFloat(s_Texts.voxelSize, m_VoxelSize); EditorGUI.indentLevel--; GUIFloat(s_Texts.colliderForce, m_ColliderForce); EditorGUI.indentLevel++; GUIToggle(s_Texts.multiplyColliderForceByCollisionAngle, m_MultiplyColliderForceByCollisionAngle); GUIToggle(s_Texts.multiplyColliderForceByParticleSpeed, m_MultiplyColliderForceByParticleSpeed); GUIToggle(s_Texts.multiplyColliderForceByParticleSize, m_MultiplyColliderForceByParticleSize); EditorGUI.indentLevel--; } GUIToggle(s_Texts.collisionMessages, m_CollisionMessages); if (EditorGUIUtility.comparisonViewMode == EditorGUIUtility.ComparisonViewMode.None) { EditorGUILayout.BeginVertical("GroupBox"); if (type == CollisionTypes.Plane) { var editorTools = new List<EditorTool>(2); EditorToolManager.GetComponentTools(x => x.GetEditor<EditorTool>() is CollisionModuleTransformTool, editorTools, true); GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(s_Texts.sceneTools, ParticleSystemStyles.Get().label, ParticleSystemStyles.Get().label); EditorGUILayout.EditorToolbar(editorTools); GUILayout.EndHorizontal(); EditorGUILayout.Space(); EditorGUI.BeginChangeCheck(); m_PlaneVisualizationType = (PlaneVizType)GUIPopup(s_Texts.visualization, (int)m_PlaneVisualizationType, s_Texts.planeVizTypes); if (EditorGUI.EndChangeCheck()) { EditorPrefs.SetInt("PlaneColisionVizType", (int)m_PlaneVisualizationType); } EditorGUI.BeginChangeCheck(); m_ScaleGrid = GUIFloat(s_Texts.scalePlane, m_ScaleGrid, "f2"); if (EditorGUI.EndChangeCheck()) { m_ScaleGrid = Mathf.Max(0f, m_ScaleGrid); EditorPrefs.SetFloat("ScalePlaneColision", m_ScaleGrid); } } else { GUILayout.Label(s_Texts.sceneTools, ParticleSystemStyles.Get().label); } EditorGUI.BeginChangeCheck(); s_VisualizeBounds = GUIToggle(s_Texts.visualizeBounds, s_VisualizeBounds); if (EditorGUI.EndChangeCheck()) EditorPrefs.SetBool("VisualizeBounds", s_VisualizeBounds); EditorGUILayout.EndVertical(); } } private static GameObject CreateEmptyGameObject(string name, ParticleSystem parentOfGameObject) { GameObject go = new GameObject(name); if (go) { if (parentOfGameObject) go.transform.parent = parentOfGameObject.transform; Undo.RegisterCreatedObjectUndo(go, "Created `" + name + "`"); return go; } return null; } private void DoListOfPlanesGUI() { // only allow editing in single edit mode if (m_ParticleSystemUI.multiEdit) { EditorGUILayout.HelpBox("Trigger editing is only available when editing a single Particle System", MessageType.Info, true); return; } m_PlanesList.DoLayoutList(); } void OnAddPlaneElementCallback(ReorderableList list) { int index = m_Planes.arraySize; m_Planes.InsertArrayElementAtIndex(index); m_Planes.GetArrayElementAtIndex(index).objectReferenceValue = null; } void DrawPlaneElementCallback(Rect rect, int index, bool isActive, bool isFocused) { rect.height = kSingleLineHeight; var plane = m_Planes.GetArrayElementAtIndex(index); Rect objectRect = new Rect(rect.x, rect.y, rect.width - EditorGUI.kSpacing - ParticleSystemStyles.Get().plus.fixedWidth, rect.height); GUIObject(objectRect, GUIContent.none, plane, null); if (plane.objectReferenceValue == null) { Rect buttonRect = new Rect(objectRect.xMax + EditorGUI.kSpacing, rect.y + 4, ParticleSystemStyles.Get().plus.fixedWidth, rect.height); if (GUI.Button(buttonRect, s_Texts.createPlane, ParticleSystemStyles.Get().plus)) { GameObject go = CreateEmptyGameObject("Plane Transform " + (index + 1), m_ParticleSystemUI.m_ParticleSystems[0]); go.transform.localPosition = new Vector3(0, 0, 10 + index); // ensure each plane is not at same pos go.transform.localEulerAngles = (new Vector3(-90, 0, 0)); // make the plane normal point towards the forward axis of the particle system plane.objectReferenceValue = go.GetComponent<Transform>(); } } } override public void OnSceneViewGUI() { RenderCollisionBounds(); } void RenderCollisionBounds() { if (s_VisualizeBounds == false) return; Color oldColor = Handles.color; Handles.color = s_CollisionBoundsColor; Matrix4x4 oldMatrix = Handles.matrix; Vector3[] points0 = new Vector3[20]; Vector3[] points1 = new Vector3[20]; Vector3[] points2 = new Vector3[20]; Handles.SetDiscSectionPoints(points0, Vector3.zero, Vector3.forward, Vector3.right, 360, 1.0f); Handles.SetDiscSectionPoints(points1, Vector3.zero, Vector3.up, -Vector3.right, 360, 1.0f); Handles.SetDiscSectionPoints(points2, Vector3.zero, Vector3.right, Vector3.up, 360, 1.0f); Vector3[] points = new Vector3[points0.Length + points1.Length + points2.Length]; points0.CopyTo(points, 0); points1.CopyTo(points, 20); points2.CopyTo(points, 40); foreach (ParticleSystem ps in m_ParticleSystemUI.m_ParticleSystems) { if (!ps.collision.enabled) continue; ParticleSystem.Particle[] particles = new ParticleSystem.Particle[ps.particleCount]; int count = ps.GetParticles(particles); Matrix4x4 transform = Matrix4x4.identity; if (ps.main.simulationSpace == ParticleSystemSimulationSpace.Local) { transform = ps.localToWorldMatrix; } for (int i = 0; i < count; i++) { ParticleSystem.Particle particle = particles[i]; Vector3 size = particle.GetCurrentSize3D(ps); float radius = System.Math.Max(size.x, System.Math.Max(size.y, size.z)) * 0.5f * ps.collision.radiusScale; Handles.matrix = transform * Matrix4x4.TRS(particle.position, Quaternion.identity, new Vector3(radius, radius, radius)); Handles.DrawPolyLine(points); } } Handles.color = oldColor; Handles.matrix = oldMatrix; } private static void DrawSolidPlane(Vector3 pos, Quaternion rot, Color faceColor, Color edgeColor) { if (Event.current.type != EventType.Repaint) return; var oldMatrix = Handles.matrix; float scale = 10 * m_ScaleGrid; Handles.matrix = Matrix4x4.TRS(pos, rot, new Vector3(scale, scale, scale)) * Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(90, 0, 0), Vector3.one); // Rotate plane by 90 Handles.DrawSolidRectangleWithOutline(new Rect(-0.5f, -0.5f, 1, 1), faceColor, edgeColor); Handles.DrawLine(Vector3.zero, Vector3.back / scale); Handles.matrix = oldMatrix; } private static void DrawGrid(Vector3 pos, Vector3 axis1, Vector3 axis2, Vector3 normal, Color color) { if (Event.current.type != EventType.Repaint) return; HandleUtility.ApplyWireMaterial(); if (color.a > 0) { GL.Begin(GL.LINES); float lineLength = 10f; int numLines = 11; lineLength *= m_ScaleGrid; numLines = (int)lineLength; numLines = Mathf.Clamp(numLines, 10, 40); if (numLines % 2 == 0) numLines++; float halfLength = lineLength * 0.5f; float distBetweenLines = lineLength / (numLines - 1); Vector3 v1 = axis1 * lineLength; Vector3 v2 = axis2 * lineLength; Vector3 dist1 = axis1 * distBetweenLines; Vector3 dist2 = axis2 * distBetweenLines; Vector3 startPos = pos - axis1 * halfLength - axis2 * halfLength; for (int i = 0; i < numLines; i++) { if (i % 2 == 0) GL.Color(color * 0.7f); else GL.Color(color); // Axis1 GL.Vertex(startPos + i * dist1); GL.Vertex(startPos + i * dist1 + v2); // Axis2 GL.Vertex(startPos + i * dist2); GL.Vertex(startPos + i * dist2 + v1); } GL.Color(color); GL.Vertex(pos); GL.Vertex(pos + normal); GL.End(); } } override public void UpdateCullingSupportedString(ref string text) { text += "\nCollision module is enabled."; } } } // namespace UnityEditor
UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemModules/CollisionModuleUI.cs/0
{ "file_path": "UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemModules/CollisionModuleUI.cs", "repo_id": "UnityCsReference", "token_count": 12987 }
407
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; namespace UnityEditor { class RotationModuleUI : ModuleUI { SerializedMinMaxCurve m_X; SerializedMinMaxCurve m_Y; SerializedMinMaxCurve m_Z; SerializedProperty m_SeparateAxes; class Texts { public GUIContent rotation = EditorGUIUtility.TrTextContent("Angular Velocity", "Controls the angular velocity of each particle during its lifetime."); public GUIContent separateAxes = EditorGUIUtility.TrTextContent("Separate Axes", "If enabled, you can control the angular velocity limit separately for each axis."); public GUIContent x = EditorGUIUtility.TextContent("X"); public GUIContent y = EditorGUIUtility.TextContent("Y"); public GUIContent z = EditorGUIUtility.TextContent("Z"); } static Texts s_Texts; public RotationModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "RotationModule", displayName) { m_ToolTip = "Controls the angular velocity of each particle during its lifetime."; } protected override void Init() { // Already initialized? if (m_Z != null) return; if (s_Texts == null) s_Texts = new Texts(); m_SeparateAxes = GetProperty("separateAxes"); m_X = new SerializedMinMaxCurve(this, s_Texts.x, "x", kUseSignedRange, false, m_SeparateAxes.boolValue); m_Y = new SerializedMinMaxCurve(this, s_Texts.y, "y", kUseSignedRange, false, m_SeparateAxes.boolValue); m_Z = new SerializedMinMaxCurve(this, s_Texts.z, "curve", kUseSignedRange); m_X.m_RemapValue = Mathf.Rad2Deg; m_Y.m_RemapValue = Mathf.Rad2Deg; m_Z.m_RemapValue = Mathf.Rad2Deg; } public override void OnInspectorGUI(InitialModuleUI initial) { EditorGUI.BeginChangeCheck(); bool separateAxes = GUIToggle(s_Texts.separateAxes, m_SeparateAxes); if (EditorGUI.EndChangeCheck()) { // Remove old curves from curve editor if (!separateAxes) { m_X.RemoveCurveFromEditor(); m_Y.RemoveCurveFromEditor(); } } // Keep states in sync if (!m_Z.stateHasMultipleDifferentValues) { m_X.SetMinMaxState(m_Z.state, separateAxes); m_Y.SetMinMaxState(m_Z.state, separateAxes); } if (separateAxes) { m_Z.m_DisplayName = s_Texts.z; GUITripleMinMaxCurve(GUIContent.none, s_Texts.x, m_X, s_Texts.y, m_Y, s_Texts.z, m_Z, null); } else { m_Z.m_DisplayName = s_Texts.rotation; GUIMinMaxCurve(s_Texts.rotation, m_Z); } } override public void UpdateCullingSupportedString(ref string text) { Init(); string failureReason = string.Empty; if (!m_X.SupportsProcedural(ref failureReason)) text += "\nRotation over Lifetime module curve X: " + failureReason; failureReason = string.Empty; if (!m_Y.SupportsProcedural(ref failureReason)) text += "\nRotation over Lifetime module curve Y: " + failureReason; failureReason = string.Empty; if (!m_Z.SupportsProcedural(ref failureReason)) text += "\nRotation over Lifetime module curve Z: " + failureReason; } } } // namespace UnityEditor
UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemModules/RotationModuleUI.cs/0
{ "file_path": "UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemModules/RotationModuleUI.cs", "repo_id": "UnityCsReference", "token_count": 1854 }
408