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.Snap;
using UnityEngine;
namespace UnityEditor
{
public sealed partial class Handles
{
/// <summary>
/// Set of IDs corresponding to the handles of Handles.RotationHandle.
/// </summary>
public struct RotationHandleIds
{
/// <summary>
/// Default set of IDs to pass to Handles.RotationHandle.
/// </summary>
public static RotationHandleIds @default
{
get
{
return new RotationHandleIds(
GUIUtility.GetControlID(s_xRotateHandleHash, FocusType.Passive),
GUIUtility.GetControlID(s_yRotateHandleHash, FocusType.Passive),
GUIUtility.GetControlID(s_zRotateHandleHash, FocusType.Passive),
GUIUtility.GetControlID(s_cameraAxisRotateHandleHash, FocusType.Passive),
GUIUtility.GetControlID(s_xyzRotateHandleHash, FocusType.Passive)
);
}
}
public readonly int x, y, z, cameraAxis, xyz;
internal int this[int index]
{
get
{
switch (index)
{
case 0: return x;
case 1: return y;
case 2: return z;
case 3: return cameraAxis;
case 4: return xyz;
}
return -1;
}
}
internal bool Has(int id)
{
return x == id
|| y == id
|| z == id
|| cameraAxis == id
|| xyz == id;
}
internal RotationHandleIds(int x, int y, int z, int cameraAxis, int xyz)
{
this.x = x;
this.y = y;
this.z = z;
this.cameraAxis = cameraAxis;
this.xyz = xyz;
}
public override int GetHashCode()
{
return x ^ y ^ z ^ cameraAxis ^ xyz;
}
public override bool Equals(object obj)
{
if (!(obj is RotationHandleIds))
return false;
var o = (RotationHandleIds)obj;
return o.x == x && o.y == y && o.z == z
&& o.cameraAxis == cameraAxis && o.xyz == xyz;
}
}
internal struct RotationHandleParam
{
[Flags]
public enum Handle
{
None = 0,
X = 1 << 0,
Y = 1 << 1,
Z = 1 << 2,
CameraAxis = 1 << 3,
XYZ = 1 << 4,
All = ~None
}
static RotationHandleParam s_Default = new RotationHandleParam((Handle)(-1), Vector3.one, 1f, 1.1f, true, true);
public static RotationHandleParam Default { get { return s_Default; } set { s_Default = value; } }
public readonly Vector3 axisSize;
public readonly float cameraAxisSize;
public readonly float xyzSize;
public readonly Handle handles;
public readonly bool enableRayDrag;
public readonly bool displayXYZCircle;
public bool ShouldShow(int axis)
{
return (handles & (Handle)(1 << axis)) != 0;
}
public bool ShouldShow(Handle handle)
{
return (handles & handle) != 0;
}
public RotationHandleParam(Handle handles, Vector3 axisSize, float xyzSize, float cameraAxisSize, bool enableRayDrag, bool displayXYZCircle)
{
this.axisSize = axisSize;
this.xyzSize = xyzSize;
this.handles = handles;
this.cameraAxisSize = cameraAxisSize;
this.enableRayDrag = enableRayDrag;
this.displayXYZCircle = displayXYZCircle;
}
}
static readonly Color k_RotationPieColor = new Color(246f / 255, 242f / 255, 50f / 255, .89f);
public static Quaternion DoRotationHandle(Quaternion rotation, Vector3 position)
{
return DoRotationHandle(RotationHandleIds.@default, rotation, position, RotationHandleParam.Default);
}
internal static Quaternion DoRotationHandle(RotationHandleIds ids, Quaternion rotation, Vector3 position, RotationHandleParam param)
{
var evt = Event.current;
var camForward = Handles.inverseMatrix.MultiplyVector(Camera.current != null ? Camera.current.transform.forward : Vector3.forward);
var size = HandleUtility.GetHandleSize(position);
var temp = color;
bool isDisabled = !GUI.enabled;
var isHot = ids.Has(GUIUtility.hotControl);
VertexSnapping.HandleMouseMove(ids.xyz);
// Draw free rotation first to give it the lowest priority
if (!isDisabled
&& param.ShouldShow(RotationHandleParam.Handle.XYZ)
&& (ids.xyz == GUIUtility.hotControl || !isHot))
{
color = new Color(0, 0, 0, 0.3f);
rotation = UnityEditorInternal.FreeRotate.Do(ids.xyz, rotation, position, size * param.xyzSize, param.displayXYZCircle);
}
for (var i = 0; i < 3; ++i)
{
if (!param.ShouldShow(i))
continue;
var axisColor = GetColorByAxis(i);
color = isDisabled ? Color.Lerp(axisColor, staticColor, staticBlend) : axisColor;
color = ToActiveColorSpace(color);
var axisDir = GetAxisVector(i);
var radius = size * param.axisSize[i];
rotation = UnityEditorInternal.Disc.Do(ids[i], rotation, position, rotation * axisDir, radius, true, EditorSnapSettings.rotate, param.enableRayDrag, true, k_RotationPieColor);
}
// while dragging any rotation handles, draw a gray disc outline
if (isHot && evt.type == EventType.Repaint)
{
color = ToActiveColorSpace(s_DisabledHandleColor);
Handles.DrawWireDisc(position, camForward, size * param.axisSize[0], Handles.lineThickness);
}
if (!isDisabled
&& param.ShouldShow(RotationHandleParam.Handle.CameraAxis)
&& (ids.cameraAxis == GUIUtility.hotControl || !isHot))
{
color = ToActiveColorSpace(centerColor);
rotation = UnityEditorInternal.Disc.Do(ids.cameraAxis, rotation, position, camForward, size * param.cameraAxisSize, false, 0, param.enableRayDrag, true, k_RotationPieColor);
}
color = temp;
return rotation;
}
}
}
| UnityCsReference/Editor/Mono/Handles/RotationHandle.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Handles/RotationHandle.cs",
"repo_id": "UnityCsReference",
"token_count": 3713
} | 314 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace UnityEditor;
internal interface IBuildPlatformProperties : IPlatformProperties
{
// The BuildPlayerWindow.ActiveBuildTargetsGUI method uses this property to determine whether or not to display certain
// build options based on whether or not the desired build target is compatible with the OS on which the editor is running.
bool CanBuildOnCurrentHostPlatform => true;
// The BuildEventsHandlerPostProcess.OnPostprocessBuild method uses this method to report permissions for a build target.
// This method replaces the BuildEventsHandlerPostProcess.ReportBuildTargetPermissions private method.
public void ReportBuildTargetPermissions(BuildOptions buildOptions) {}
// The BuildPlayerWindow.BuildPlayerAndRun method uses this method to set the build location for those build targets
// that require special handling. Only the stand-alone Windows build targets implement this method.
public string ValidateBuildLocation() => null;
}
| UnityCsReference/Editor/Mono/IBuildPlatformProperties.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/IBuildPlatformProperties.cs",
"repo_id": "UnityCsReference",
"token_count": 272
} | 315 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.IMGUI.Controls;
using UnityEngine;
namespace UnityEditor
{
internal class ExposeTransformEditor
{
private static class Styles
{
// TreeView column
public static GUIContent TransformName = EditorGUIUtility.TrTextContent("Node Name");
public static GUIContent EnableName = EditorGUIUtility.TrTextContent("Use", "Maintain Alt/Option key to enable or disable all children");
}
// TreeView
private string[] m_TransformPaths;
private SerializedProperty m_ExtraExposedTransformPaths;
List<string> m_ExtraExposedTransformPathsList;
TreeViewState m_TreeViewState;
MultiColumnHeaderState m_ViewHeaderState;
private OptimizeGameObjectTreeView m_ExposeTransformEditor;
public void OnEnable(string[] transformPaths, SerializedObject serializedObject)
{
m_TransformPaths = transformPaths;
m_ExtraExposedTransformPaths = serializedObject.FindProperty("m_ExtraExposedTransformPaths");
SetupOptimizeGameObjectTreeView();
ResetExposedTransformList();
}
public void ResetExposedTransformList()
{
int exposedNodeCount = m_ExtraExposedTransformPaths.arraySize;
m_ExtraExposedTransformPathsList = new List<string>(exposedNodeCount);
if (exposedNodeCount > 0)
{
var nodeIterator = m_ExtraExposedTransformPaths.GetArrayElementAtIndex(0);
for (int i = 0; i < exposedNodeCount; ++i)
{
m_ExtraExposedTransformPathsList.Add(nodeIterator.stringValue);
nodeIterator.Next(false);
}
}
}
public void OnGUI()
{
var listRect = GUILayoutUtility.GetRect(0, 0, GUILayout.ExpandWidth(true));
m_ExposeTransformEditor.OnGUI(listRect);
}
void SetupOptimizeGameObjectTreeView()
{
if (m_TreeViewState == null)
m_TreeViewState = new TreeViewState();
var columns = new[]
{
new MultiColumnHeaderState.Column
{
headerContent = Styles.EnableName,
headerTextAlignment = TextAlignment.Center,
canSort = false,
width = 31f, minWidth = 31f, maxWidth = 31f,
autoResize = true, allowToggleVisibility = false
},
new MultiColumnHeaderState.Column
{
headerContent = Styles.TransformName,
headerTextAlignment = TextAlignment.Left,
canSort = false,
autoResize = true, allowToggleVisibility = false,
}
};
var newHeader = new MultiColumnHeaderState(columns);
if (m_ViewHeaderState != null)
{
MultiColumnHeaderState.OverwriteSerializedFields(m_ViewHeaderState, newHeader);
}
m_ViewHeaderState = newHeader;
var multiColumnHeader = new MultiColumnHeader(m_ViewHeaderState);
multiColumnHeader.ResizeToFit();
m_ExposeTransformEditor = new OptimizeGameObjectTreeView(m_TreeViewState, multiColumnHeader, FillNodeInfos);
if (m_ExposeTransformEditor.searchString == null)
m_ExposeTransformEditor.searchString = string.Empty;
}
SerializedNodeInfo FillNodeInfos()
{
var rootNode = new SerializedNodeInfo() { depth = -1, displayName = "", id = 0, children = new List<TreeViewItem>(0) };
if (m_TransformPaths == null || m_TransformPaths.Length < 1)
{
return rootNode;
}
var nodesCount = m_TransformPaths.Length;
var nodeInfos = new List<SerializedNodeInfo>(nodesCount - 1);
Stack<string> depth = new Stack<string>(nodesCount);
string currentPath = String.Empty;
// skip the first index as it is the empty root of the gameObject
for (int i = 1; i < nodesCount; i++)
{
var newNode = new SerializedNodeInfo();
newNode.id = i;
newNode.path = m_TransformPaths[i];
newNode.getNodeState = GetNodeState;
newNode.setNodeState = SetNodeState;
var newPath = newNode.path;
while (!string.IsNullOrEmpty(currentPath) && !newPath.StartsWith(currentPath + "/", StringComparison.InvariantCulture))
{
// we are in a new node, lets unstack until we reach the correct hierarchy
var oldParent = depth.Pop();
var index = currentPath.LastIndexOf(oldParent, StringComparison.InvariantCulture);
if (index > 0)
index--;
currentPath = currentPath.Remove(index);
}
var nodeName = newPath;
if (!string.IsNullOrEmpty(currentPath))
nodeName = nodeName.Remove(0, currentPath.Length + 1);
newNode.depth = depth.Count;
newNode.displayName = nodeName;
depth.Push(nodeName);
currentPath = newPath;
nodeInfos.Add(newNode);
}
TreeViewUtility.SetChildParentReferences(nodeInfos.Cast<TreeViewItem>().ToList(), rootNode);
return rootNode;
}
private bool GetNodeState(string nodePath)
{
return m_ExtraExposedTransformPathsList.Contains(nodePath);
}
private void SetNodeState(string nodePath, bool state)
{
if (GetNodeState(nodePath) != state)
{
if (state)
{
m_ExtraExposedTransformPaths.InsertArrayElementAtIndex(m_ExtraExposedTransformPaths.arraySize);
m_ExtraExposedTransformPaths.GetArrayElementAtIndex(m_ExtraExposedTransformPaths.arraySize - 1).stringValue = nodePath;
m_ExtraExposedTransformPathsList.Add(nodePath);
}
else
{
var index = m_ExtraExposedTransformPathsList.IndexOf(nodePath);
m_ExtraExposedTransformPaths.DeleteArrayElementAtIndex(index);
m_ExtraExposedTransformPathsList.RemoveAt(index);
}
}
}
}
internal class OptimizeGameObjectTreeView : ToggleTreeView<SerializedNodeInfo>
{
public OptimizeGameObjectTreeView(TreeViewState state, MultiColumnHeader multiColumnHeader, Func<SerializedNodeInfo> rebuildRoot)
: base(state, multiColumnHeader, rebuildRoot)
{
}
}
internal class SerializedNodeInfo : ToggleTreeViewItem
{
public string path;
public Func<string, bool> getNodeState;
public Action<string, bool> setNodeState;
public override bool nodeState
{
get { return getNodeState != null && getNodeState(path); }
set
{
setNodeState?.Invoke(path, value);
}
}
}
}
| UnityCsReference/Editor/Mono/ImportSettings/ExposeTransformEditor.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/ImportSettings/ExposeTransformEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 3564
} | 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.IO;
using System.Linq;
using UnityEditor.Compilation;
using UnityEngine;
using UnityEditorInternal;
using UnityEditor.AssetImporters;
using UnityEditor.Scripting.ScriptCompilation;
namespace UnityEditor
{
[CustomEditor(typeof(AssemblyDefinitionReferenceImporter))]
[CanEditMultipleObjects]
internal class AssemblyDefinitionReferenceImporterInspector : AssetImporterEditor
{
internal class Styles
{
public static readonly GUIContent assemblyDefinition = EditorGUIUtility.TrTextContent("Assembly Definition");
public static readonly GUIContent loadError = EditorGUIUtility.TrTextContent("Load error");
public static readonly GUIContent useGUID = EditorGUIUtility.TrTextContent("Use GUID", "Use the Assembly Definition asset GUID instead of name for referencing. Allows the referenced assembly to be renamed without having to update references.");
}
GUIStyle m_TextStyle;
class AssemblyDefinitionReferenceState : ScriptableObject
{
public string path
{
get { return AssetDatabase.GetAssetPath(asset); }
}
public AssemblyDefinitionReferenceAsset asset;
public AssemblyDefinitionImporterInspector.AssemblyDefinitionReference reference;
public bool useGUIDs;
}
SerializedProperty m_Reference;
SerializedProperty m_ReferenceName;
SerializedProperty m_ReferenceAsset;
SerializedProperty m_UseGUIDs;
Exception extraDataInitializeException;
public override bool showImportedObject { get { return false; } }
public override void OnEnable()
{
base.OnEnable();
//Ensure UIElements handles the IMGUI container with margins
alwaysAllowExpansion = true;
m_Reference = extraDataSerializedObject.FindProperty("reference");
m_ReferenceName = m_Reference.FindPropertyRelative("name");
m_ReferenceAsset = m_Reference.FindPropertyRelative("asset");
m_UseGUIDs = extraDataSerializedObject.FindProperty("useGUIDs");
}
public override void OnInspectorGUI()
{
if (extraDataInitializeException != null)
{
ShowLoadErrorExceptionGUI(extraDataInitializeException);
ApplyRevertGUI();
return;
}
extraDataSerializedObject.Update();
EditorGUI.BeginDisabled(m_ReferenceAsset.objectReferenceValue == null);
EditorGUILayout.PropertyField(m_UseGUIDs, Styles.useGUID);
EditorGUI.EndDisabled();
EditorGUI.BeginChangeCheck();
var obj = EditorGUILayout.ObjectField(Styles.assemblyDefinition, m_ReferenceAsset.objectReferenceValue, typeof(AssemblyDefinitionAsset), false);
if (EditorGUI.EndChangeCheck())
{
m_ReferenceAsset.objectReferenceValue = obj;
if (m_ReferenceAsset.objectReferenceValue != null)
{
var data = CustomScriptAssemblyData.FromJson(((AssemblyDefinitionAsset)obj).text);
m_ReferenceName.stringValue = data.name;
}
else
{
m_ReferenceName.stringValue = string.Empty;
}
}
extraDataSerializedObject.ApplyModifiedProperties();
ApplyRevertGUI();
}
protected override void Apply()
{
base.Apply();
SaveAndUpdateAssemblyDefinitionReferenceStates(extraDataTargets.Cast<AssemblyDefinitionReferenceState>().ToArray());
}
void ShowLoadErrorExceptionGUI(Exception e)
{
if (m_TextStyle == null)
m_TextStyle = "ScriptText";
GUILayout.Label(Styles.loadError, EditorStyles.boldLabel);
Rect rect = GUILayoutUtility.GetRect(EditorGUIUtility.TempContent(e.Message), m_TextStyle);
EditorGUI.HelpBox(rect, e.Message, MessageType.Error);
}
protected override Type extraDataType => typeof(AssemblyDefinitionReferenceState);
protected override void InitializeExtraDataInstance(UnityEngine.Object extraData, int targetIndex)
{
try
{
LoadAssemblyDefinitionReferenceState((AssemblyDefinitionReferenceState)extraData, ((AssetImporter)targets[targetIndex]).assetPath);
extraDataInitializeException = null;
}
catch (Exception e)
{
extraDataInitializeException = e;
}
}
[MenuItem("CONTEXT/AssemblyDefinitionReferenceImporter/Reset", secondaryPriority = 9)]
internal static void ContextReset(MenuCommand command)
{
var templatePath = AssetsMenuUtility.GetScriptTemplatePath(ScriptTemplate.AsmRef_NewAssemblyReference);
Debug.Assert(!string.IsNullOrEmpty(templatePath));
var templateContent = File.ReadAllText(templatePath);
var importer = command.context as AssemblyDefinitionReferenceImporter;
if (importer != null)
{
var assetPath = importer.assetPath;
templateContent = ProjectWindowUtil.PreprocessScriptAssetTemplate(assetPath, templateContent);
File.WriteAllText(assetPath, templateContent);
AssetDatabase.ImportAsset(assetPath);
}
}
static void LoadAssemblyDefinitionReferenceState(AssemblyDefinitionReferenceState state, string path)
{
var asset = AssetDatabase.LoadAssetAtPath<AssemblyDefinitionReferenceAsset>(path);
if (asset == null)
return;
var data = CustomScriptAssemblyReferenceData.FromJson(asset.text);
if (data == null)
return;
state.asset = asset;
state.useGUIDs = string.IsNullOrEmpty(data.reference) || CompilationPipeline.GetAssemblyDefinitionReferenceType(data.reference) == AssemblyDefinitionReferenceType.Guid;
state.reference = new AssemblyDefinitionImporterInspector.AssemblyDefinitionReference { name = data.reference, serializedReference = data.reference };
state.reference.Load(data.reference, state.useGUIDs);
}
static void SaveAndUpdateAssemblyDefinitionReferenceStates(AssemblyDefinitionReferenceState[] states)
{
foreach (var state in states)
{
SaveAndUpdateAssemblyDefinitionReferenceState(state);
}
}
static void SaveAndUpdateAssemblyDefinitionReferenceState(AssemblyDefinitionReferenceState state)
{
CustomScriptAssemblyReferenceData data = new CustomScriptAssemblyReferenceData();
if (state.asset != null)
{
data.reference = state.useGUIDs ? CompilationPipeline.GUIDToAssemblyDefinitionReferenceGUID(AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(state.reference.asset))) : state.reference.name;
}
var json = CustomScriptAssemblyReferenceData.ToJson(data);
File.WriteAllText(state.path, json);
AssetDatabase.ImportAsset(state.path);
}
}
}
| UnityCsReference/Editor/Mono/Inspector/AssemblyDefinitionReferenceImporterInspector.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/AssemblyDefinitionReferenceImporterInspector.cs",
"repo_id": "UnityCsReference",
"token_count": 3047
} | 317 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using UnityEditor.Inspector;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.XR;
using AnimatedBool = UnityEditor.AnimatedValues.AnimBool;
using UnityEngine.Scripting;
using UnityEditor.Modules;
using UnityEditor.Overlays;
using UnityEditor.UIElements;
using UnityEditorInternal.VR;
using UnityEngine.UIElements;
using Object = UnityEngine.Object;
namespace UnityEditor
{
[CustomEditor(typeof(Camera))]
[CanEditMultipleObjects]
public class CameraEditor : Editor
{
internal static class Styles
{
public static readonly GUIContent iconRemove = EditorGUIUtility.TrIconContent("Toolbar Minus", "Remove command buffer");
public static readonly GUIContent clearFlags = EditorGUIUtility.TrTextContent("Clear Flags", "What to display in empty areas of this Camera's view.\n\nChoose Skybox to display a skybox in empty areas, defaulting to a background color if no skybox is found.\n\nChoose Solid Color to display a background color in empty areas.\n\nChoose Depth Only to display nothing in empty areas.\n\nChoose Don't Clear to display whatever was displayed in the previous frame in empty areas.");
public static readonly GUIContent background = EditorGUIUtility.TrTextContent("Background", "The Camera clears the screen to this color before rendering.");
public static readonly GUIContent projection = EditorGUIUtility.TrTextContent("Projection", "How the Camera renders perspective.\n\nChoose Perspective to render objects with perspective.\n\nChoose Orthographic to render objects uniformly, with no sense of perspective.");
public static readonly GUIContent size = EditorGUIUtility.TrTextContent("Size", "The vertical size of the camera view.");
public static readonly GUIContent fieldOfView = EditorGUIUtility.TrTextContent("Field of View", "The camera's view angle measured in degrees along the selected axis.");
public static readonly GUIContent viewportRect = EditorGUIUtility.TrTextContent("Viewport Rect", "Four values that indicate where on the screen this camera view will be drawn. Measured in Viewport Coordinates (values 0-1).");
public static readonly GUIContent sensorSize = EditorGUIUtility.TrTextContent("Sensor Size", "The size of the camera sensor in millimeters.");
public static readonly GUIContent lensShift = EditorGUIUtility.TrTextContent("Lens Shift", "Offset from the camera sensor. Use these properties to simulate a shift lens. Measured as a multiple of the sensor size.");
public static readonly GUIContent iso = EditorGUIUtility.TrTextContent("ISO", "The sensor sensitivity (ISO).");
public static readonly GUIContent shutterSpeed = EditorGUIUtility.TrTextContent("Shutter Speed", "The exposure time, in second.");
public static readonly GUIContent aperture = EditorGUIUtility.TrTextContent("Aperture", "The aperture number, in f-stop.");
public static readonly GUIContent focusDistance = EditorGUIUtility.TrTextContent("Focus Distance", "The focus distance of the lens. The Depth of Field Volume override uses this value if you set focusDistanceMode to FocusDistanceMode.Camera.");
public static readonly GUIContent bladeCount = EditorGUIUtility.TrTextContent("Blade Count", "The number of diaphragm blades.");
public static readonly GUIContent curvature = EditorGUIUtility.TrTextContent("Curvature", "Maps an aperture range to blade curvature.");
public static readonly GUIContent barrelClipping = EditorGUIUtility.TrTextContent("Barrel Clipping", "The strength of the \"cat eye\" effect on bokeh (optical vignetting).");
public static readonly GUIContent anamorphism = EditorGUIUtility.TrTextContent("Anamorphism", "Stretches the sensor to simulate an anamorphic look. Positive values distort the Camera vertically, negative will distort the Camera horizontally.");
public static readonly GUIContent physicalCamera = EditorGUIUtility.TrTextContent("Physical Camera", "Enables Physical camera mode. When checked, the field of view is calculated from properties for simulating physical attributes (focal length, sensor size, and lens shift)");
public static readonly GUIContent cameraType = EditorGUIUtility.TrTextContent("Sensor Type", "Common sensor sizes. Choose an item to set Sensor Size, or edit Sensor Size for your custom settings.");
public static readonly GUIContent renderingPath = EditorGUIUtility.TrTextContent("Rendering Path", "Choose a rendering method for this camera.\n\nUse Graphics Settings to use the rendering path specified in graphics settings.\n\nUse Forward to render all objects with one pass per light.\n\nUse Deferred to draw all objects once without lighting and then draw the lighting of all objects at the end of the render queue.\n\nUse Legacy Vertex Lit to render all lights in a single pass, calculated at vertices.");
public static readonly GUIContent focalLength = EditorGUIUtility.TrTextContent("Focal Length", "The simulated distance between the lens and the sensor of the physical camera. Larger values give a narrower field of view.");
public static readonly GUIContent allowOcclusionCulling = EditorGUIUtility.TrTextContent("Occlusion Culling", "Occlusion Culling disables rendering of objects when they are not currently seen by the camera because they are obscured (occluded) by other objects.");
public static readonly GUIContent allowHDR = EditorGUIUtility.TrTextContent("HDR", "High Dynamic Range gives you a wider range of light intensities, so your lighting looks more realistic. With it, you can still see details and experience less saturation even with bright light.");
public static readonly GUIContent allowMSAA = EditorGUIUtility.TrTextContent("MSAA", "Use Multi Sample Anti-aliasing to reduce aliasing.");
public static readonly GUIContent gateFit = EditorGUIUtility.TrTextContent("Gate Fit", "Determines how the rendered area (resolution gate) fits into the sensor area (film gate).");
public static readonly GUIContent allowDynamicResolution = EditorGUIUtility.TrTextContent("Allow Dynamic Resolution", "Scales render textures to support dynamic resolution if the target platform/graphics API supports it.");
public static readonly GUIContent FOVAxisMode = EditorGUIUtility.TrTextContent("FOV Axis", "Field of view axis.");
public static readonly GUIContent targetDisplay = EditorGUIUtility.TrTextContent("Target Display", "Set the target display for this camera.");
public static readonly GUIContent xrTargetEye = EditorGUIUtility.TrTextContent("Target Eye", "Allows XR rendering for target eye. This disables stereo rendering and only works for the selected eye.");
public static readonly GUIContent orthoDeferredWarning = EditorGUIUtility.TrTextContent("Deferred rendering does not work with Orthographic camera, will use Forward.");
public static readonly GUIContent orthoXRWarning = EditorGUIUtility.TrTextContent("Orthographic projection is not supported when running in XR.", "One or more XR Plug-in providers were detected in your project. Using Orthographic projection is not supported when running in XR and enabling this may cause problems.", EditorGUIUtility.warningIcon);
public static readonly GUIContent deferredMSAAWarning = EditorGUIUtility.TrTextContent("The target texture is using MSAA. Note that this will not affect MSAA behaviour of this camera. MSAA rendering for cameras is configured through the 'MSAA' camera setting and related project settings. The target texture will always contain resolved pixel data.");
public static readonly GUIContent dynamicResolutionTimingWarning = EditorGUIUtility.TrTextContent("It is recommended to enable Frame Timing Statistics under Rendering Player Settings when using dynamic resolution cameras.");
public static readonly GUIStyle invisibleButton = "InvisibleButton";
public const string k_CameraEditorUxmlPath = "UXML/InspectorWindow/CameraEditor.uxml";
public const string k_ClearFlagsElementName = "clear-flags";
public const string k_BackgroundElementName = "background";
public const string k_CullingMaskElementName = "culling-mask";
public const string k_ClippingPlanesElementName = "clipping-planes";
public const string k_ViewportRectElementName = "viewport-rect";
public const string k_DepthElementName = "depth";
public const string k_RenderingPathElementName = "rendering-path";
public const string k_OrthographicDeferredWarningElementName = "orthographic-deferred-warning";
public const string k_DeferredMsaaWarningElementName = "deferred-msaa-warning";
public const string k_TargetTextureElementName = "target-texture";
public const string k_OcclusionCullingElementName = "occlusion-culling";
public const string k_HdrElementName = "hdr";
public const string k_MsaaElementName = "msaa";
public const string k_DynamicResolution = "dynamic-resolution";
public const string k_DynamicResolutionTimingWarningElementName = "dynamic-resolution-timing-warning";
public const string k_CameraWarningsElementName = "camera-warnings";
public const string k_VrGroupElementName = "vr-group";
public const string k_TargetDisplayElementName = "target-display";
public const string k_TargetEyeElementName = "target-eye";
public const string k_DepthTextureModeElementName = "depth-texture-mode";
public const string k_CommandBuffersElementName = "command-buffers";
public const string k_CommandBuffersListElementName = "list";
public const string k_CommandBuffersRemoveAllElementName = "remove-all";
public const string k_PerspectiveGroupElementName = "perspective-group";
public const string k_OrthographicGroupElementName = "orthographic-group";
public const string k_ProjectionTypeElementName = "projection-type";
public const string k_FovAxisModeElementName = "fov-axis-mode";
public const string k_FieldOfViewElementName = "field-of-view";
public const string k_PhysicalCameraGroupElementName = "physical-camera-group";
public const string k_PhysicalCameraElementName = "physical-camera";
public const string k_IsoElementName = "iso";
public const string k_ShutterSpeedElementName = "shutter-speed";
public const string k_ApertureElementName = "aperture";
public const string k_FocusDistanceElementName = "focus-distance";
public const string k_BladeCountElementName = "blade-count";
public const string k_CurvatureElementName = "curvature";
public const string k_BarrelClippingElementName = "barrel-clipping";
public const string k_AnamorphismElementName = "anamorphism";
public const string k_FocalLengthElementName = "focal-length";
public const string k_SensorTypeElementName = "sensor-type";
public const string k_SensorSizeElementName = "sensor-size";
public const string k_LensShiftElementName = "lens-shift";
public const string k_GateFitElementName = "gate-fit";
public const string k_OrthographicSizeElementName = "orthographic-size";
public const string k_OrthographicXrWarningElementName = "orthographic-xr-warning";
public const string commandBufferUssClassName = "camera-editor__command-buffer__line";
public const string commandBufferLabelUssClassName = "camera-editor__command-buffer__label";
public const string commandBufferRemoveButtonUssClassName = "camera-editor__command-buffer__remove-button";
}
public sealed class Settings
{
readonly SerializedObject m_SerializedObject;
public Settings(SerializedObject so)
{
m_SerializedObject = so;
}
public static IEnumerable<string> ApertureFormatNames => k_ApertureFormats;
internal static readonly string[] k_ApertureFormats =
{
"8mm",
"Super 8mm",
"16mm",
"Super 16mm",
"35mm 2-perf",
"35mm Academy",
"Super-35",
"35mm TV Projection",
"35mm Full Aperture",
"35mm 1.85 Projection",
"35mm Anamorphic",
"65mm ALEXA",
"70mm",
"70mm IMAX",
"Custom"
};
public static IEnumerable<Vector2> ApertureFormatValues => k_ApertureFormatValues;
internal static readonly Vector2[] k_ApertureFormatValues =
{
new(4.8f, 3.5f), // 8mm
new(5.79f, 4.01f), // Super 8mm
new(10.26f, 7.49f), // 16mm
new(12.522f, 7.417f), // Super 16mm
new(21.95f, 9.35f), // 35mm 2-perf
new(21.946f, 16.002f), // 35mm academy
new(24.89f, 18.66f), // Super-35
new(20.726f, 15.545f), // 35mm TV Projection
new(24.892f, 18.669f), // 35mm Full Aperture
new(20.955f, 11.328f), // 35mm 1.85 Projection
new(21.946f, 18.593f), // 35mm Anamorphic
new(54.12f, 25.59f), // 65mm ALEXA
new(52.476f, 23.012f), // 70mm
new(70.41f, 52.63f), // 70mm IMAX
};
// Manually entered rendering path names/values, since we want to show them
// in different order than they appear in the enum.
internal static readonly GUIContent[] k_CameraRenderPaths =
{
EditorGUIUtility.TrTextContent("Use Graphics Settings"),
EditorGUIUtility.TrTextContent("Forward"),
EditorGUIUtility.TrTextContent("Deferred"),
EditorGUIUtility.TrTextContent("Legacy Vertex Lit")
};
internal static readonly int[] k_CameraRenderPathValues =
{
(int)RenderingPath.UsePlayerSettings,
(int)RenderingPath.Forward,
(int)RenderingPath.DeferredShading,
(int)RenderingPath.VertexLit
};
internal static readonly GUIContent[] k_DefaultOptions =
{
EditorGUIUtility.TrTextContent("Off"),
EditorGUIUtility.TrTextContent("Use Graphics Settings"),
};
internal static readonly int[] k_DefaultOptionValues =
{
0,
1
};
internal static readonly GUIContent[] k_TargetEyes =
{
EditorGUIUtility.TrTextContent("Both"),
EditorGUIUtility.TrTextContent("Left"),
EditorGUIUtility.TrTextContent("Right"),
EditorGUIUtility.TrTextContent("None (Main Display)"),
};
internal static readonly int[] k_TargetEyeValues =
{
(int)StereoTargetEyeMask.Both,
(int)StereoTargetEyeMask.Left,
(int)StereoTargetEyeMask.Right,
(int)StereoTargetEyeMask.None
};
public SerializedProperty clearFlags { get; private set; }
public SerializedProperty backgroundColor { get; private set; }
public SerializedProperty normalizedViewPortRect { get; private set; }
internal SerializedProperty projectionMatrixMode { get; private set; }
public SerializedProperty iso { get; private set; }
public SerializedProperty shutterSpeed { get; private set; }
public SerializedProperty aperture { get; private set; }
public SerializedProperty focusDistance { get; private set; }
public SerializedProperty focalLength { get; private set; }
public SerializedProperty bladeCount { get; private set; }
public SerializedProperty curvature { get; private set; }
public SerializedProperty barrelClipping { get; private set; }
public SerializedProperty anamorphism { get; private set; }
public SerializedProperty sensorSize { get; private set; }
public SerializedProperty lensShift { get; private set; }
public SerializedProperty gateFit { get; private set; }
public SerializedProperty verticalFOV { get; private set; }
public SerializedProperty orthographic { get; private set; }
public SerializedProperty orthographicSize { get; private set; }
public SerializedProperty depth { get; private set; }
public SerializedProperty cullingMask { get; private set; }
public SerializedProperty renderingPath { get; private set; }
public SerializedProperty occlusionCulling { get; private set; }
public SerializedProperty targetTexture { get; private set; }
public SerializedProperty HDR { get; private set; }
public SerializedProperty allowMSAA { get; private set; }
public SerializedProperty allowDynamicResolution { get; private set; }
public SerializedProperty stereoConvergence { get; private set; }
public SerializedProperty stereoSeparation { get; private set; }
public SerializedProperty nearClippingPlane { get; private set; }
public SerializedProperty farClippingPlane { get; private set; }
public SerializedProperty fovAxisMode { get; private set; }
public SerializedProperty targetDisplay { get; private set; }
public SerializedProperty targetEye { get; private set; }
public void OnEnable()
{
clearFlags = m_SerializedObject.FindProperty("m_ClearFlags");
backgroundColor = m_SerializedObject.FindProperty("m_BackGroundColor");
normalizedViewPortRect = m_SerializedObject.FindProperty("m_NormalizedViewPortRect");
iso = m_SerializedObject.FindProperty("m_Iso");
shutterSpeed = m_SerializedObject.FindProperty("m_ShutterSpeed");
aperture = m_SerializedObject.FindProperty("m_Aperture");
focusDistance = m_SerializedObject.FindProperty("m_FocusDistance");
focalLength = m_SerializedObject.FindProperty("m_FocalLength");
bladeCount = m_SerializedObject.FindProperty("m_BladeCount");
curvature = m_SerializedObject.FindProperty("m_Curvature");
barrelClipping = m_SerializedObject.FindProperty("m_BarrelClipping");
anamorphism = m_SerializedObject.FindProperty("m_Anamorphism");
sensorSize = m_SerializedObject.FindProperty("m_SensorSize");
lensShift = m_SerializedObject.FindProperty("m_LensShift");
gateFit = m_SerializedObject.FindProperty("m_GateFitMode");
projectionMatrixMode = m_SerializedObject.FindProperty("m_projectionMatrixMode");
nearClippingPlane = m_SerializedObject.FindProperty("near clip plane");
farClippingPlane = m_SerializedObject.FindProperty("far clip plane");
verticalFOV = m_SerializedObject.FindProperty("field of view");
fovAxisMode = m_SerializedObject.FindProperty("m_FOVAxisMode");
orthographic = m_SerializedObject.FindProperty("orthographic");
orthographicSize = m_SerializedObject.FindProperty("orthographic size");
depth = m_SerializedObject.FindProperty("m_Depth");
cullingMask = m_SerializedObject.FindProperty("m_CullingMask");
renderingPath = m_SerializedObject.FindProperty("m_RenderingPath");
occlusionCulling = m_SerializedObject.FindProperty("m_OcclusionCulling");
targetTexture = m_SerializedObject.FindProperty("m_TargetTexture");
HDR = m_SerializedObject.FindProperty("m_HDR");
allowMSAA = m_SerializedObject.FindProperty("m_AllowMSAA");
allowDynamicResolution = m_SerializedObject.FindProperty("m_AllowDynamicResolution");
stereoConvergence = m_SerializedObject.FindProperty("m_StereoConvergence");
stereoSeparation = m_SerializedObject.FindProperty("m_StereoSeparation");
targetDisplay = m_SerializedObject.FindProperty("m_TargetDisplay");
targetEye = m_SerializedObject.FindProperty("m_TargetEye");
}
public void Update()
{
m_SerializedObject.Update();
}
public void ApplyModifiedProperties()
{
m_SerializedObject.ApplyModifiedProperties();
}
public void DrawClearFlags()
{
EditorGUILayout.PropertyField(clearFlags, Styles.clearFlags);
}
public void DrawBackgroundColor()
{
EditorGUILayout.PropertyField(backgroundColor, Styles.background);
}
public void DrawCullingMask()
{
EditorGUILayout.PropertyField(cullingMask);
}
public void DrawProjection()
{
var projectionType = orthographic.boolValue ? ProjectionType.Orthographic : ProjectionType.Perspective;
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = orthographic.hasMultipleDifferentValues;
var controlRect = EditorGUILayout.GetControlRect();
var label = EditorGUI.BeginProperty(controlRect, Styles.projection, orthographic);
projectionType = (ProjectionType)EditorGUI.EnumPopup(controlRect, label, projectionType);
EditorGUI.showMixedValue = false;
if (EditorGUI.EndChangeCheck())
orthographic.boolValue = (projectionType == ProjectionType.Orthographic);
EditorGUI.EndProperty();
if (!orthographic.hasMultipleDifferentValues)
{
if (projectionType == ProjectionType.Orthographic)
EditorGUILayout.PropertyField(orthographicSize, Styles.size);
else
{
float fovCurrentValue;
var multipleDifferentFovValues = false;
var isPhysicalCamera = projectionMatrixMode.intValue == (int)Camera.ProjectionMatrixMode.PhysicalPropertiesBased;
var rect = EditorGUILayout.GetControlRect();
var guiContent = EditorGUI.BeginProperty(rect, Styles.FOVAxisMode, fovAxisMode);
EditorGUI.showMixedValue = fovAxisMode.hasMultipleDifferentValues;
EditorGUI.BeginChangeCheck();
var fovAxisNewVal = (int)(Camera.FieldOfViewAxis)EditorGUI.EnumPopup(rect, guiContent, (Camera.FieldOfViewAxis)fovAxisMode.intValue);
if (EditorGUI.EndChangeCheck())
fovAxisMode.intValue = fovAxisNewVal;
EditorGUI.EndProperty();
var fovAxisVertical = fovAxisMode.intValue == 0;
var targets = m_SerializedObject.targetObjects;
var camera0 = targets[0] as Camera;
var aspectRatio = isPhysicalCamera ? sensorSize.vector2Value.x / sensorSize.vector2Value.y : camera0.aspect;
if (!fovAxisVertical && !fovAxisMode.hasMultipleDifferentValues)
{
// camera.aspect is not serialized so we have to check all targets.
fovCurrentValue = Camera.VerticalToHorizontalFieldOfView(camera0.fieldOfView, aspectRatio);
if (m_SerializedObject.targetObjectsCount > 1)
{
foreach (Camera camera in targets)
{
if (camera.fieldOfView != fovCurrentValue)
{
multipleDifferentFovValues = true;
break;
}
}
}
}
else
{
fovCurrentValue = verticalFOV.floatValue;
multipleDifferentFovValues = fovAxisMode.hasMultipleDifferentValues;
}
EditorGUI.showMixedValue = multipleDifferentFovValues;
var content = EditorGUI.BeginProperty(EditorGUILayout.BeginHorizontal(), Styles.fieldOfView, verticalFOV);
EditorGUI.BeginDisabled(projectionMatrixMode.hasMultipleDifferentValues || isPhysicalCamera && (sensorSize.hasMultipleDifferentValues || fovAxisMode.hasMultipleDifferentValues));
EditorGUI.BeginChangeCheck();
var fovMinValue = fovAxisVertical ? 0.00001f : Camera.VerticalToHorizontalFieldOfView(0.00001f, aspectRatio);
var fovMaxValue = fovAxisVertical ? 179.0f : Camera.VerticalToHorizontalFieldOfView(179.0f, aspectRatio);
var fovNewValue = EditorGUILayout.Slider(content, fovCurrentValue, fovMinValue, fovMaxValue);
var fovChanged = EditorGUI.EndChangeCheck();
EditorGUI.EndDisabled();
EditorGUILayout.EndHorizontal();
EditorGUI.EndProperty();
EditorGUI.showMixedValue = false;
content = EditorGUI.BeginProperty(EditorGUILayout.BeginHorizontal(), Styles.physicalCamera, projectionMatrixMode);
EditorGUI.showMixedValue = projectionMatrixMode.hasMultipleDifferentValues;
EditorGUI.BeginChangeCheck();
isPhysicalCamera = EditorGUILayout.Toggle(content, isPhysicalCamera);
if (EditorGUI.EndChangeCheck())
projectionMatrixMode.intValue = isPhysicalCamera ? (int)Camera.ProjectionMatrixMode.PhysicalPropertiesBased : (int)Camera.ProjectionMatrixMode.Implicit;
EditorGUILayout.EndHorizontal();
EditorGUI.EndProperty();
EditorGUI.showMixedValue = false;
if (isPhysicalCamera && !projectionMatrixMode.hasMultipleDifferentValues)
{
using (new EditorGUI.IndentLevelScope())
{
EditorGUILayout.PropertyField(iso, Styles.iso);
EditorGUILayout.PropertyField(shutterSpeed, Styles.shutterSpeed);
EditorGUILayout.PropertyField(aperture, Styles.aperture);
EditorGUILayout.PropertyField(focusDistance, Styles.focusDistance);
EditorGUILayout.PropertyField(bladeCount, Styles.bladeCount);
EditorGUILayout.PropertyField(curvature, Styles.curvature);
EditorGUILayout.PropertyField(barrelClipping, Styles.barrelClipping);
EditorGUILayout.PropertyField(anamorphism, Styles.anamorphism);
using (var horizontal = new EditorGUILayout.HorizontalScope())
using (new EditorGUI.PropertyScope(horizontal.rect, Styles.focalLength, focalLength))
using (var checkScope = new EditorGUI.ChangeCheckScope())
{
EditorGUI.showMixedValue = focalLength.hasMultipleDifferentValues;
var sensorLength = fovAxisVertical ? sensorSize.vector2Value.y : sensorSize.vector2Value.x;
var focalLengthVal = fovChanged ? Camera.FieldOfViewToFocalLength(fovNewValue, sensorLength) : focalLength.floatValue;
focalLengthVal = EditorGUILayout.FloatField(Styles.focalLength, focalLengthVal);
if (checkScope.changed || fovChanged)
focalLength.floatValue = focalLengthVal;
}
EditorGUI.showMixedValue = sensorSize.hasMultipleDifferentValues;
EditorGUI.BeginChangeCheck();
var filmGateIndex = Array.IndexOf(k_ApertureFormatValues, new Vector2((float)Math.Round(sensorSize.vector2Value.x, 3), (float)Math.Round(sensorSize.vector2Value.y, 3)));
if (filmGateIndex == -1)
filmGateIndex = EditorGUILayout.Popup(Styles.cameraType, k_ApertureFormats.Length - 1, k_ApertureFormats);
else
filmGateIndex = EditorGUILayout.Popup(Styles.cameraType, filmGateIndex, k_ApertureFormats);
EditorGUI.showMixedValue = false;
if (EditorGUI.EndChangeCheck() && filmGateIndex < k_ApertureFormatValues.Length)
{
sensorSize.vector2Value = k_ApertureFormatValues[filmGateIndex];
}
EditorGUILayout.PropertyField(sensorSize, Styles.sensorSize);
EditorGUILayout.PropertyField(lensShift, Styles.lensShift);
using (var horizontal = new EditorGUILayout.HorizontalScope())
using (var propertyScope = new EditorGUI.PropertyScope(horizontal.rect, Styles.gateFit, gateFit))
using (var checkScope = new EditorGUI.ChangeCheckScope())
{
var gateValue = (int)(Camera.GateFitMode)EditorGUILayout.EnumPopup(propertyScope.content, (Camera.GateFitMode)gateFit.intValue);
if (checkScope.changed)
gateFit.intValue = gateValue;
}
}
}
else if (fovChanged)
{
verticalFOV.floatValue = fovAxisVertical ? fovNewValue : Camera.HorizontalToVerticalFieldOfView(fovNewValue, (m_SerializedObject.targetObjects[0] as Camera).aspect);
}
EditorGUILayout.Space();
}
}
}
public void DrawClippingPlanes()
{
EditorGUILayout.PropertiesField(EditorGUI.s_ClipingPlanesLabel, new[] { nearClippingPlane, farClippingPlane }, EditorGUI.s_NearAndFarLabels, EditorGUI.kNearFarLabelsWidth);
}
public void DrawNormalizedViewPort()
{
EditorGUILayout.PropertyField(normalizedViewPortRect, Styles.viewportRect);
}
public void DrawDepth()
{
EditorGUILayout.PropertyField(depth);
}
public void DrawRenderingPath()
{
EditorGUILayout.IntPopup(renderingPath, k_CameraRenderPaths, k_CameraRenderPathValues, Styles.renderingPath);
}
public void DrawTargetTexture(bool deferred)
{
EditorGUILayout.PropertyField(targetTexture);
// show warning if we have deferred but manual MSAA set
// only do this if the m_TargetTexture has the same values across all target cameras
if (!deferred || targetTexture.hasMultipleDifferentValues)
return;
var renderTexture = this.targetTexture.objectReferenceValue as RenderTexture;
if (renderTexture && renderTexture.antiAliasing > 1)
EditorGUILayout.HelpBox(Styles.deferredMSAAWarning.text, MessageType.Warning, true);
}
public void DrawOcclusionCulling()
{
EditorGUILayout.PropertyField(occlusionCulling, Styles.allowOcclusionCulling);
}
public void DrawHDR()
{
var rect = EditorGUILayout.GetControlRect(true);
EditorGUI.BeginProperty(rect, Styles.allowHDR, HDR);
var value = HDR.boolValue ? 1 : 0;
value = EditorGUI.IntPopup(rect, Styles.allowHDR, value, k_DefaultOptions, k_DefaultOptionValues);
HDR.boolValue = value == 1;
EditorGUI.EndProperty();
}
public void DrawMSAA()
{
var rect = EditorGUILayout.GetControlRect(true);
EditorGUI.BeginProperty(rect, Styles.allowMSAA, allowMSAA);
var value = allowMSAA.boolValue ? 1 : 0;
value = EditorGUI.IntPopup(rect, Styles.allowMSAA, value, k_DefaultOptions, k_DefaultOptionValues);
allowMSAA.boolValue = value == 1;
EditorGUI.EndProperty();
}
public void DrawDynamicResolution()
{
EditorGUILayout.PropertyField(allowDynamicResolution, Styles.allowDynamicResolution);
if ((allowDynamicResolution.boolValue || allowDynamicResolution.hasMultipleDifferentValues) && !PlayerSettings.enableFrameTimingStats)
EditorGUILayout.HelpBox(Styles.dynamicResolutionTimingWarning.text, MessageType.Warning, true);
}
[Obsolete("This API is deprecated and will be removed. Please use XRManagement package instead.", false)]
public void DrawVR()
{
}
public void DrawMultiDisplay()
{
if (!showMultiDisplayOptions)
return;
var prevDisplay = targetDisplay.intValue;
EditorGUILayout.IntPopup(targetDisplay, DisplayUtility.GetDisplayNames(), DisplayUtility.GetDisplayIndices(), Styles.targetDisplay);
if (prevDisplay != targetDisplay.intValue)
PlayModeView.RepaintAll();
}
public void DrawTargetEye()
{
EditorGUILayout.IntPopup(targetEye, k_TargetEyes, k_TargetEyeValues, Styles.xrTargetEye);
}
public static void DrawCameraWarnings(Camera camera)
{
var warnings = camera.GetCameraBufferWarnings();
if (warnings.Length > 0)
EditorGUILayout.HelpBox(string.Join("\n\n", warnings), MessageType.Info, true);
}
}
readonly AnimatedBool m_ShowBGColorOptions = new();
readonly AnimatedBool m_ShowOrthoOptions = new();
readonly AnimatedBool m_ShowTargetEyeOption = new();
Camera camera => target as Camera;
Camera m_PreviewCamera;
[Obsolete("Preview camera is obsolete, use Overlays to create a Camera preview.")]
protected Camera previewCamera
{
get
{
if (m_PreviewCamera == null)
{
// Only log a warning once when creating the camera so that we don't flood the console with
// redundant logs.
Debug.LogWarning("Preview camera is obsolete, use Overlays to create a Camera preview.");
m_PreviewCamera = EditorUtility.CreateGameObjectWithHideFlags("Preview Camera", HideFlags.HideAndDontSave, typeof(Camera), typeof(Skybox)).GetComponent<Camera>();
}
m_PreviewCamera.enabled = false;
return m_PreviewCamera;
}
}
static bool showMultiDisplayOptions
{
get => ModuleManager.ShouldShowMultiDisplayOption();
}
bool wantsDeferredRendering
{
get
{
var isCamDeferred = camera.renderingPath == RenderingPath.DeferredShading;
var isTierDeferred = Rendering.EditorGraphicsSettings.GetCurrentTierSettings().renderingPath == RenderingPath.DeferredShading;
return isCamDeferred || (camera.renderingPath == RenderingPath.UsePlayerSettings && isTierDeferred);
}
}
internal bool showBackgroundColorOptions => !settings.clearFlags.hasMultipleDifferentValues && camera.clearFlags is CameraClearFlags.SolidColor or CameraClearFlags.Skybox;
internal bool showOrthographicOptions => !settings.orthographic.hasMultipleDifferentValues && settings.orthographic.boolValue;
internal bool showPerspectiveOptions => !settings.orthographic.hasMultipleDifferentValues && !settings.orthographic.boolValue;
internal bool showPhysicalCameraOptions => settings.projectionMatrixMode.intValue == (int)Camera.ProjectionMatrixMode.PhysicalPropertiesBased;
internal bool showOrthographicXRWarning => k_DisplayDescriptors.Count > 0 && settings.targetEye.intValue != (int)StereoTargetEyeMask.None && camera.orthographic && camera.targetTexture == null;
internal bool showOrthographicDeferredWarning => showOrthographicOptions && wantsDeferredRendering;
internal bool showDeferredMSAAWarning
{
get
{
// show warning if we have deferred but manual MSAA set
// only do this if the m_TargetTexture has the same values across all target cameras
var singleValue = !settings.targetTexture.hasMultipleDifferentValues;
var targetTextureValue = settings.targetTexture.objectReferenceValue as RenderTexture;
var wantsAntiAliasing = targetTextureValue != null && targetTextureValue.antiAliasing > 1;
return singleValue && wantsAntiAliasing && wantsDeferredRendering;
}
}
internal bool showDynamicResolutionTimingWarning => (settings.allowDynamicResolution.boolValue || settings.allowDynamicResolution.hasMultipleDifferentValues) && !PlayerSettings.enableFrameTimingStats;
bool showTargetEyeOption => settings.targetEye.intValue != (int)StereoTargetEyeMask.Both || k_DisplayDescriptors.Count > 0;
// Camera's depth texture mode is not serialized data, so can't get to it through
// serialized property (hence no multi-edit).
internal bool showDepthTextureMode => targets.Length == 1 && target is Camera { depthTextureMode: not DepthTextureMode.None };
// Command buffers are not serialized data, so can't get to them through
// serialized property (hence no multi-edit).
internal bool showCommandBufferGUI => targets.Length == 1 && target is Camera { commandBufferCount: > 0 };
internal enum ProjectionType
{
Perspective,
Orthographic
}
bool m_CommandBuffersShown = true;
Settings m_Settings;
protected internal Settings settings => m_Settings ??= new Settings(serializedObject);
internal static readonly List<XRDisplaySubsystemDescriptor> k_DisplayDescriptors = new();
uint m_LastNonSerializedVersion;
internal event Action onSettingsChanged;
static void OnReloadSubsystemsComplete()
{
SubsystemManager.GetSubsystemDescriptors(k_DisplayDescriptors);
}
public void OnEnable()
{
settings.OnEnable();
var c = (Camera)target;
m_ShowBGColorOptions.value = showBackgroundColorOptions;
m_ShowOrthoOptions.value = showOrthographicOptions;
m_ShowTargetEyeOption.value = showTargetEyeOption;
m_ShowBGColorOptions.valueChanged.AddListener(Repaint);
m_ShowOrthoOptions.valueChanged.AddListener(Repaint);
m_ShowTargetEyeOption.valueChanged.AddListener(Repaint);
SubsystemManager.GetSubsystemDescriptors(k_DisplayDescriptors);
SubsystemManager.afterReloadSubsystems += OnReloadSubsystemsComplete;
}
public void OnDestroy()
{
if (m_PreviewCamera != null)
DestroyImmediate(m_PreviewCamera.gameObject, true);
}
public void OnDisable()
{
m_ShowBGColorOptions.valueChanged.RemoveListener(Repaint);
m_ShowOrthoOptions.valueChanged.RemoveListener(Repaint);
m_ShowTargetEyeOption.valueChanged.RemoveListener(Repaint);
}
bool TryGetDepthTextureModeString(out string depthTextureModeString)
{
depthTextureModeString = string.Empty;
var buffers = new List<string>();
if ((camera.depthTextureMode & DepthTextureMode.Depth) != 0)
buffers.Add("Depth");
if ((camera.depthTextureMode & DepthTextureMode.DepthNormals) != 0)
buffers.Add("DepthNormals");
if ((camera.depthTextureMode & DepthTextureMode.MotionVectors) != 0)
buffers.Add("MotionVectors");
if (buffers.Count == 0)
return false;
var sb = new StringBuilder("Info: renders ");
for (var i = 0; i < buffers.Count; ++i)
{
if (i != 0)
sb.Append(" & ");
sb.Append(buffers[i]);
}
sb.Append(buffers.Count > 1 ? " textures" : " texture");
depthTextureModeString = sb.ToString();
return true;
}
void DepthTextureModeGUI()
{
if (!showDepthTextureMode || !TryGetDepthTextureModeString(out var depthTextureModeInfo))
return;
EditorGUILayout.HelpBox(depthTextureModeInfo, MessageType.None, true);
}
static Rect GetRemoveButtonRect(Rect r)
{
var buttonSize = Styles.invisibleButton.CalcSize(Styles.iconRemove);
return new Rect(r.xMax - buttonSize.x, r.y + (int)(r.height / 2 - buttonSize.y / 2), buttonSize.x, buttonSize.y);
}
/**
* Draws the 2D bounds of the camera when in 2D mode.
*/
[DrawGizmo(GizmoType.NonSelected)]
static void DrawCameraBound(Camera camera, GizmoType gizmoType)
{
if (!(SceneView.currentDrawingSceneView?.in2DMode ?? false))
return;
if (camera == Camera.main && camera.orthographic)
RenderGizmo(camera);
}
void CommandBufferGUI()
{
if(!showCommandBufferGUI)
return;
m_CommandBuffersShown = GUILayout.Toggle(m_CommandBuffersShown, GUIContent.Temp(camera.commandBufferCount + " command buffers"), EditorStyles.foldout);
if (!m_CommandBuffersShown)
return;
EditorGUI.indentLevel++;
foreach (var ce in (CameraEvent[])Enum.GetValues(typeof(CameraEvent)))
{
var cbs = camera.GetCommandBuffers(ce);
foreach (var cb in cbs)
{
using (new GUILayout.HorizontalScope())
{
// row with event & command buffer information label
var rowRect = GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.miniLabel);
rowRect.xMin += EditorGUI.indent;
var minusRect = GetRemoveButtonRect(rowRect);
rowRect.xMax = minusRect.x;
GUI.Label(rowRect, string.Format("{0}: {1} ({2})", ce, cb.name, EditorUtility.FormatBytes(cb.sizeInBytes)), EditorStyles.miniLabel);
// and a button to remove it
if (GUI.Button(minusRect, Styles.iconRemove, Styles.invisibleButton))
{
camera.RemoveCommandBuffer(ce, cb);
SceneView.RepaintAll();
PlayModeView.RepaintAll();
GUIUtility.ExitGUI();
}
}
}
}
// "remove all" button
using (new GUILayout.HorizontalScope())
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("Remove all", EditorStyles.miniButton))
{
camera.RemoveAllCommandBuffers();
SceneView.RepaintAll();
PlayModeView.RepaintAll();
}
}
EditorGUI.indentLevel--;
}
public override void OnInspectorGUI()
{
settings.Update();
var c = (Camera)target;
m_ShowBGColorOptions.target = showBackgroundColorOptions;
m_ShowOrthoOptions.target = showOrthographicOptions;
m_ShowTargetEyeOption.target = showTargetEyeOption;
settings.DrawClearFlags();
if (EditorGUILayout.BeginFadeGroup(m_ShowBGColorOptions.faded))
settings.DrawBackgroundColor();
EditorGUILayout.EndFadeGroup();
settings.DrawCullingMask();
EditorGUILayout.Space();
settings.DrawProjection();
if (showOrthographicXRWarning)
GUILayout.Label(Styles.orthoXRWarning);
settings.DrawClippingPlanes();
settings.DrawNormalizedViewPort();
EditorGUILayout.Space();
settings.DrawDepth();
settings.DrawRenderingPath();
if (showOrthographicDeferredWarning)
EditorGUILayout.HelpBox(Styles.orthoDeferredWarning.text, MessageType.Warning, true);
settings.DrawTargetTexture(wantsDeferredRendering);
settings.DrawOcclusionCulling();
settings.DrawHDR();
settings.DrawMSAA();
settings.DrawDynamicResolution();
foreach (Camera camera in targets)
{
if (camera != null)
{
Settings.DrawCameraWarnings(camera);
}
}
EditorGUILayout.Space();
settings.DrawMultiDisplay();
if (EditorGUILayout.BeginFadeGroup(m_ShowTargetEyeOption.faded))
settings.DrawTargetEye();
EditorGUILayout.EndFadeGroup();
DepthTextureModeGUI();
CommandBufferGUI();
serializedObject.ApplyModifiedProperties();
}
// marked obsolete @karlh 2021/02/13
[Obsolete("OnOverlayGUI is obsolete. Use global Cameras Overlay instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual void OnOverlayGUI(Object target, SceneView sceneView)
{
}
// marked obsolete @thomastu 2023/04/05
[Obsolete("CreatePreviewOverlay is obsolete. Use global Cameras Overlay instead.", false)]
public virtual Overlay CreatePreviewOverlay(Camera cam) => SceneViewCameraOverlay.GetOrCreateCameraOverlay(cam);
[RequiredByNativeCode]
internal static float GetGameViewAspectRatio()
{
var gameViewSize = PlayModeView.GetMainPlayModeViewTargetSize();
if (gameViewSize.x < 0f)
{
// Fallback to Scene View of not a valid game view size
gameViewSize.x = Screen.width;
gameViewSize.y = Screen.height;
}
return gameViewSize.x / gameViewSize.y;
}
[RequiredByNativeCode]
internal static void GetMainPlayModeViewSize(out Vector2 size)
{
size = PlayModeView.GetMainPlayModeViewTargetSize();
}
// Called from C++ when we need to render a Camera's gizmo
[RequiredByNativeCode]
internal static void RenderGizmo(Camera camera) => CameraEditorUtils.DrawFrustumGizmo(camera);
static Vector2 s_PreviousMainPlayModeViewTargetSize;
public virtual void OnSceneGUI()
{
if (!target)
return;
var c = (Camera)target;
if (!CameraEditorUtils.IsViewportRectValidToRender(c.rect))
return;
var currentMainPlayModeViewTargetSize = PlayModeView.GetMainPlayModeViewTargetSize();
if (s_PreviousMainPlayModeViewTargetSize != currentMainPlayModeViewTargetSize)
{
// a gameView size change can affect horizontal FOV, refresh the inspector when that happens.
Repaint();
s_PreviousMainPlayModeViewTargetSize = currentMainPlayModeViewTargetSize;
}
CameraEditorUtils.HandleFrustum(c, referenceTargetIndex);
}
static T ExtendedQuery<T>(VisualElement editor, string elementName, SerializedProperty property) where T : VisualElement
{
var content = EditorGUIUtility.TrTextContent(property.displayName, property.tooltip);
return ExtendedQuery<T>(editor, elementName, content);
}
static T ExtendedQuery<T>(VisualElement editor, string elementName, GUIContent content) where T : VisualElement
{
var result = editor.MandatoryQ<T>(elementName);
switch (result)
{
case PropertyField field:
field.label = content.text;
break;
case DropdownField field:
field.label = content.text;
break;
case EnumField field:
field.label = content.text;
break;
case Toggle toggle:
toggle.label = content.text;
break;
case Slider slider:
slider.label = content.text;
break;
case FloatField field:
field.label = content.text;
break;
case ClippingPlanes planes:
planes.label = content.text;
break;
case HelpBox box:
box.text = content.text;
break;
}
result.tooltip = content.tooltip;
return result;
}
public override VisualElement CreateInspectorGUI()
{
var editor = new VisualElement();
var c = (Camera)target;
var visualTree = EditorGUIUtility.Load(Styles.k_CameraEditorUxmlPath) as VisualTreeAsset;
visualTree?.CloneTree(editor);
var clearFlags = ExtendedQuery<PropertyField>(editor, Styles.k_ClearFlagsElementName, Styles.clearFlags);
var backgroundColor = ExtendedQuery<PropertyField>(editor, Styles.k_BackgroundElementName, Styles.background);
ExtendedQuery<PropertyField>(editor, Styles.k_CullingMaskElementName, Styles.allowOcclusionCulling);
var backgroundCheck = UIElementsEditorUtility.CreateDynamicVisibilityCallback(backgroundColor, () => showBackgroundColorOptions);
clearFlags.RegisterValueChangeCallback(e => backgroundCheck.Invoke());
SetupProjectionParameters(editor);
var clippingPlanes = ExtendedQuery<ClippingPlanes>(editor, Styles.k_ClippingPlanesElementName, EditorGUI.s_ClipingPlanesLabel);
clippingPlanes.nearClip = settings.nearClippingPlane;
clippingPlanes.farClip = settings.farClippingPlane;
ExtendedQuery<PropertyField>(editor, Styles.k_ViewportRectElementName, Styles.viewportRect);
ExtendedQuery<PropertyField>(editor, Styles.k_DepthElementName, settings.depth);
var renderingPath = ExtendedQuery<DropdownField>(editor, Styles.k_RenderingPathElementName, Styles.renderingPath);
var renderingPathUpdate = UIElementsEditorUtility.BindSerializedProperty(renderingPath, settings.renderingPath, Settings.k_CameraRenderPaths, Settings.k_CameraRenderPathValues);
var orthographicDeferredWarning = ExtendedQuery<HelpBox>(editor, Styles.k_OrthographicDeferredWarningElementName, Styles.orthoDeferredWarning);
var orthographicDeferrednCheck = UIElementsEditorUtility.CreateDynamicVisibilityCallback(orthographicDeferredWarning, () => showOrthographicDeferredWarning);
var deferredMSAAWarning = ExtendedQuery<HelpBox>(editor, Styles.k_DeferredMsaaWarningElementName, Styles.deferredMSAAWarning);
var deferredMSAACheck = UIElementsEditorUtility.CreateDynamicVisibilityCallback(deferredMSAAWarning, () => showDeferredMSAAWarning);
ExtendedQuery<PropertyField>(editor, Styles.k_TargetTextureElementName, settings.targetTexture);
ExtendedQuery<PropertyField>(editor, Styles.k_OcclusionCullingElementName, Styles.allowOcclusionCulling);
var hdr = ExtendedQuery<DropdownField>(editor, Styles.k_HdrElementName, Styles.allowHDR);
var msaa = ExtendedQuery<DropdownField>(editor, Styles.k_MsaaElementName, Styles.allowMSAA);
var hdrUpdate = UIElementsEditorUtility.BindSerializedProperty(hdr, settings.HDR, Settings.k_DefaultOptions, Settings.k_DefaultOptionValues);
var msaaUpdate = UIElementsEditorUtility.BindSerializedProperty(msaa, settings.allowMSAA, Settings.k_DefaultOptions, Settings.k_DefaultOptionValues);
ExtendedQuery<PropertyField>(editor, Styles.k_DynamicResolution, Styles.allowDynamicResolution);
var dynamicResolutionTimingWarning = ExtendedQuery<HelpBox>(editor, Styles.k_DynamicResolutionTimingWarningElementName, Styles.dynamicResolutionTimingWarning);
var dynamicResolutionTimingCheck = UIElementsEditorUtility.CreateDynamicVisibilityCallback(dynamicResolutionTimingWarning, () => showDynamicResolutionTimingWarning);
var cameraWarnings = editor.MandatoryQ<VisualElement>(Styles.k_CameraWarningsElementName);
var cameraWarningsUpdate = UIElementsEditorUtility.CreateDynamicVisibilityCallback(cameraWarnings, () =>
{
var visible = false;
cameraWarnings.Clear();
foreach (var target in targets)
{
if (target is not Camera camera)
continue;
var warnings = camera.GetCameraBufferWarnings();
if (warnings.Length == 0)
continue;
cameraWarnings.Add(new HelpBox(string.Join("\n\n", warnings), HelpBoxMessageType.Warning));
visible = true;
}
return visible;
});
Action targetDisplayCheck;
Action targetDisplayUpdate;
var targetDisplay = ExtendedQuery<DropdownField>(editor, Styles.k_TargetDisplayElementName, Styles.targetDisplay);
var choiceContents = DisplayUtility.GetDisplayNames();
targetDisplay.choices = new List<string>(choiceContents.Length);
foreach (var choiceContent in choiceContents)
targetDisplay.choices.Add(choiceContent.text);
targetDisplayCheck = UIElementsEditorUtility.CreateDynamicVisibilityCallback(targetDisplay, () => showMultiDisplayOptions);
targetDisplayUpdate = UIElementsEditorUtility.BindSerializedProperty(targetDisplay, settings.targetDisplay, DisplayUtility.GetDisplayNames(), DisplayUtility.GetDisplayIndices());
var targetEye = ExtendedQuery<DropdownField>(editor, Styles.k_TargetEyeElementName, Styles.xrTargetEye);
var targetEyeCheck = UIElementsEditorUtility.CreateDynamicVisibilityCallback(targetEye, () => showTargetEyeOption);
var targetEyeUpdate = UIElementsEditorUtility.BindSerializedProperty(targetEye, settings.targetEye, Settings.k_TargetEyes, Settings.k_TargetEyeValues);
var depthTextureMode = editor.MandatoryQ<HelpBox>(Styles.k_DepthTextureModeElementName);
var depthTextureModeCheck = UIElementsEditorUtility.CreateDynamicVisibilityCallback(depthTextureMode, () =>
{
if (!showDepthTextureMode || !TryGetDepthTextureModeString(out var info))
return false;
depthTextureMode.text = info;
return true;
});
var buffers = new List<CommandBuffer>();
var bufferEvents = new Dictionary<CommandBuffer, CameraEvent>();
var commandBuffers = editor.MandatoryQ<Foldout>(Styles.k_CommandBuffersElementName);
var list = commandBuffers.MandatoryQ<ListView>(Styles.k_CommandBuffersListElementName);
var commandBuffersUpdate = UIElementsEditorUtility.CreateDynamicVisibilityCallback(commandBuffers, () =>
{
commandBuffers.text = L10n.Tr($"{c.commandBufferCount} command buffers");
buffers.Clear();
bufferEvents.Clear();
foreach (var ce in (CameraEvent[])Enum.GetValues(typeof(CameraEvent)))
{
var cbs = camera.GetCommandBuffers(ce);
foreach (var cb in cbs)
{
buffers.Add(cb);
bufferEvents[cb] = ce;
}
}
list.Rebuild();
return showCommandBufferGUI;
});
list.makeItem = () =>
{
var entry = new VisualElement();
entry.AddToClassList(Styles.commandBufferUssClassName);
var label = new Label();
label.AddToClassList(Styles.commandBufferLabelUssClassName);
var button = new VisualElement();
button.AddToClassList(Styles.commandBufferRemoveButtonUssClassName);
button.RegisterCallback<ClickEvent>(e =>
{
var cameraEvent = (CameraEvent)entry.userData;
var commandBuffer = (CommandBuffer)label.userData;
camera.RemoveCommandBuffer(cameraEvent, commandBuffer);
SceneView.RepaintAll();
PlayModeView.RepaintAll();
commandBuffersUpdate?.Invoke();
});
entry.Add(label);
entry.Add(button);
return entry;
};
list.bindItem = (v, i) =>
{
var cb = buffers[i];
var ce = bufferEvents[cb];
var label = v.Q<Label>();
label.text = $"{ce}: {cb.name} ({EditorUtility.FormatBytes(cb.sizeInBytes)})";
label.userData = cb;
v.userData = ce;
};
list.itemsSource = buffers;
var removeAll = editor.MandatoryQ<Button>(Styles.k_CommandBuffersRemoveAllElementName);
removeAll.RegisterCallback<ClickEvent>(e =>
{
c.RemoveAllCommandBuffers();
SceneView.RepaintAll();
PlayModeView.RepaintAll();
commandBuffersUpdate?.Invoke();
});
onSettingsChanged += () =>
{
clippingPlanes.Update();
renderingPathUpdate?.Invoke();
hdrUpdate?.Invoke();
msaaUpdate?.Invoke();
targetDisplayUpdate?.Invoke();
targetEyeUpdate?.Invoke();
orthographicDeferrednCheck?.Invoke();
deferredMSAACheck?.Invoke();
dynamicResolutionTimingCheck?.Invoke();
depthTextureModeCheck?.Invoke();
cameraWarningsUpdate?.Invoke();
targetDisplayCheck?.Invoke();
targetEyeCheck?.Invoke();
commandBuffersUpdate?.Invoke();
};
editor.RegisterCallback<AttachToPanelEvent>(e => EditorApplication.tick += UpdateNonSerializedIfNeeded);
editor.RegisterCallback<DetachFromPanelEvent>(e => EditorApplication.tick -= UpdateNonSerializedIfNeeded);
editor.TrackSerializedObjectValue(serializedObject, (so) => onSettingsChanged?.Invoke());
return editor;
}
void UpdateNonSerializedIfNeeded()
{
if (m_LastNonSerializedVersion == camera.m_NonSerializedVersion)
return;
onSettingsChanged?.Invoke();
m_LastNonSerializedVersion = camera.m_NonSerializedVersion;
}
void SetupProjectionParameters(VisualElement contents)
{
var perspectiveGroup = contents.MandatoryQ<VisualElement>(Styles.k_PerspectiveGroupElementName);
var perspectiveGroupCheck = UIElementsEditorUtility.CreateDynamicVisibilityCallback(perspectiveGroup, () => showPerspectiveOptions);
var orthographicGroup = contents.MandatoryQ<VisualElement>(Styles.k_OrthographicGroupElementName);
var orthographicGroupCheck = UIElementsEditorUtility.CreateDynamicVisibilityCallback(orthographicGroup, () => showOrthographicOptions);
var projectionType = ExtendedQuery<EnumField>(contents, Styles.k_ProjectionTypeElementName, Styles.projection);
var projectionTypeUpdate = UIElementsEditorUtility.BindSerializedProperty<ProjectionType>(projectionType, settings.orthographic, _ =>
{
orthographicGroupCheck?.Invoke();
perspectiveGroupCheck?.Invoke();
});
var fovAxisMode = ExtendedQuery<EnumField>(contents, Styles.k_FovAxisModeElementName, Styles.FOVAxisMode);
var fovAxisModeUpdate = UIElementsEditorUtility.BindSerializedProperty<Camera.FieldOfViewAxis>(fovAxisMode, settings.fovAxisMode);
var fieldOfView = ExtendedQuery<Slider>(contents, Styles.k_FieldOfViewElementName, Styles.fieldOfView);
fieldOfView.SetEnabled(!fovAxisMode.showMixedValue);
var physicalCameraGroup = contents.MandatoryQ<VisualElement>(Styles.k_PhysicalCameraGroupElementName);
var physicalCameraGroupCheck = UIElementsEditorUtility.CreateDynamicVisibilityCallback(physicalCameraGroup, () => showPhysicalCameraOptions);
var physicalCamera = ExtendedQuery<Toggle>(contents, Styles.k_PhysicalCameraElementName, Styles.physicalCamera);
var physicalCameraUpdate = UIElementsEditorUtility.BindSerializedProperty(physicalCamera, settings.projectionMatrixMode,
p => p.intValue == (int)Camera.ProjectionMatrixMode.PhysicalPropertiesBased,
(v, p) =>
{
p.intValue = (int)(v ? Camera.ProjectionMatrixMode.PhysicalPropertiesBased : Camera.ProjectionMatrixMode.Implicit);
p.serializedObject.ApplyModifiedProperties();
physicalCameraGroupCheck?.Invoke();
});
ExtendedQuery<PropertyField>(contents, Styles.k_IsoElementName, Styles.iso);
ExtendedQuery<PropertyField>(contents, Styles.k_ShutterSpeedElementName, Styles.shutterSpeed);
ExtendedQuery<PropertyField>(contents, Styles.k_ApertureElementName, Styles.aperture);
ExtendedQuery<PropertyField>(contents, Styles.k_FocusDistanceElementName, Styles.focusDistance);
ExtendedQuery<PropertyField>(contents, Styles.k_BladeCountElementName, Styles.bladeCount);
ExtendedQuery<PropertyField>(contents, Styles.k_CurvatureElementName, Styles.curvature);
ExtendedQuery<PropertyField>(contents, Styles.k_BarrelClippingElementName, Styles.barrelClipping);
ExtendedQuery<PropertyField>(contents, Styles.k_AnamorphismElementName, Styles.anamorphism);
var fieldOfViewUpdate = UIElementsEditorUtility.BindSerializedProperty(fieldOfView, settings.verticalFOV,
p =>
{
var isPhysicalCamera = settings.projectionMatrixMode.intValue == (int)Camera.ProjectionMatrixMode.PhysicalPropertiesBased;
var fovAxisVertical = settings.fovAxisMode.intValue == (int)Camera.FieldOfViewAxis.Vertical;
var aspectRatio = isPhysicalCamera ? settings.sensorSize.vector2Value.x / settings.sensorSize.vector2Value.y : camera.aspect;
fieldOfView.lowValue = fovAxisVertical ? 0.00001f : Camera.VerticalToHorizontalFieldOfView(0.00001f, aspectRatio);
fieldOfView.highValue = fovAxisVertical ? 179.0f : Camera.VerticalToHorizontalFieldOfView(179.0f, aspectRatio);
return fovAxisVertical ? settings.verticalFOV.floatValue : Camera.VerticalToHorizontalFieldOfView(settings.verticalFOV.floatValue, aspectRatio);
},
(fov, p) =>
{
var isPhysicalCamera = settings.projectionMatrixMode.intValue == (int)Camera.ProjectionMatrixMode.PhysicalPropertiesBased;
var fovAxisVertical = settings.fovAxisMode.intValue == (int)Camera.FieldOfViewAxis.Vertical;
var aspectRatio = isPhysicalCamera ? settings.sensorSize.vector2Value.x / settings.sensorSize.vector2Value.y : camera.aspect;
p.floatValue = fovAxisVertical ? fov : Camera.HorizontalToVerticalFieldOfView(fov, aspectRatio);
p.serializedObject.ApplyModifiedProperties();
});
var focalLength = ExtendedQuery<FloatField>(contents, Styles.k_FocalLengthElementName, Styles.focalLength);
var focalLengthUpdate = UIElementsEditorUtility.BindSerializedProperty(focalLength, settings.focalLength,
p =>
{
var fovAxisVertical = settings.fovAxisMode.intValue == (int)Camera.FieldOfViewAxis.Vertical;
var sensorLength = fovAxisVertical ? settings.sensorSize.vector2Value.y : settings.sensorSize.vector2Value.x;
return Camera.FieldOfViewToFocalLength(fieldOfView.value, sensorLength);
},
(v, p) =>
{
var isPhysicalCamera = settings.projectionMatrixMode.intValue == (int)Camera.ProjectionMatrixMode.PhysicalPropertiesBased;
if (!isPhysicalCamera)
return;
p.floatValue = v;
p.serializedObject.ApplyModifiedProperties();
});
var sensorType = ExtendedQuery<DropdownField>(contents, Styles.k_SensorTypeElementName, Styles.cameraType);
sensorType.choices = new List<string>(Settings.k_ApertureFormats.Length);
foreach (var apertureFormat in Settings.k_ApertureFormats)
sensorType.choices.Add(apertureFormat);
var sensorTypeUpdate = UIElementsEditorUtility.BindSerializedProperty(sensorType, settings.sensorSize,
p =>
{
var approximateApertureFormat = new Vector2((float)Math.Round(p.vector2Value.x, 3), (float)Math.Round(p.vector2Value.y, 3));
var index = Array.IndexOf(Settings.k_ApertureFormatValues, approximateApertureFormat);
return index >= 0 ? index : Settings.k_ApertureFormatValues.Length;
},
(i, p) =>
{
if (i < 0 || i >= Settings.k_ApertureFormatValues.Length)
return;
p.vector2Value = Settings.k_ApertureFormatValues[i];
p.serializedObject.ApplyModifiedProperties();
});
ExtendedQuery<PropertyField>(contents, Styles.k_SensorSizeElementName, Styles.sensorSize);
ExtendedQuery<PropertyField>(contents, Styles.k_LensShiftElementName, Styles.lensShift);
var gateFit = ExtendedQuery<EnumField>(contents, Styles.k_GateFitElementName, Styles.gateFit);
var gateFitUpdate = UIElementsEditorUtility.BindSerializedProperty<Camera.GateFitMode>(gateFit, settings.gateFit);
// Cannot bind serialized properties with spaces in them via UI Builder
var orthographicSize = ExtendedQuery<PropertyField>(contents, Styles.k_OrthographicSizeElementName, Styles.size);
orthographicSize.BindProperty(settings.orthographicSize);
var orthographicXRWarning = ExtendedQuery<HelpBox>(contents, Styles.k_OrthographicXrWarningElementName, Styles.orthoXRWarning);
var orthographicXRCheck = UIElementsEditorUtility.CreateDynamicVisibilityCallback(orthographicXRWarning, () => showOrthographicXRWarning);
onSettingsChanged += () =>
{
projectionTypeUpdate?.Invoke();
fovAxisModeUpdate?.Invoke();
physicalCameraUpdate?.Invoke();
fieldOfViewUpdate?.Invoke();
focalLengthUpdate?.Invoke();
sensorTypeUpdate?.Invoke();
gateFitUpdate?.Invoke();
orthographicXRCheck?.Invoke();
physicalCameraGroupCheck?.Invoke();
};
}
}
}
| UnityCsReference/Editor/Mono/Inspector/CameraEditor.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/CameraEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 30565
} | 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.IO;
using System.Linq;
using UnityEngine;
using UnityEditorInternal;
namespace UnityEditor.AddComponent
{
class NewScriptDropdownItem : ComponentDropdownItem
{
private readonly char[] kInvalidPathChars = new char[] {'<', '>', ':', '"', '|', '?', '*', (char)0};
private readonly char[] kPathSepChars = new char[] {'/', '\\'};
private string m_Directory = string.Empty;
internal string m_ClassName = "NewBehaviourScript";
public string className
{
set { m_ClassName = value; }
get { return m_ClassName; }
}
public NewScriptDropdownItem()
: base("New Script", L10n.Tr("New Script"))
{
}
internal bool CanCreate()
{
return m_ClassName.Length > 0 &&
!ClassNameIsInvalid() &&
!File.Exists(TargetPath()) &&
!ClassAlreadyExists() &&
!InvalidTargetPath();
}
public string GetError()
{
// Create string to tell the user what the problem is
var blockReason = string.Empty;
if (m_ClassName != string.Empty)
{
if (ClassNameIsInvalid())
blockReason = "The script name may only consist of a-z, A-Z, 0-9, _.";
else if (File.Exists(TargetPath()))
blockReason = "A script called \"" + m_ClassName + "\" already exists at that path.";
else if (ClassAlreadyExists())
blockReason = "A class called \"" + m_ClassName + "\" already exists.";
else if (InvalidTargetPath())
blockReason = "The folder path contains invalid characters.";
}
return blockReason;
}
internal void Create(GameObject[] gameObjects, string searchString)
{
if (!CanCreate())
return;
CreateScript();
foreach (var go in gameObjects)
{
var script = AssetDatabase.LoadAssetAtPath(TargetPath(), typeof(MonoScript)) as MonoScript;
script.SetScriptTypeWasJustCreatedFromComponentMenu();
InternalEditorUtility.AddScriptComponentUncheckedUndoable(go, script);
}
}
private bool InvalidTargetPath()
{
if (m_Directory.IndexOfAny(kInvalidPathChars) >= 0)
return true;
if (TargetDir().Split(kPathSepChars, StringSplitOptions.None).Contains(string.Empty))
return true;
return false;
}
private string TargetPath()
{
return Path.Combine(TargetDir(), m_ClassName + ".cs");
}
private string TargetDir()
{
return Path.Combine("Assets", m_Directory.Trim(kPathSepChars));
}
private bool ClassNameIsInvalid()
{
return !System.CodeDom.Compiler.CodeGenerator.IsValidLanguageIndependentIdentifier(m_ClassName);
}
private bool ClassExists(string className)
{
return AppDomain.CurrentDomain.GetAssemblies()
.Any(a => a.GetType(className, false) != null);
}
private bool ClassAlreadyExists()
{
if (m_ClassName == string.Empty)
return false;
return ClassExists(m_ClassName);
}
private string GetTemplatePath()
{
var scriptTemplatePath = AssetsMenuUtility.GetScriptTemplatePath(ScriptTemplate.CSharp_NewBehaviourScript);
var scriptTemplateFilename = scriptTemplatePath.Substring(scriptTemplatePath.LastIndexOf('/'));
var localScriptTemplatePath = $"Assets/ScriptTemplates/{scriptTemplateFilename}";
if(File.Exists(localScriptTemplatePath))
return localScriptTemplatePath;
return scriptTemplatePath;
}
private void CreateScript()
{
ProjectWindowUtil.CreateScriptAssetFromTemplate(TargetPath(), GetTemplatePath());
AssetDatabase.Refresh();
}
}
}
| UnityCsReference/Editor/Mono/Inspector/Core/AddComponent/NewScriptDropdownItem.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/Core/AddComponent/NewScriptDropdownItem.cs",
"repo_id": "UnityCsReference",
"token_count": 1970
} | 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 UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor
{
internal class InspectorPreviewWindow : VisualElement
{
internal class Styles
{
public static readonly string ussClassName = "unity-preview-pane";
public static readonly string uxmlPath = "UXML/InspectorWindow/InspectorPreview.uxml";
public static readonly string ussPath = "StyleSheets/InspectorWindow/InspectorPreview.uss";
public static readonly string controlsUssPath = "StyleSheets/InspectorWindow/InspectorPreviewControls.uss";
public static readonly string titleName = "title";
public static readonly string previewName = "inspector-preview";
public static readonly string contentContainerName = "content-container";
public static readonly string toolbarName = "toolbar";
public static readonly string elipsisMenuName = "ellipsis-menu";
public static readonly string headerName = "header";
public static readonly string dropdownButton = "unity-dropdown-button";
public static readonly string basePopupFieldArrow = "unity-base-popup-field__arrow";
public static readonly string previewPopupFieldArrow = "unity-dropdown-arrow";
}
VisualElement m_Container;
VisualElement m_Toolbar;
ToolbarMenu m_EllipsisMenu;
public VisualElement GetButtonPane() { return m_Toolbar; }
public VisualElement GetPreviewPane() { return m_Container; }
public InspectorPreviewWindow()
{
AddToClassList(Styles.ussClassName);
var visualAsset = EditorGUIUtility.Load(Styles.uxmlPath) as VisualTreeAsset;
visualAsset.CloneTree(this);
AddStyleSheetPath(Styles.ussPath);
AddStyleSheetPath(Styles.controlsUssPath);
name = Styles.previewName;
m_Container = this.Q(Styles.contentContainerName);
m_Toolbar = this.Q(Styles.toolbarName);
focusable = true;
m_EllipsisMenu = this.Q<ToolbarMenu>(Styles.elipsisMenuName);
m_EllipsisMenu.style.display = DisplayStyle.Flex;
}
public void AppendActionToEllipsisMenu(string actionName,
Action<DropdownMenuAction> action,
Func<DropdownMenuAction, DropdownMenuAction.Status> actionStatusCallback,
object userData = null)
{
m_EllipsisMenu.menu.AppendAction(actionName, action, actionStatusCallback, userData);
}
public void ClearEllipsisMenu()
{
m_EllipsisMenu.menu.ClearItems();
}
public void AddButton(string propertyName, Texture2D image, Action clickEvent)
{
if (m_Toolbar.Q(propertyName) != null)
return;
var button = new Button(clickEvent);
button.name = propertyName;
button.style.backgroundImage = image;
m_Toolbar.Add(button);
}
public void UpdateButtonIcon(string propertyName, Texture2D image)
{
var button = m_Toolbar.Q(propertyName);
if (button == null)
return;
button.style.backgroundImage = image;
}
public void AddDropdownWithIcon(string propertyName, Texture2D image, Action clickEvent)
{
if (m_Toolbar.Q(propertyName) != null)
return;
var dropdown = new Button(clickEvent);
dropdown.name = propertyName;
dropdown.AddToClassList(Styles.dropdownButton);
var icon = new Image();
icon.image = image;
var arrow = new VisualElement();
arrow.AddToClassList(Styles.basePopupFieldArrow);
arrow.AddToClassList(Styles.previewPopupFieldArrow);
dropdown.style.flexDirection = FlexDirection.Row;
dropdown.Add(icon);
dropdown.Add(arrow);
m_Toolbar.Add(dropdown);
}
public override VisualElement contentContainer => m_Container == null ? this : m_Container;
}
}
| UnityCsReference/Editor/Mono/Inspector/Core/InspectorPreviewWindow.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/Core/InspectorPreviewWindow.cs",
"repo_id": "UnityCsReference",
"token_count": 1834
} | 320 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using uei = UnityEngine.Internal;
using System;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.Bindings;
using UnityEngine.Scripting;
using Object = UnityEngine.Object;
namespace UnityEditor
{
[StructLayout(LayoutKind.Sequential)]
[RequiredByNativeCode]
[NativeHeader("Editor/Mono/Inspector/Core/ScriptBindings/Editor.bindings.h")]
[StaticAccessor("EditorBindings", StaticAccessorType.DoubleColon)]
public partial class Editor
{
// Make a custom editor for /targetObject/ or /objects/.
extern static Editor CreateEditorWithContextInternal(Object[] targetObjects, Object context, Type editorType);
internal extern static Vector2 GetCurrentMousePosition();
}
}
| UnityCsReference/Editor/Mono/Inspector/Core/ScriptBindings/Editor.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/Core/ScriptBindings/Editor.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 277
} | 321 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
using UnityEditor;
using UnityEngine.Rendering;
using System;
namespace UnityEditor
{
[CustomEditor(typeof(LightmapParameters))]
[CanEditMultipleObjects]
class LightmapParametersEditor : Editor
{
SerializedProperty m_Resolution;
SerializedProperty m_ClusterResolution;
SerializedProperty m_IrradianceBudget;
SerializedProperty m_IrradianceQuality;
SerializedProperty m_BackFaceTolerance;
SerializedProperty m_ModellingTolerance;
SerializedProperty m_EdgeStitching;
SerializedProperty m_SystemTag;
SerializedProperty m_IsTransparent;
SerializedProperty m_Pushoff;
SerializedProperty m_BakedLightmapTag;
SerializedProperty m_LimitLightmapCount;
SerializedProperty m_LightmapMaxCount;
SerializedProperty m_AntiAliasingSamples;
SavedBool m_RealtimeGISettings;
SavedBool m_BakedGISettings;
SavedBool m_GeneralParametersSettings;
public void OnEnable()
{
m_Resolution = serializedObject.FindProperty("resolution");
m_ClusterResolution = serializedObject.FindProperty("clusterResolution");
m_IrradianceBudget = serializedObject.FindProperty("irradianceBudget");
m_IrradianceQuality = serializedObject.FindProperty("irradianceQuality");
m_BackFaceTolerance = serializedObject.FindProperty("backFaceTolerance");
m_ModellingTolerance = serializedObject.FindProperty("modellingTolerance");
m_EdgeStitching = serializedObject.FindProperty("edgeStitching");
m_IsTransparent = serializedObject.FindProperty("isTransparent");
m_SystemTag = serializedObject.FindProperty("systemTag");
m_AntiAliasingSamples = serializedObject.FindProperty("antiAliasingSamples");
m_BakedLightmapTag = serializedObject.FindProperty("bakedLightmapTag");
m_Pushoff = serializedObject.FindProperty("pushoff");
m_LimitLightmapCount = serializedObject.FindProperty("limitLightmapCount");
m_LightmapMaxCount = serializedObject.FindProperty("maxLightmapCount");
m_RealtimeGISettings = new SavedBool("LightmapParameters.ShowRealtimeGISettings", true);
m_BakedGISettings = new SavedBool("LightmapParameters.ShowBakedGISettings", true);
m_GeneralParametersSettings = new SavedBool("LightmapParameters.ShowGeneralParametersSettings", true);
}
public override bool UseDefaultMargins()
{
return false;
}
public override void OnInspectorGUI()
{
serializedObject.Update();
// realtime settings
if (SupportedRenderingFeatures.IsLightmapBakeTypeSupported(LightmapBakeType.Realtime))
{
m_RealtimeGISettings.value = EditorGUILayout.FoldoutTitlebar(m_RealtimeGISettings.value, Styles.precomputedRealtimeGIContent, true);
if (m_RealtimeGISettings.value)
{
++EditorGUI.indentLevel;
EditorGUILayout.PropertyField(m_Resolution, Styles.resolutionContent);
EditorGUILayout.Slider(m_ClusterResolution, 0.1F, 1.0F, Styles.clusterResolutionContent);
EditorGUILayout.IntSlider(m_IrradianceBudget, 32, 2048, Styles.irradianceBudgetContent);
if (m_IrradianceQuality.hasMultipleDifferentValues)
{
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = true;
int newValue = (int) EditorGUILayout.LogarithmicIntSlider(Styles.irradianceQualityContent, value: m_IrradianceQuality.intValue, leftValue: 512, rightValue: 131072, logbase: 2, 512, 131072);
if (EditorGUI.EndChangeCheck())
m_IrradianceQuality.intValue = newValue;
EditorGUI.showMixedValue = false;
}
else
m_IrradianceQuality.intValue = EditorGUILayout.LogarithmicIntSlider(Styles.irradianceQualityContent, value: m_IrradianceQuality.intValue, leftValue: 512, rightValue: 131072, logbase: 2, 512, 131072);
EditorGUILayout.Slider(m_ModellingTolerance, 0.0f, 1.0f, Styles.modellingToleranceContent);
EditorGUILayout.PropertyField(m_EdgeStitching, Styles.edgeStitchingContent);
EditorGUILayout.PropertyField(m_IsTransparent, Styles.isTransparent);
EditorGUILayout.PropertyField(m_SystemTag, Styles.systemTagContent);
EditorGUILayout.Space();
--EditorGUI.indentLevel;
}
}
m_BakedGISettings.value = EditorGUILayout.FoldoutTitlebar(m_BakedGISettings.value, Styles.bakedGIContent, true);
if (m_BakedGISettings.value)
{
EditorGUI.indentLevel++;
if (m_AntiAliasingSamples.hasMultipleDifferentValues)
{
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = true;
int fieldValue = EditorGUILayout.IntPopup(Styles.antiAliasingSamplesContent, m_AntiAliasingSamples.intValue, Styles.antiAliasingSamplesStrings, Styles.antiAliasingSampleValues);
if (EditorGUI.EndChangeCheck())
m_AntiAliasingSamples.intValue = fieldValue;
EditorGUI.showMixedValue = false;
}
else
{
int fieldValue = EditorGUILayout.IntPopup(Styles.antiAliasingSamplesContent, m_AntiAliasingSamples.intValue, Styles.antiAliasingSamplesStrings, Styles.antiAliasingSampleValues);
m_AntiAliasingSamples.intValue = fieldValue;
}
const float minPushOff = 0.0001f; // Keep in sync with PLM_MIN_PUSHOFF
EditorGUILayout.Slider(m_Pushoff, minPushOff, 1.0f, Styles.pushoffContent);
EditorGUILayout.PropertyField(m_BakedLightmapTag, Styles.bakedLightmapTagContent);
m_LimitLightmapCount.boolValue = EditorGUILayout.Toggle(Styles.limitLightmapCount, m_LimitLightmapCount.boolValue);
if (m_LimitLightmapCount.boolValue)
{
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(m_LightmapMaxCount, Styles.lightmapMaxCount);
EditorGUI.indentLevel--;
}
EditorGUI.indentLevel--;
}
m_GeneralParametersSettings.value = EditorGUILayout.FoldoutTitlebar(m_GeneralParametersSettings.value, Styles.generalGIContent, true);
if (m_GeneralParametersSettings.value)
{
++EditorGUI.indentLevel;
EditorGUILayout.Slider(m_BackFaceTolerance, 0.0f, 1.0f, Styles.backFaceToleranceContent);
--EditorGUI.indentLevel;
}
serializedObject.ApplyModifiedProperties();
}
internal override void OnHeaderControlsGUI()
{
GUILayoutUtility.GetRect(10, 10, 16, 16, EditorStyles.layerMaskField);
GUILayout.FlexibleSpace();
}
private class Styles
{
public static readonly int[] antiAliasingSampleValues = (int[]) Enum.GetValues(typeof(LightmapParameters.AntiAliasingSamples));
public static readonly GUIContent[] antiAliasingSamplesStrings =
{
EditorGUIUtility.TrTextContent("1"),
EditorGUIUtility.TrTextContent("4"),
EditorGUIUtility.TrTextContent("16")
};
public static readonly GUIContent generalGIContent = EditorGUIUtility.TrTextContent("General Parameters", "Settings used in both Precomputed Realtime Global Illumination and Baked Global Illumination.");
public static readonly GUIContent precomputedRealtimeGIContent = EditorGUIUtility.TrTextContent("Realtime Global Illumination", "Settings used in Precomputed Realtime Global Illumination where it is precomputed how indirect light can bounce between static objects, but the final lighting is done at runtime. Lights, ambient lighting in addition to the materials and emission of static objects can still be changed at runtime. Only static objects can affect GI by blocking and bouncing light, but non-static objects can receive bounced light via light probes."); // Reuse the label from the Lighting window
public static readonly GUIContent resolutionContent = EditorGUIUtility.TrTextContent("Resolution", "Realtime lightmap resolution in texels per world unit. This value is multiplied by the realtime resolution in the Lighting window to give the output lightmap resolution. This should generally be an order of magnitude less than what is common for baked lightmaps to keep the precompute time manageable and the performance at runtime acceptable. Note that if this is made more fine-grained, then the Irradiance Budget will often need to be increased too, to fully take advantage of this increased detail.");
public static readonly GUIContent clusterResolutionContent = EditorGUIUtility.TrTextContent("Cluster Resolution", "The ratio between the resolution of the clusters with which light bounce is calculated and the resolution of the output lightmaps that sample from these.");
public static readonly GUIContent irradianceBudgetContent = EditorGUIUtility.TrTextContent("Irradiance Budget", "The amount of data used by each texel in the output lightmap. Specifies how fine-grained a view of the scene an output texel has. Small values mean more averaged out lighting, since the light contributions from more clusters are treated as one. Affects runtime memory usage and to a lesser degree runtime CPU usage.");
public static readonly GUIContent irradianceQualityContent = EditorGUIUtility.TrTextContent("Irradiance Quality", "The number of rays to cast to compute which clusters affect a given output lightmap texel - the granularity of how this is saved is defined by the Irradiance Budget. Affects the speed of the precomputation but has no influence on runtime performance.");
public static readonly GUIContent backFaceToleranceContent = EditorGUIUtility.TrTextContent("Backface Tolerance", "Defines the percentage of rays which must hit front-facing geometry for the lightmapper to consider a texel valid. Increasing this number increases the likelihood that texels will be invalidated when backfaces can be seen. Invalid texels will then receive dilation.");
public static readonly GUIContent modellingToleranceContent = EditorGUIUtility.TrTextContent("Modelling Tolerance", "Maximum size of gaps that can be ignored for GI.");
public static readonly GUIContent edgeStitchingContent = EditorGUIUtility.TrTextContent("Edge Stitching", "If enabled, ensures that UV charts (aka UV islands) in the generated lightmaps blend together where they meet so there is no visible seam between them.");
public static readonly GUIContent systemTagContent = EditorGUIUtility.TrTextContent("System Tag", "Systems are groups of objects whose lightmaps are in the same atlas. It is also the granularity at which dependencies are calculated. Multiple systems are created automatically if the scene is big enough, but it can be helpful to be able to split them up manually for e.g. streaming in sections of a level. The system tag lets you force an object into a different realtime system even though all the other parameters are the same.");
public static readonly GUIContent bakedGIContent = EditorGUIUtility.TrTextContent("Baked Global Illumination", "Settings used in Baked Global Illumination where direct and indirect lighting for static objects is precalculated and saved (baked) into lightmaps for use at runtime. This is useful when lights are known to be static, for mobile, for low end devices and other situations where there is not enough processing power to use Precomputed Realtime GI. You can toggle on each light whether it should be included in the bake."); // Reuse the label from the Lighting window
public static readonly GUIContent antiAliasingSamplesContent = EditorGUIUtility.TrTextContent("Anti-aliasing Samples", "How many samples to use when antialiasing lightmap texels. Ray positions and normals buffers are also increased in size by this value. Higher values improve lightmap quality but also multiply memory usage when baking. A value of 1 disables supersampling.");
public static readonly GUIContent isTransparent = EditorGUIUtility.TrTextContent("Is Transparent", "If enabled, the object appears transparent during GlobalIllumination lighting calculations. Backfaces are not contributing to and light travels through the surface. This is useful for emissive invisible surfaces.");
public static readonly GUIContent pushoffContent = EditorGUIUtility.TrTextContent("Pushoff", "The amount to push off geometry for ray tracing, in modelling units. It is applied to all baked light maps, so it will affect direct light, indirect light and AO. Useful for getting rid of unwanted AO or shadowing.");
public static readonly GUIContent bakedLightmapTagContent = EditorGUIUtility.TrTextContent("Baked Tag", "An integer that lets you force an object into a different baked lightmap even though all the other parameters are the same. This can be useful e.g. when streaming in sections of a level.");
public static readonly GUIContent limitLightmapCount = EditorGUIUtility.TrTextContent("Limit Lightmap Count", "If enabled, objects with the same baked GI settings will be packed into a specified number of lightmaps. This may reduce the objects' lightmap resolution.");
public static readonly GUIContent lightmapMaxCount = EditorGUIUtility.TrTextContent("Max Lightmaps", "The maximum number of lightmaps into which objects will be packed.");
}
}
}
| UnityCsReference/Editor/Mono/Inspector/Enlighten/LightmapParameters.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/Enlighten/LightmapParameters.cs",
"repo_id": "UnityCsReference",
"token_count": 5411
} | 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;
namespace UnityEditor
{
internal class LayoutDropdownWindow : PopupWindowContent
{
class Styles
{
public Color tableHeaderColor;
public Color tableLineColor;
public Color parentColor;
public Color selfColor;
public Color simpleAnchorColor;
public Color stretchAnchorColor;
public Color anchorCornerColor;
public Color pivotColor;
public GUIStyle frame;
public GUIStyle label = new GUIStyle(EditorStyles.miniLabel);
public Styles()
{
frame = new GUIStyle();
Texture2D tex = new Texture2D(4, 4);
tex.SetPixels(new Color[]
{
Color.white, Color.white, Color.white, Color.white,
Color.white, Color.clear, Color.clear, Color.white,
Color.white, Color.clear, Color.clear, Color.white,
Color.white, Color.white, Color.white, Color.white
});
tex.filterMode = FilterMode.Point;
tex.Apply();
tex.hideFlags = HideFlags.HideAndDontSave;
frame.normal.background = tex;
frame.border = new RectOffset(2, 2, 2, 2);
label.alignment = TextAnchor.LowerCenter;
if (EditorGUIUtility.isProSkin)
{
tableHeaderColor = new Color(0.18f, 0.18f, 0.18f, 1);
tableLineColor = new Color(1, 1, 1, 0.3f);
parentColor = new Color(0.4f, 0.4f, 0.4f, 1);
selfColor = new Color(0.6f, 0.6f, 0.6f, 1);
simpleAnchorColor = new Color(0.7f, 0.3f, 0.3f, 1);
stretchAnchorColor = new Color(0.0f, 0.6f, 0.8f, 1);
anchorCornerColor = new Color(0.8f, 0.6f, 0.0f, 1);
pivotColor = new Color(0.0f, 0.6f, 0.8f, 1);
}
else
{
tableHeaderColor = new Color(0.8f, 0.8f, 0.8f, 1);
tableLineColor = new Color(0, 0, 0, 0.5f);
parentColor = new Color(0.55f, 0.55f, 0.55f, 1);
selfColor = new Color(0.2f, 0.2f, 0.2f, 1);
simpleAnchorColor = new Color(0.8f, 0.3f, 0.3f, 1);
stretchAnchorColor = new Color(0.2f, 0.5f, 0.9f, 1);
anchorCornerColor = new Color(0.6f, 0.4f, 0.0f, 1);
pivotColor = new Color(0.2f, 0.5f, 0.9f, 1);
}
}
}
static Styles s_Styles;
SerializedProperty m_AnchorMin;
SerializedProperty m_AnchorMax;
Vector2[,] m_InitValues;
const int kTopPartHeight = 38;
static float[] kPivotsForModes = new float[] { 0, 0.5f, 1, 0.5f, 0.5f }; // Only for actual modes, not for Undefined.
static string[] kHLabels = new string[] { "custom", "left", "center", "right", "stretch", "%" };
static string[] kVLabels = new string[] { "custom", "top", "middle", "bottom", "stretch", "%" };
public enum LayoutMode { Undefined = -1, Min = 0, Middle = 1, Max = 2, Stretch = 3 }
public LayoutDropdownWindow(SerializedObject so)
{
m_AnchorMin = so.FindProperty("m_AnchorMin");
m_AnchorMax = so.FindProperty("m_AnchorMax");
var targetObjects = so.targetObjects;
m_InitValues = new Vector2[targetObjects.Length, 4];
for (int i = 0; i < targetObjects.Length; i++)
{
RectTransform gui = targetObjects[i] as RectTransform;
m_InitValues[i, 0] = gui.anchorMin;
m_InitValues[i, 1] = gui.anchorMax;
m_InitValues[i, 2] = gui.anchoredPosition;
m_InitValues[i, 3] = gui.sizeDelta;
}
}
public override void OnOpen()
{
EditorApplication.modifierKeysChanged += editorWindow.Repaint;
}
public override void OnClose()
{
EditorApplication.modifierKeysChanged -= editorWindow.Repaint;
}
public override Vector2 GetWindowSize()
{
return new Vector2(262, 262 + kTopPartHeight);
}
public override void OnGUI(Rect rect)
{
if (s_Styles == null)
s_Styles = new Styles();
if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Return)
editorWindow.Close();
if (Event.current.type == EventType.MouseDown && Event.current.clickCount == 2 && rect.Contains(Event.current.mousePosition))
{
Event.current.Use();
editorWindow.Close();
}
GUI.Label(new Rect(rect.x + 5, rect.y + 3, rect.width - 10, 16), EditorGUIUtility.TrTextContent("Anchor Presets"), EditorStyles.boldLabel);
GUI.Label(new Rect(rect.x + 5, rect.y + 3 + 16, rect.width - 10, 16), EditorGUIUtility.TrTextContent("Shift: Also set pivot Alt: Also set position"), EditorStyles.label);
Color oldColor = GUI.color;
GUI.color = s_Styles.tableLineColor * oldColor;
GUI.DrawTexture(new Rect(0, kTopPartHeight - 1, 400, 1), EditorGUIUtility.whiteTexture);
GUI.color = oldColor;
GUI.BeginGroup(new Rect(rect.x, rect.y + kTopPartHeight, rect.width, rect.height - kTopPartHeight));
TableGUI(rect);
GUI.EndGroup();
}
static LayoutMode SwappedVMode(LayoutMode vMode)
{
if (vMode == LayoutMode.Min)
return LayoutMode.Max;
else if (vMode == LayoutMode.Max)
return LayoutMode.Min;
return vMode;
}
internal static void DrawLayoutModeHeadersOutsideRect(Rect rect,
SerializedProperty anchorMin,
SerializedProperty anchorMax,
SerializedProperty position,
SerializedProperty sizeDelta)
{
LayoutMode hMode = GetLayoutModeForAxis(anchorMin, anchorMax, 0);
LayoutMode vMode = GetLayoutModeForAxis(anchorMin, anchorMax, 1);
vMode = SwappedVMode(vMode);
DrawLayoutModeHeaderOutsideRect(rect, 0, hMode);
DrawLayoutModeHeaderOutsideRect(rect, 1, vMode);
}
internal static void DrawLayoutModeHeaderOutsideRect(Rect position, int axis, LayoutMode mode)
{
Rect headerRect = new Rect(position.x, position.y - 16, position.width, 16);
Matrix4x4 normalMatrix = GUI.matrix;
if (axis == 1)
GUIUtility.RotateAroundPivot(-90, position.center);
int index = (int)(mode) + 1;
GUI.Label(headerRect, axis == 0 ? kHLabels[index] : kVLabels[index], s_Styles.label);
GUI.matrix = normalMatrix;
}
void TableGUI(Rect rect)
{
int padding = 6;
int size = 31 + padding * 2;
int spacing = 0;
int[] groupings = new int[] { 15, 30, 30, 30, 45, 45 };
Color oldColor = GUI.color;
int headerW = 62;
GUI.color = s_Styles.tableHeaderColor * oldColor;
GUI.DrawTexture(new Rect(0, 0, 400, headerW), EditorGUIUtility.whiteTexture);
GUI.DrawTexture(new Rect(0, 0, headerW, 400), EditorGUIUtility.whiteTexture);
GUI.color = s_Styles.tableLineColor * oldColor;
GUI.DrawTexture(new Rect(0, headerW, 400, 1), EditorGUIUtility.whiteTexture);
GUI.DrawTexture(new Rect(headerW, 0, 1, 400), EditorGUIUtility.whiteTexture);
GUI.color = oldColor;
LayoutMode hMode = GetLayoutModeForAxis(m_AnchorMin, m_AnchorMax, 0);
LayoutMode vMode = GetLayoutModeForAxis(m_AnchorMin, m_AnchorMax, 1);
vMode = SwappedVMode(vMode);
bool doPivot = Event.current.shift;
bool doPosition = Event.current.alt;
int number = 5;
for (int i = 0; i < number; i++)
{
LayoutMode cellHMode = (LayoutMode)(i - 1);
for (int j = 0; j < number; j++)
{
LayoutMode cellVMode = (LayoutMode)(j - 1);
if (i == 0 && j == 0 && vMode >= 0 && hMode >= 0)
continue;
Rect position = new Rect(
i * (size + spacing) + groupings[i],
j * (size + spacing) + groupings[j],
size,
size);
if (j == 0 && !(i == 0 && hMode != LayoutMode.Undefined))
DrawLayoutModeHeaderOutsideRect(position, 0, cellHMode);
if (i == 0 && !(j == 0 && vMode != LayoutMode.Undefined))
DrawLayoutModeHeaderOutsideRect(position, 1, cellVMode);
bool selected = (cellHMode == hMode) && (cellVMode == vMode);
bool selectedHeader = (i == 0 && cellVMode == vMode) || (j == 0 && cellHMode == hMode);
if (Event.current.type == EventType.Repaint)
{
if (selected)
{
GUI.color = Color.white * oldColor;
s_Styles.frame.Draw(position, false, false, false, false);
}
else if (selectedHeader)
{
GUI.color = new Color(1, 1, 1, 0.7f) * oldColor;
s_Styles.frame.Draw(position, false, false, false, false);
}
}
DrawLayoutMode(
new Rect(position.x + padding, position.y + padding, position.width - padding * 2, position.height - padding * 2),
cellHMode, cellVMode,
doPivot, doPosition);
int clickCount = Event.current.clickCount;
if (GUI.Button(position, GUIContent.none, GUIStyle.none))
{
SetLayoutModeForAxis(m_AnchorMin, 0, cellHMode, doPivot, doPosition, m_InitValues);
SetLayoutModeForAxis(m_AnchorMin, 1, SwappedVMode(cellVMode), doPivot, doPosition, m_InitValues);
if (clickCount == 2)
editorWindow.Close();
else
editorWindow.Repaint();
}
}
}
GUI.color = oldColor;
}
static LayoutMode GetLayoutModeForAxis(
SerializedProperty anchorMin,
SerializedProperty anchorMax,
int axis)
{
if (anchorMin.vector2Value[axis] == 0 && anchorMax.vector2Value[axis] == 0)
return LayoutMode.Min;
if (anchorMin.vector2Value[axis] == 0.5f && anchorMax.vector2Value[axis] == 0.5f)
return LayoutMode.Middle;
if (anchorMin.vector2Value[axis] == 1 && anchorMax.vector2Value[axis] == 1)
return LayoutMode.Max;
if (anchorMin.vector2Value[axis] == 0 && anchorMax.vector2Value[axis] == 1)
return LayoutMode.Stretch;
return LayoutMode.Undefined;
}
static void SetLayoutModeForAxis(
SerializedProperty anchorMin,
int axis, LayoutMode layoutMode,
bool doPivot, bool doPosition, Vector2[,] defaultValues)
{
anchorMin.serializedObject.ApplyModifiedProperties();
var targetObjects = anchorMin.serializedObject.targetObjects;
for (int i = 0; i < targetObjects.Length; i++)
{
RectTransform gui = targetObjects[i] as RectTransform;
Undo.RecordObject(gui, "Change Rectangle Anchors");
if (doPosition)
{
if (defaultValues != null && defaultValues.Length > i)
{
Vector2 temp;
temp = gui.anchorMin;
temp[axis] = defaultValues[i, 0][axis];
gui.anchorMin = temp;
temp = gui.anchorMax;
temp[axis] = defaultValues[i, 1][axis];
gui.anchorMax = temp;
temp = gui.anchoredPosition;
temp[axis] = defaultValues[i, 2][axis];
gui.anchoredPosition = temp;
temp = gui.sizeDelta;
temp[axis] = defaultValues[i, 3][axis];
gui.sizeDelta = temp;
}
}
if (doPivot && layoutMode != LayoutMode.Undefined)
{
RectTransformEditor.SetPivotSmart(gui, kPivotsForModes[(int)layoutMode], axis, true, true);
}
Vector2 refPosition = Vector2.zero;
switch (layoutMode)
{
case LayoutMode.Min:
RectTransformEditor.SetAnchorSmart(gui, 0, axis, false, true, true);
RectTransformEditor.SetAnchorSmart(gui, 0, axis, true, true, true);
refPosition = gui.offsetMin;
EditorUtility.SetDirty(gui);
break;
case LayoutMode.Middle:
RectTransformEditor.SetAnchorSmart(gui, 0.5f, axis, false, true, true);
RectTransformEditor.SetAnchorSmart(gui, 0.5f, axis, true, true, true);
refPosition = (gui.offsetMin + gui.offsetMax) * 0.5f;
EditorUtility.SetDirty(gui);
break;
case LayoutMode.Max:
RectTransformEditor.SetAnchorSmart(gui, 1, axis, false, true, true);
RectTransformEditor.SetAnchorSmart(gui, 1, axis, true, true, true);
refPosition = gui.offsetMax;
EditorUtility.SetDirty(gui);
break;
case LayoutMode.Stretch:
RectTransformEditor.SetAnchorSmart(gui, 0, axis, false, true, true);
RectTransformEditor.SetAnchorSmart(gui, 1, axis, true, true, true);
refPosition = (gui.offsetMin + gui.offsetMax) * 0.5f;
EditorUtility.SetDirty(gui);
break;
}
if (doPosition)
{
// Handle position
Vector2 rectPosition = gui.anchoredPosition;
rectPosition[axis] -= refPosition[axis];
gui.anchoredPosition = rectPosition;
// Handle sizeDelta
if (layoutMode == LayoutMode.Stretch)
{
Vector2 rectSizeDelta = gui.sizeDelta;
rectSizeDelta[axis] = 0;
gui.sizeDelta = rectSizeDelta;
}
}
}
anchorMin.serializedObject.Update();
}
internal static void DrawLayoutMode(Rect rect,
SerializedProperty anchorMin,
SerializedProperty anchorMax,
SerializedProperty position,
SerializedProperty sizeDelta)
{
LayoutMode hMode = GetLayoutModeForAxis(anchorMin, anchorMax, 0);
LayoutMode vMode = GetLayoutModeForAxis(anchorMin, anchorMax, 1);
vMode = SwappedVMode(vMode);
DrawLayoutMode(rect, hMode, vMode);
}
internal static void DrawLayoutMode(Rect position, LayoutMode hMode, LayoutMode vMode)
{
DrawLayoutMode(position, hMode, vMode, false, false);
}
internal static void DrawLayoutMode(Rect position, LayoutMode hMode, LayoutMode vMode, bool doPivot)
{
DrawLayoutMode(position, hMode, vMode, doPivot, false);
}
internal static void DrawLayoutMode(Rect position, LayoutMode hMode, LayoutMode vMode, bool doPivot, bool doPosition)
{
if (s_Styles == null)
s_Styles = new Styles();
Color oldColor = GUI.color;
// Make parent size the largest possible square, but enforce it's an uneven number.
int parentWidth = (int)Mathf.Min(position.width, position.height);
if (parentWidth % 2 == 0)
parentWidth--;
int selfWidth = parentWidth / 2;
if (selfWidth % 2 == 0)
selfWidth++;
Vector2 parentSize = parentWidth * Vector2.one;
Vector2 selfSize = selfWidth * Vector2.one;
Vector2 padding = (position.size - parentSize) / 2;
padding.x = Mathf.Floor(padding.x);
padding.y = Mathf.Floor(padding.y);
Vector2 padding2 = (position.size - selfSize) / 2;
padding2.x = Mathf.Floor(padding2.x);
padding2.y = Mathf.Floor(padding2.y);
Rect outer = new Rect(position.x + padding.x, position.y + padding.y, parentSize.x, parentSize.y);
Rect inner = new Rect(position.x + padding2.x, position.y + padding2.y, selfSize.x, selfSize.y);
if (doPosition)
{
for (int axis = 0; axis < 2; axis++)
{
LayoutMode mode = (axis == 0 ? hMode : vMode);
if (mode == LayoutMode.Min)
{
Vector2 center = inner.center;
center[axis] += outer.min[axis] - inner.min[axis];
inner.center = center;
}
if (mode == LayoutMode.Middle)
{
// TODO
}
if (mode == LayoutMode.Max)
{
Vector2 center = inner.center;
center[axis] += outer.max[axis] - inner.max[axis];
inner.center = center;
}
if (mode == LayoutMode.Stretch)
{
Vector2 innerMin = inner.min;
Vector2 innerMax = inner.max;
innerMin[axis] = outer.min[axis];
innerMax[axis] = outer.max[axis];
inner.min = innerMin;
inner.max = innerMax;
}
}
}
Rect anchor = new Rect();
Vector2 min = Vector2.zero;
Vector2 max = Vector2.zero;
for (int axis = 0; axis < 2; axis++)
{
LayoutMode mode = (axis == 0 ? hMode : vMode);
if (mode == LayoutMode.Min)
{
min[axis] = outer.min[axis] + 0.5f;
max[axis] = outer.min[axis] + 0.5f;
}
if (mode == LayoutMode.Middle)
{
min[axis] = outer.center[axis];
max[axis] = outer.center[axis];
}
if (mode == LayoutMode.Max)
{
min[axis] = outer.max[axis] - 0.5f;
max[axis] = outer.max[axis] - 0.5f;
}
if (mode == LayoutMode.Stretch)
{
min[axis] = outer.min[axis] + 0.5f;
max[axis] = outer.max[axis] - 0.5f;
}
}
anchor.min = min;
anchor.max = max;
// Draw parent rect
if (Event.current.type == EventType.Repaint)
{
GUI.color = s_Styles.parentColor * oldColor;
s_Styles.frame.Draw(outer, false, false, false, false);
}
// Draw anchor lines
if (hMode != LayoutMode.Undefined && hMode != LayoutMode.Stretch)
{
GUI.color = s_Styles.simpleAnchorColor * oldColor;
GUI.DrawTexture(new Rect(anchor.xMin - 0.5f, outer.y + 1, 1, outer.height - 2), EditorGUIUtility.whiteTexture);
GUI.DrawTexture(new Rect(anchor.xMax - 0.5f, outer.y + 1, 1, outer.height - 2), EditorGUIUtility.whiteTexture);
}
if (vMode != LayoutMode.Undefined && vMode != LayoutMode.Stretch)
{
GUI.color = s_Styles.simpleAnchorColor * oldColor;
GUI.DrawTexture(new Rect(outer.x + 1, anchor.yMin - 0.5f, outer.width - 2, 1), EditorGUIUtility.whiteTexture);
GUI.DrawTexture(new Rect(outer.x + 1, anchor.yMax - 0.5f, outer.width - 2, 1), EditorGUIUtility.whiteTexture);
}
// Draw stretch mode arrows
if (hMode == LayoutMode.Stretch)
{
GUI.color = s_Styles.stretchAnchorColor * oldColor;
DrawArrow(new Rect(inner.x + 1, inner.center.y - 0.5f, inner.width - 2, 1));
}
if (vMode == LayoutMode.Stretch)
{
GUI.color = s_Styles.stretchAnchorColor * oldColor;
DrawArrow(new Rect(inner.center.x - 0.5f, inner.y + 1, 1, inner.height - 2));
}
// Draw self rect
if (Event.current.type == EventType.Repaint)
{
GUI.color = s_Styles.selfColor * oldColor;
s_Styles.frame.Draw(inner, false, false, false, false);
}
// Draw pivot
if (doPivot && hMode != LayoutMode.Undefined && vMode != LayoutMode.Undefined)
{
Vector2 pivot = new Vector2(
Mathf.Lerp(inner.xMin + 0.5f, inner.xMax - 0.5f, kPivotsForModes[(int)hMode]),
Mathf.Lerp(inner.yMin + 0.5f, inner.yMax - 0.5f, kPivotsForModes[(int)vMode])
);
GUI.color = s_Styles.pivotColor * oldColor;
GUI.DrawTexture(new Rect(pivot.x - 2.5f, pivot.y - 1.5f, 5, 3), EditorGUIUtility.whiteTexture);
GUI.DrawTexture(new Rect(pivot.x - 1.5f, pivot.y - 2.5f, 3, 5), EditorGUIUtility.whiteTexture);
}
// Draw anchor corners
if (hMode != LayoutMode.Undefined && vMode != LayoutMode.Undefined)
{
GUI.color = s_Styles.anchorCornerColor * oldColor;
GUI.DrawTexture(new Rect(anchor.xMin - 1.5f, anchor.yMin - 1.5f, 2, 2), EditorGUIUtility.whiteTexture);
GUI.DrawTexture(new Rect(anchor.xMax - 0.5f, anchor.yMin - 1.5f, 2, 2), EditorGUIUtility.whiteTexture);
GUI.DrawTexture(new Rect(anchor.xMin - 1.5f, anchor.yMax - 0.5f, 2, 2), EditorGUIUtility.whiteTexture);
GUI.DrawTexture(new Rect(anchor.xMax - 0.5f, anchor.yMax - 0.5f, 2, 2), EditorGUIUtility.whiteTexture);
}
GUI.color = oldColor;
}
static void DrawArrow(Rect lineRect)
{
GUI.DrawTexture(lineRect, EditorGUIUtility.whiteTexture);
if (lineRect.width == 1)
{
GUI.DrawTexture(new Rect(lineRect.x - 1, lineRect.y + 1, 3, 1), EditorGUIUtility.whiteTexture);
GUI.DrawTexture(new Rect(lineRect.x - 2, lineRect.y + 2, 5, 1), EditorGUIUtility.whiteTexture);
GUI.DrawTexture(new Rect(lineRect.x - 1, lineRect.yMax - 2, 3, 1), EditorGUIUtility.whiteTexture);
GUI.DrawTexture(new Rect(lineRect.x - 2, lineRect.yMax - 3, 5, 1), EditorGUIUtility.whiteTexture);
}
else
{
GUI.DrawTexture(new Rect(lineRect.x + 1, lineRect.y - 1, 1, 3), EditorGUIUtility.whiteTexture);
GUI.DrawTexture(new Rect(lineRect.x + 2, lineRect.y - 2, 1, 5), EditorGUIUtility.whiteTexture);
GUI.DrawTexture(new Rect(lineRect.xMax - 2, lineRect.y - 1, 1, 3), EditorGUIUtility.whiteTexture);
GUI.DrawTexture(new Rect(lineRect.xMax - 3, lineRect.y - 2, 1, 5), EditorGUIUtility.whiteTexture);
}
}
}
}
| UnityCsReference/Editor/Mono/Inspector/LayoutDropdownWindow.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/LayoutDropdownWindow.cs",
"repo_id": "UnityCsReference",
"token_count": 13132
} | 323 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.Scripting;
namespace UnityEditor
{
internal class MaterialPropertyHandler
{
private MaterialPropertyDrawer m_PropertyDrawer;
private List<MaterialPropertyDrawer> m_DecoratorDrawers;
public MaterialPropertyDrawer propertyDrawer { get { return m_PropertyDrawer; } }
public bool IsEmpty()
{
return m_PropertyDrawer == null && (m_DecoratorDrawers == null || m_DecoratorDrawers.Count == 0);
}
public void OnGUI(ref Rect position, MaterialProperty prop, GUIContent label, MaterialEditor editor)
{
float oldLabelWidth, oldFieldWidth;
var propHeight = position.height;
position.height = 0;
if (m_DecoratorDrawers != null)
{
foreach (var decorator in m_DecoratorDrawers)
{
position.height = decorator.GetPropertyHeight(prop, label.text, editor);
oldLabelWidth = EditorGUIUtility.labelWidth;
oldFieldWidth = EditorGUIUtility.fieldWidth;
decorator.OnGUI(position, prop, label, editor);
EditorGUIUtility.labelWidth = oldLabelWidth;
EditorGUIUtility.fieldWidth = oldFieldWidth;
position.y += position.height;
propHeight -= position.height;
}
}
position.height = propHeight;
if (m_PropertyDrawer != null)
{
oldLabelWidth = EditorGUIUtility.labelWidth;
oldFieldWidth = EditorGUIUtility.fieldWidth;
m_PropertyDrawer.OnGUI(position, prop, label, editor);
EditorGUIUtility.labelWidth = oldLabelWidth;
EditorGUIUtility.fieldWidth = oldFieldWidth;
}
}
public float GetPropertyHeight(MaterialProperty prop, string label, MaterialEditor editor)
{
var height = 0f;
if (m_DecoratorDrawers != null)
foreach (var drawer in m_DecoratorDrawers)
height += drawer.GetPropertyHeight(prop, label, editor);
if (m_PropertyDrawer != null)
height += m_PropertyDrawer.GetPropertyHeight(prop, label, editor);
return height;
}
private static Dictionary<string, MaterialPropertyHandler> s_PropertyHandlers = new Dictionary<string, MaterialPropertyHandler>();
private static string GetPropertyString(Shader shader, string name)
{
if (shader == null)
return string.Empty;
return shader.GetInstanceID() + "_" + name;
}
[RequiredByNativeCode]
internal static void InvalidatePropertyCache(Shader shader)
{
if (shader == null)
return;
string keyStart = shader.GetInstanceID() + "_";
var toDelete = new List<string>();
foreach (string key in s_PropertyHandlers.Keys)
{
if (key.StartsWith(keyStart, StringComparison.Ordinal))
toDelete.Add(key);
}
foreach (string key in toDelete)
{
s_PropertyHandlers.Remove(key);
}
}
private static MaterialPropertyDrawer CreatePropertyDrawer(Type klass, string argsText)
{
// no args -> default constructor
if (string.IsNullOrEmpty(argsText))
return Activator.CreateInstance(klass) as MaterialPropertyDrawer;
// split the argument list by commas
string[] argStrings = argsText.Split(',');
var args = new object[argStrings.Length];
for (var i = 0; i < argStrings.Length; ++i)
{
float f;
string arg = argStrings[i].Trim();
// if can parse as a float, use the float; otherwise pass the string
if (float.TryParse(arg, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture.NumberFormat, out f))
{
args[i] = f;
}
else
{
args[i] = arg;
}
}
return Activator.CreateInstance(klass, args) as MaterialPropertyDrawer;
}
private static MaterialPropertyDrawer GetShaderPropertyDrawer(string attrib, out bool isDecorator)
{
isDecorator = false;
string className = attrib;
string args = string.Empty;
Match match = Regex.Match(attrib, @"(\w+)\s*\((.*)\)");
if (match.Success)
{
className = match.Groups[1].Value;
args = match.Groups[2].Value.Trim();
}
//Debug.Log ("looking for class " + className + " args '" + args + "'");
foreach (var klass in TypeCache.GetTypesDerivedFrom<MaterialPropertyDrawer>())
{
// When you write [Foo] in shader, get Foo, FooDrawer, MaterialFooDrawer,
// FooDecorator or MaterialFooDecorator class;
// "kind of" similar to how C# does attributes.
//@TODO: namespaces?
if (klass.Name == className ||
klass.Name == className + "Drawer" ||
klass.Name == "Material" + className + "Drawer" ||
klass.Name == className + "Decorator" ||
klass.Name == "Material" + className + "Decorator")
{
try
{
isDecorator = klass.Name.EndsWith("Decorator");
return CreatePropertyDrawer(klass, args);
}
catch (Exception)
{
Debug.LogWarningFormat("Failed to create material drawer {0} with arguments '{1}'", className, args);
return null;
}
}
}
return null;
}
private static MaterialPropertyHandler GetShaderPropertyHandler(Shader shader, string name)
{
if (name == null)
return null;
int propertyIndex = shader.FindPropertyIndex(name);
if (propertyIndex < 0)
return null;
string[] attribs = shader.GetPropertyAttributes(propertyIndex);
if (attribs == null || attribs.Length == 0)
return null;
var handler = new MaterialPropertyHandler();
foreach (var attr in attribs)
{
bool isDecorator;
MaterialPropertyDrawer drawer = GetShaderPropertyDrawer(attr, out isDecorator);
if (drawer != null)
{
if (isDecorator)
{
if (handler.m_DecoratorDrawers == null)
handler.m_DecoratorDrawers = new List<MaterialPropertyDrawer>();
handler.m_DecoratorDrawers.Add(drawer);
}
else
{
if (handler.m_PropertyDrawer != null)
{
Debug.LogWarning(string.Format("Shader property {0} already has a property drawer", name), shader);
}
handler.m_PropertyDrawer = drawer;
}
}
}
return handler;
}
internal static MaterialPropertyHandler GetHandler(Shader shader, string name)
{
if (shader == null || name == null)
return null;
// Use cached handler if available
MaterialPropertyHandler handler;
string key = GetPropertyString(shader, name);
if (s_PropertyHandlers.TryGetValue(key, out handler))
return handler;
// Get the handler for this shader property
handler = GetShaderPropertyHandler(shader, name);
if (handler != null && handler.IsEmpty())
handler = null;
//Debug.Log ("drawer " + drawer);
// Special exception for KeywordEnums, as the cache doesn't have a way to
// determine whether a KeywordEnum has been changed or not.
if (handler != null && handler.propertyDrawer is MaterialKeywordEnumDrawer)
return handler;
// Cache the handler and return. Cache even if it was null, so we can return
// later requests fast as well.
s_PropertyHandlers[key] = handler;
return handler;
}
}
public abstract class MaterialPropertyDrawer
{
public virtual void OnGUI(Rect position, MaterialProperty prop, GUIContent label, MaterialEditor editor)
{
OnGUI(position, prop, label.text, editor);
}
public virtual void OnGUI(Rect position, MaterialProperty prop, string label, MaterialEditor editor)
{
EditorGUI.LabelField(position, new GUIContent(label), EditorGUIUtility.TempContent("No GUI Implemented"));
}
public virtual float GetPropertyHeight(MaterialProperty prop, string label, MaterialEditor editor)
{
return EditorGUI.kSingleLineHeight;
}
public virtual void Apply(MaterialProperty prop)
{
// empty base implementation
}
}
// --------------------------------------------------------------------------
// Built-in drawers below.
// They aren't directly used by the code, but can be used by writing attribute-like
// syntax in shaders, e.g. [Toggle] in front of a shader property will
// end up using MaterialToggleDrawer to display it as a toggle.
// Variant of the ToggleDrawer that defines no keyword (just UI)
internal class MaterialToggleUIDrawer : MaterialPropertyDrawer
{
public MaterialToggleUIDrawer()
{
}
public MaterialToggleUIDrawer(string keyword)
{
}
protected virtual void SetKeyword(MaterialProperty prop, bool on)
{
}
static bool IsPropertyTypeSuitable(MaterialProperty prop)
{
return prop.type == MaterialProperty.PropType.Float || prop.type == MaterialProperty.PropType.Range || prop.type == MaterialProperty.PropType.Int;
}
public override float GetPropertyHeight(MaterialProperty prop, string label, MaterialEditor editor)
{
if (!IsPropertyTypeSuitable(prop))
{
return EditorGUI.kSingleLineHeight * 2.5f;
}
return base.GetPropertyHeight(prop, label, editor);
}
public override void OnGUI(Rect position, MaterialProperty prop, GUIContent label, MaterialEditor editor)
{
if (!IsPropertyTypeSuitable(prop))
{
GUIContent c = EditorGUIUtility.TempContent("Toggle used on a non-float property: " + prop.name,
EditorGUIUtility.GetHelpIcon(MessageType.Warning));
EditorGUI.LabelField(position, c, EditorStyles.helpBox);
return;
}
MaterialEditor.BeginProperty(position, prop);
if (prop.type != MaterialProperty.PropType.Int)
{
EditorGUI.BeginChangeCheck();
bool value = (Math.Abs(prop.floatValue) > 0.001f);
EditorGUI.showMixedValue = prop.hasMixedValue;
value = EditorGUI.Toggle(position, label, value);
EditorGUI.showMixedValue = false;
if (EditorGUI.EndChangeCheck())
{
prop.floatValue = value ? 1.0f : 0.0f;
SetKeyword(prop, value);
}
}
else
{
EditorGUI.BeginChangeCheck();
bool value = prop.intValue != 0;
EditorGUI.showMixedValue = prop.hasMixedValue;
value = EditorGUI.Toggle(position, label, value);
EditorGUI.showMixedValue = false;
if (EditorGUI.EndChangeCheck())
{
prop.intValue = value ? 1 : 0;
SetKeyword(prop, value);
}
}
MaterialEditor.EndProperty();
}
public override void Apply(MaterialProperty prop)
{
base.Apply(prop);
if (!IsPropertyTypeSuitable(prop))
return;
if (prop.hasMixedValue)
return;
if (prop.type != MaterialProperty.PropType.Int)
SetKeyword(prop, (Math.Abs(prop.floatValue) > 0.001f));
else
SetKeyword(prop, prop.intValue != 0);
}
}
internal class MaterialToggleDrawer : MaterialToggleUIDrawer
{
protected readonly string keyword;
public MaterialToggleDrawer()
{
}
public MaterialToggleDrawer(string keyword)
{
this.keyword = keyword;
}
protected override void SetKeyword(MaterialProperty prop, bool on)
{
SetKeywordInternal(prop, on, "_ON");
}
protected void SetKeywordInternal(MaterialProperty prop, bool on, string defaultKeywordSuffix)
{
// if no keyword is provided, use <uppercase property name> + defaultKeywordSuffix
string kw = string.IsNullOrEmpty(keyword) ? prop.name.ToUpperInvariant() + defaultKeywordSuffix : keyword;
// set or clear the keyword
foreach (Material material in prop.targets)
{
if (on)
material.EnableKeyword(kw);
else
material.DisableKeyword(kw);
}
}
}
// Variant of the ToggleDrawer that defines a keyword when it's not on
// This is useful when adding Toggles to existing shaders while maintaining backwards compatibility
internal class MaterialToggleOffDrawer : MaterialToggleDrawer
{
public MaterialToggleOffDrawer()
{
}
public MaterialToggleOffDrawer(string keyword) : base(keyword)
{
}
protected override void SetKeyword(MaterialProperty prop, bool on)
{
SetKeywordInternal(prop, !on, "_OFF");
}
}
internal class MaterialPowerSliderDrawer : MaterialPropertyDrawer
{
private readonly float power;
public MaterialPowerSliderDrawer(float power)
{
this.power = power;
}
public override float GetPropertyHeight(MaterialProperty prop, string label, MaterialEditor editor)
{
if (prop.type != MaterialProperty.PropType.Range)
{
return EditorGUI.kSingleLineHeight * 2.5f;
}
return base.GetPropertyHeight(prop, label, editor);
}
public override void OnGUI(Rect position, MaterialProperty prop, GUIContent label, MaterialEditor editor)
{
if (prop.type != MaterialProperty.PropType.Range)
{
GUIContent c = EditorGUIUtility.TempContent("PowerSlider used on a non-range property: " + prop.name,
EditorGUIUtility.GetHelpIcon(MessageType.Warning));
EditorGUI.LabelField(position, c, EditorStyles.helpBox);
return;
}
MaterialEditor.DoPowerRangeProperty(position, prop, label, power);
}
}
internal class MaterialIntRangeDrawer : MaterialPropertyDrawer
{
public override void OnGUI(Rect position, MaterialProperty prop, GUIContent label, MaterialEditor editor)
{
if (prop.type != MaterialProperty.PropType.Range)
{
GUIContent c = EditorGUIUtility.TempContent("IntRange used on a non-range property: " + prop.name,
EditorGUIUtility.GetHelpIcon(MessageType.Warning));
EditorGUI.LabelField(position, c, EditorStyles.helpBox);
return;
}
MaterialEditor.DoIntRangeProperty(position, prop, label);
}
}
internal class MaterialKeywordEnumDrawer : MaterialPropertyDrawer
{
private readonly GUIContent[] keywords;
public MaterialKeywordEnumDrawer(string kw1) : this(new[] { kw1 }) {}
public MaterialKeywordEnumDrawer(string kw1, string kw2) : this(new[] { kw1, kw2 }) {}
public MaterialKeywordEnumDrawer(string kw1, string kw2, string kw3) : this(new[] { kw1, kw2, kw3 }) {}
public MaterialKeywordEnumDrawer(string kw1, string kw2, string kw3, string kw4) : this(new[] { kw1, kw2, kw3, kw4 }) {}
public MaterialKeywordEnumDrawer(string kw1, string kw2, string kw3, string kw4, string kw5) : this(new[] { kw1, kw2, kw3, kw4, kw5 }) {}
public MaterialKeywordEnumDrawer(string kw1, string kw2, string kw3, string kw4, string kw5, string kw6) : this(new[] { kw1, kw2, kw3, kw4, kw5, kw6 }) {}
public MaterialKeywordEnumDrawer(string kw1, string kw2, string kw3, string kw4, string kw5, string kw6, string kw7) : this(new[] { kw1, kw2, kw3, kw4, kw5, kw6, kw7 }) {}
public MaterialKeywordEnumDrawer(string kw1, string kw2, string kw3, string kw4, string kw5, string kw6, string kw7, string kw8) : this(new[] { kw1, kw2, kw3, kw4, kw5, kw6, kw7, kw8 }) {}
public MaterialKeywordEnumDrawer(string kw1, string kw2, string kw3, string kw4, string kw5, string kw6, string kw7, string kw8, string kw9) : this(new[] { kw1, kw2, kw3, kw4, kw5, kw6, kw7, kw8, kw9 }) {}
public MaterialKeywordEnumDrawer(params string[] keywords)
{
this.keywords = new GUIContent[keywords.Length];
for (int i = 0; i < keywords.Length; ++i)
this.keywords[i] = new GUIContent(keywords[i]);
}
static bool IsPropertyTypeSuitable(MaterialProperty prop)
{
return prop.type == MaterialProperty.PropType.Float || prop.type == MaterialProperty.PropType.Range || prop.type == MaterialProperty.PropType.Int;
}
void SetKeyword(MaterialProperty prop, int index)
{
for (int i = 0; i < keywords.Length; ++i)
{
string keyword = GetKeywordName(prop.name, keywords[i].text);
foreach (Material material in prop.targets)
{
if (index == i)
material.EnableKeyword(keyword);
else
material.DisableKeyword(keyword);
}
}
}
public override float GetPropertyHeight(MaterialProperty prop, string label, MaterialEditor editor)
{
if (!IsPropertyTypeSuitable(prop))
{
return EditorGUI.kSingleLineHeight * 2.5f;
}
return base.GetPropertyHeight(prop, label, editor);
}
public override void OnGUI(Rect position, MaterialProperty prop, GUIContent label, MaterialEditor editor)
{
if (!IsPropertyTypeSuitable(prop))
{
GUIContent c = EditorGUIUtility.TempContent("KeywordEnum used on a non-float property: " + prop.name,
EditorGUIUtility.GetHelpIcon(MessageType.Warning));
EditorGUI.LabelField(position, c, EditorStyles.helpBox);
return;
}
MaterialEditor.BeginProperty(position, prop);
if (prop.type != MaterialProperty.PropType.Int)
{
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = prop.hasMixedValue;
var value = (int)prop.floatValue;
value = EditorGUI.Popup(position, label, value, keywords);
EditorGUI.showMixedValue = false;
if (EditorGUI.EndChangeCheck())
{
prop.floatValue = value;
SetKeyword(prop, value);
}
}
else
{
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = prop.hasMixedValue;
var value = prop.intValue;
value = EditorGUI.Popup(position, label, value, keywords);
EditorGUI.showMixedValue = false;
if (EditorGUI.EndChangeCheck())
{
prop.intValue = value;
SetKeyword(prop, value);
}
}
MaterialEditor.EndProperty();
}
public override void Apply(MaterialProperty prop)
{
base.Apply(prop);
if (!IsPropertyTypeSuitable(prop))
return;
if (prop.hasMixedValue)
return;
if (prop.type != MaterialProperty.PropType.Int)
SetKeyword(prop, (int)prop.floatValue);
else
SetKeyword(prop, prop.intValue);
}
// Final keyword name: property name + "_" + display name. Uppercased,
// and spaces replaced with underscores.
private static string GetKeywordName(string propName, string name)
{
string n = propName + "_" + name;
return n.Replace(' ', '_').ToUpperInvariant();
}
}
internal class MaterialEnumDrawer : MaterialPropertyDrawer
{
private readonly GUIContent[] names;
private readonly int[] values;
// Single argument: enum type name; entry names & values fetched via reflection
public MaterialEnumDrawer(string enumName)
{
var loadedTypes = TypeCache.GetTypesDerivedFrom(typeof(Enum));
try
{
var enumType = loadedTypes.FirstOrDefault(x => x.Name == enumName || x.FullName == enumName);
var enumNames = Enum.GetNames(enumType);
this.names = new GUIContent[enumNames.Length];
for (int i = 0; i < enumNames.Length; ++i)
this.names[i] = new GUIContent(enumNames[i]);
var enumVals = Enum.GetValues(enumType);
values = new int[enumVals.Length];
for (var i = 0; i < enumVals.Length; ++i)
values[i] = (int)enumVals.GetValue(i);
}
catch (Exception)
{
Debug.LogWarningFormat("Failed to create MaterialEnum, enum {0} not found", enumName);
throw;
}
}
// name,value,name,value,... pairs: explicit names & values
public MaterialEnumDrawer(string n1, float v1) : this(new[] {n1}, new[] {v1}) {}
public MaterialEnumDrawer(string n1, float v1, string n2, float v2) : this(new[] { n1, n2 }, new[] { v1, v2 }) {}
public MaterialEnumDrawer(string n1, float v1, string n2, float v2, string n3, float v3) : this(new[] { n1, n2, n3 }, new[] { v1, v2, v3 }) {}
public MaterialEnumDrawer(string n1, float v1, string n2, float v2, string n3, float v3, string n4, float v4) : this(new[] { n1, n2, n3, n4 }, new[] { v1, v2, v3, v4 }) {}
public MaterialEnumDrawer(string n1, float v1, string n2, float v2, string n3, float v3, string n4, float v4, string n5, float v5) : this(new[] { n1, n2, n3, n4, n5 }, new[] { v1, v2, v3, v4, v5 }) {}
public MaterialEnumDrawer(string n1, float v1, string n2, float v2, string n3, float v3, string n4, float v4, string n5, float v5, string n6, float v6) : this(new[] { n1, n2, n3, n4, n5, n6 }, new[] { v1, v2, v3, v4, v5, v6 }) {}
public MaterialEnumDrawer(string n1, float v1, string n2, float v2, string n3, float v3, string n4, float v4, string n5, float v5, string n6, float v6, string n7, float v7) : this(new[] { n1, n2, n3, n4, n5, n6, n7 }, new[] { v1, v2, v3, v4, v5, v6, v7 }) {}
public MaterialEnumDrawer(string[] enumNames, float[] vals)
{
this.names = new GUIContent[enumNames.Length];
for (int i = 0; i < enumNames.Length; ++i)
this.names[i] = new GUIContent(enumNames[i]);
values = new int[vals.Length];
for (int i = 0; i < vals.Length; ++i)
values[i] = (int)vals[i];
}
static bool IsPropertyTypeSuitable(MaterialProperty prop)
{
return prop.type == MaterialProperty.PropType.Float || prop.type == MaterialProperty.PropType.Range || prop.type == MaterialProperty.PropType.Int;
}
public override float GetPropertyHeight(MaterialProperty prop, string label, MaterialEditor editor)
{
if (prop.type != MaterialProperty.PropType.Float && prop.type != MaterialProperty.PropType.Range && prop.type != MaterialProperty.PropType.Int)
{
return EditorGUI.kSingleLineHeight * 2.5f;
}
return base.GetPropertyHeight(prop, label, editor);
}
public override void OnGUI(Rect position, MaterialProperty prop, GUIContent label, MaterialEditor editor)
{
if (!IsPropertyTypeSuitable(prop))
{
GUIContent c = EditorGUIUtility.TempContent("Enum used on a non-float property: " + prop.name,
EditorGUIUtility.GetHelpIcon(MessageType.Warning));
EditorGUI.LabelField(position, c, EditorStyles.helpBox);
return;
}
MaterialEditor.BeginProperty(position, prop);
if (prop.type == MaterialProperty.PropType.Float || prop.type == MaterialProperty.PropType.Range)
{
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = prop.hasMixedValue;
var value = (int)prop.floatValue;
int selectedIndex = -1;
for (var index = 0; index < values.Length; index++)
{
var i = values[index];
if (i == value)
{
selectedIndex = index;
break;
}
}
var selIndex = EditorGUI.Popup(position, label, selectedIndex, names);
EditorGUI.showMixedValue = false;
if (EditorGUI.EndChangeCheck())
{
prop.floatValue = (float)values[selIndex];
}
}
else
{
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = prop.hasMixedValue;
var value = prop.intValue;
int selectedIndex = -1;
for (var index = 0; index < values.Length; index++)
{
var i = values[index];
if (i == value)
{
selectedIndex = index;
break;
}
}
var selIndex = EditorGUI.Popup(position, label, selectedIndex, names);
EditorGUI.showMixedValue = false;
if (EditorGUI.EndChangeCheck())
{
prop.intValue = values[selIndex];
}
}
MaterialEditor.EndProperty();
}
}
// [Space] or [Space(height)] decorator creates a vertical space before shader property.
internal class MaterialSpaceDecorator : MaterialPropertyDrawer
{
private readonly float height;
public MaterialSpaceDecorator()
{
height = 6f;
}
public MaterialSpaceDecorator(float height)
{
this.height = height;
}
public override float GetPropertyHeight(MaterialProperty prop, string label, MaterialEditor editor)
{
return height;
}
public override void OnGUI(Rect position, MaterialProperty prop, string label, MaterialEditor editor)
{
}
}
// [Header(foobar)] decorator shows "foobar" header before shader property.
internal class MaterialHeaderDecorator : MaterialPropertyDrawer
{
private readonly string header;
public MaterialHeaderDecorator(string header)
{
this.header = header;
}
// so that we can accept Header(1) and display that as text
public MaterialHeaderDecorator(float headerAsNumber)
{
this.header = headerAsNumber.ToString(CultureInfo.InvariantCulture);
}
public override float GetPropertyHeight(MaterialProperty prop, string label, MaterialEditor editor)
{
return 24f;
}
public override void OnGUI(Rect position, MaterialProperty prop, string label, MaterialEditor editor)
{
position.y += 8;
position = EditorGUI.IndentedRect(position);
GUI.Label(position, header, EditorStyles.boldLabel);
}
}
}
| UnityCsReference/Editor/Mono/Inspector/MaterialPropertyDrawer.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/MaterialPropertyDrawer.cs",
"repo_id": "UnityCsReference",
"token_count": 14050
} | 324 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEditor.AnimatedValues;
using UnityEngine;
using UnityEditor.Build;
using UnityEditor.SceneManagement;
using UnityEditor.PlatformSupport;
using UnityEditor.Presets;
using UnityEditorInternal;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Reflection;
using UnityEditor.Modules;
using UnityEditorInternal.VR;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using GraphicsDeviceType = UnityEngine.Rendering.GraphicsDeviceType;
using TargetAttributes = UnityEditor.BuildTargetDiscovery.TargetAttributes;
using UnityEngine.Rendering;
using UnityEngine.Scripting;
// ************************************* READ BEFORE EDITING **************************************
//
// DO NOT COPY/PASTE! Please do not have the same setting more than once in the code.
// If a setting for one platform needs to be exposed to more platforms,
// change the if statements so the same lines of code are executed for both platforms,
// instead of copying the lines into multiple code blocks.
// This ensures that if we change labels, or headers, or the order of settings, it will remain
// consistent without having to remember to make the same change multiple places. THANK YOU!
//
// ADD_NEW_PLATFORM_HERE: review this file
namespace UnityEditor
{
[CustomEditor(typeof(PlayerSettings))]
internal partial class PlayerSettingsEditor : Editor
{
class Styles
{
public static readonly GUIStyle categoryBox = new GUIStyle(EditorStyles.helpBox);
static Styles()
{
categoryBox.padding.left = 4;
}
}
class SettingsContent
{
public static readonly GUIContent recordingInfo = EditorGUIUtility.TrTextContent("Reordering the list will switch editor to the first available platform");
public static readonly GUIContent appleSiliconOpenGLWarning = EditorGUIUtility.TrTextContent("OpenGL is not supported on Apple Silicon chips. Metal will be used on devices with Apple Silicon chips instead.");
public static readonly GUIContent sharedBetweenPlatformsInfo = EditorGUIUtility.TrTextContent("* Shared setting between multiple platforms.");
public static readonly GUIContent cursorHotspot = EditorGUIUtility.TrTextContent("Cursor Hotspot");
public static readonly GUIContent defaultCursor = EditorGUIUtility.TrTextContent("Default Cursor");
public static readonly GUIContent vertexChannelCompressionMask = EditorGUIUtility.TrTextContent("Vertex Compression*", "Select which vertex channels should be compressed. Compression can save memory and bandwidth, but precision will be lower.");
public static readonly GUIContent resolutionPresentationTitle = EditorGUIUtility.TrTextContent("Resolution and Presentation");
public static readonly GUIContent resolutionTitle = EditorGUIUtility.TrTextContent("Resolution");
public static readonly GUIContent orientationTitle = EditorGUIUtility.TrTextContent("Orientation");
public static readonly GUIContent allowedOrientationTitle = EditorGUIUtility.TrTextContent("Allowed Orientations for Auto Rotation");
public static readonly GUIContent multitaskingSupportTitle = EditorGUIUtility.TrTextContent("Multitasking Support");
public static readonly GUIContent statusBarTitle = EditorGUIUtility.TrTextContent("Status Bar");
public static readonly GUIContent standalonePlayerOptionsTitle = EditorGUIUtility.TrTextContent("Standalone Player Options");
public static readonly GUIContent debuggingCrashReportingTitle = EditorGUIUtility.TrTextContent("Debugging and crash reporting");
public static readonly GUIContent debuggingTitle = EditorGUIUtility.TrTextContent("Debugging");
public static readonly GUIContent crashReportingTitle = EditorGUIUtility.TrTextContent("Crash Reporting");
public static readonly GUIContent otherSettingsTitle = EditorGUIUtility.TrTextContent("Other Settings");
public static readonly GUIContent renderingTitle = EditorGUIUtility.TrTextContent("Rendering");
public static readonly GUIContent vulkanSettingsTitle = EditorGUIUtility.TrTextContent("Vulkan Settings");
public static readonly GUIContent identificationTitle = EditorGUIUtility.TrTextContent("Identification");
public static readonly GUIContent macAppStoreTitle = EditorGUIUtility.TrTextContent("Mac App Store Options");
public static readonly GUIContent configurationTitle = EditorGUIUtility.TrTextContent("Configuration");
public static readonly GUIContent macConfigurationTitle = EditorGUIUtility.TrTextContent("Mac Configuration");
public static readonly GUIContent optimizationTitle = EditorGUIUtility.TrTextContent("Optimization");
public static readonly GUIContent loggingTitle = EditorGUIUtility.TrTextContent("Stack Trace*");
public static readonly GUIContent legacyTitle = EditorGUIUtility.TrTextContent("Legacy");
public static readonly GUIContent publishingSettingsTitle = EditorGUIUtility.TrTextContent("Publishing Settings");
public static readonly GUIContent captureLogsTitle = EditorGUIUtility.TrTextContent("Capture Logs");
public static readonly GUIContent shaderSectionTitle = EditorGUIUtility.TrTextContent("Shader Settings");
public static readonly GUIContent shaderVariantLoadingTitle = EditorGUIUtility.TrTextContent("Shader Variant Loading Settings");
public static readonly GUIContent defaultShaderChunkSize = EditorGUIUtility.TrTextContent("Default chunk size (MB)*", "Use this setting to control how much memory is used when loading shader variants.");
public static readonly GUIContent defaultShaderChunkCount = EditorGUIUtility.TrTextContent("Default chunk count*", "Use this setting to control how much memory is used when loading shader variants.");
public static readonly GUIContent overrideDefaultChunkSettings = EditorGUIUtility.TrTextContent("Override", "Override the default settings for this build target.");
public static readonly GUIContent platformShaderChunkSize = EditorGUIUtility.TrTextContent("Chunk size (MB)", "Use this setting to control how much memory is used when loading shader variants.");
public static readonly GUIContent platformShaderChunkCount = EditorGUIUtility.TrTextContent("Chunk count", "Use this setting to control how much memory is used when loading shader variants.");
public static readonly GUIContent bakeCollisionMeshes = EditorGUIUtility.TrTextContent("Prebake Collision Meshes*", "Bake collision data into the meshes on build time");
public static readonly GUIContent dedicatedServerOptimizations = EditorGUIUtility.TrTextContent("Enable Dedicated Server optimizations", "Performs additional optimizations on Dedicated Server builds.");
public static readonly GUIContent keepLoadedShadersAlive = EditorGUIUtility.TrTextContent("Keep Loaded Shaders Alive*", "Prevents shaders from being unloaded");
public static readonly GUIContent preloadedAssets = EditorGUIUtility.TrTextContent("Preloaded Assets*", "Assets to load at start up in the player and kept alive until the player terminates");
public static readonly GUIContent stripEngineCode = EditorGUIUtility.TrTextContent("Strip Engine Code*", "Strip Unused Engine Code - Note that byte code stripping of managed assemblies is always enabled for the IL2CPP scripting backend.");
public static readonly GUIContent iPhoneScriptCallOptimization = EditorGUIUtility.TrTextContent("Script Call Optimization*");
public static readonly GUIContent enableInternalProfiler = EditorGUIUtility.TrTextContent("Enable Internal Profiler* (Deprecated)", "Internal profiler counters should be accessed by scripts using UnityEngine.Profiling::Profiler API.");
public static readonly GUIContent stripUnusedMeshComponents = EditorGUIUtility.TrTextContent("Optimize Mesh Data*", "Remove unused mesh components");
public static readonly GUIContent strictShaderVariantMatching = EditorGUIUtility.TrTextContent("Strict shader variant matching*", "When enabled, if a shader variant is missing, Unity uses the error shader and displays an error in the Console.");
public static readonly GUIContent mipStripping = EditorGUIUtility.TrTextContent("Texture MipMap Stripping*", "Remove unused texture levels from package builds, reducing package size on disk. Limits the texture quality settings to the highest mip that was included during the build.");
public static readonly GUIContent enableFrameTimingStats = EditorGUIUtility.TrTextContent("Frame Timing Stats", "Enable gathering of CPU/GPU frame timing statistics.");
public static readonly GUIContent enableOpenGLProfilerGPURecorders = EditorGUIUtility.TrTextContent("OpenGL: Profiler GPU Recorders", "Enable Profiler Recorders when rendering with OpenGL. Always enabled with other rendering APIs. Optional on OpenGL due to potential incompatibility with Frame Timing Stats and the GPU Profiler.");
public static readonly GUIContent openGLFrameTimingStatsOnGPURecordersOnWarning = EditorGUIUtility.TrTextContent("On OpenGL, Frame Timing Stats may disable Profiler GPU Recorders and the GPU Profiler.");
public static readonly GUIContent openGLFrameTimingStatsOnGPURecordersOffInfo = EditorGUIUtility.TrTextContent("On OpenGL, Frame Timing Stats may disable the GPU Profiler.");
public static readonly GUIContent openGLFrameTimingStatsOffGPURecordersOnInfo = EditorGUIUtility.TrTextContent("On OpenGL, Profiler GPU Recorders may disable the GPU Profiler.");
public static readonly GUIContent useOSAutoRotation = EditorGUIUtility.TrTextContent("Use Animated Autorotation", "If set OS native animated autorotation method will be used. Otherwise orientation will be changed immediately.");
public static readonly GUIContent defaultScreenWidth = EditorGUIUtility.TrTextContent("Default Screen Width");
public static readonly GUIContent defaultScreenHeight = EditorGUIUtility.TrTextContent("Default Screen Height");
public static readonly GUIContent macRetinaSupport = EditorGUIUtility.TrTextContent("Mac Retina Support");
public static readonly GUIContent runInBackground = EditorGUIUtility.TrTextContent("Run In Background*");
public static readonly GUIContent defaultScreenOrientation = EditorGUIUtility.TrTextContent("Default Orientation*");
public static readonly GUIContent allowedAutoRotateToPortrait = EditorGUIUtility.TrTextContent("Portrait");
public static readonly GUIContent allowedAutoRotateToPortraitUpsideDown = EditorGUIUtility.TrTextContent("Portrait Upside Down");
public static readonly GUIContent allowedAutoRotateToLandscapeRight = EditorGUIUtility.TrTextContent("Landscape Right");
public static readonly GUIContent allowedAutoRotateToLandscapeLeft = EditorGUIUtility.TrTextContent("Landscape Left");
public static readonly GUIContent UIRequiresFullScreen = EditorGUIUtility.TrTextContent("Requires Fullscreen");
public static readonly GUIContent UIStatusBarHidden = EditorGUIUtility.TrTextContent("Status Bar Hidden");
public static readonly GUIContent UIStatusBarStyle = EditorGUIUtility.TrTextContent("Status Bar Style");
public static readonly GUIContent useMacAppStoreValidation = EditorGUIUtility.TrTextContent("Mac App Store Validation");
public static readonly GUIContent macAppStoreCategory = EditorGUIUtility.TrTextContent("Category", "'LSApplicationCategoryType'");
public static readonly GUIContent macOSURLSchemes = EditorGUIUtility.TrTextContent("Supported URL schemes*");
public static readonly GUIContent fullscreenMode = EditorGUIUtility.TrTextContent("Fullscreen Mode ", " Not all platforms support all modes");
public static readonly GUIContent exclusiveFullscreen = EditorGUIUtility.TrTextContent("Exclusive Fullscreen");
public static readonly GUIContent fullscreenWindow = EditorGUIUtility.TrTextContent("Fullscreen Window");
public static readonly GUIContent maximizedWindow = EditorGUIUtility.TrTextContent("Maximized Window");
public static readonly GUIContent windowed = EditorGUIUtility.TrTextContent("Windowed");
public static readonly GUIContent displayResolutionDialogEnabledLabel = EditorGUIUtility.TrTextContent("Enabled (Deprecated)");
public static readonly GUIContent displayResolutionDialogHiddenLabel = EditorGUIUtility.TrTextContent("Hidden by Default (Deprecated)");
public static readonly GUIContent displayResolutionDialogDeprecationWarning = EditorGUIUtility.TrTextContent("The Display Resolution Dialog has been deprecated and will be removed in a future version.");
public static readonly GUIContent visibleInBackground = EditorGUIUtility.TrTextContent("Visible In Background");
public static readonly GUIContent allowFullscreenSwitch = EditorGUIUtility.TrTextContent("Allow Fullscreen Switch*");
public static readonly GUIContent useFlipModelSwapChain = EditorGUIUtility.TrTextContent("Use DXGI flip model swapchain for D3D11", "Disable this option to fallback to Windows 7-style BitBlt model. Using flip model (leaving this option enabled) ensures the best performance. This setting affects only D3D11 graphics API.");
public static readonly GUIContent flipModelSwapChainWarning = EditorGUIUtility.TrTextContent("Disabling DXGI flip model swapchain will result in Unity falling back to the slower and less efficient BitBlt model. See documentation for more information.");
public static readonly GUIContent use32BitDisplayBuffer = EditorGUIUtility.TrTextContent("Use 32-bit Display Buffer*", "If set Display Buffer will be created to hold 32-bit color values. Use it only if you see banding, as it has performance implications.");
public static readonly GUIContent disableDepthAndStencilBuffers = EditorGUIUtility.TrTextContent("Disable Depth and Stencil*");
public static readonly GUIContent preserveFramebufferAlpha = EditorGUIUtility.TrTextContent("Render Over Native UI*", "Enable this option ONLY if you want Unity to render on top of the native Android or iOS UI.");
public static readonly GUIContent actionOnDotNetUnhandledException = EditorGUIUtility.TrTextContent("On .Net UnhandledException*");
public static readonly GUIContent logObjCUncaughtExceptions = EditorGUIUtility.TrTextContent("Log Obj-C Uncaught Exceptions*");
public static readonly GUIContent enableCrashReportAPI = EditorGUIUtility.TrTextContent("Enable CrashReport API*");
public static readonly GUIContent activeColorSpace = EditorGUIUtility.TrTextContent("Color Space*");
public static readonly GUIContent unsupportedMSAAFallback = EditorGUIUtility.TrTextContent("MSAA Fallback");
public static readonly GUIContent colorGamut = EditorGUIUtility.TrTextContent("Color Gamut*");
public static readonly GUIContent colorGamutForMac = EditorGUIUtility.TrTextContent("Color Gamut For Mac*");
public static readonly GUIContent metalForceHardShadows = EditorGUIUtility.TrTextContent("Force hard shadows on Metal*");
public static readonly GUIContent metalAPIValidation = EditorGUIUtility.TrTextContent("Metal API Validation*", "When enabled, additional binding state validation is applied.");
public static readonly GUIContent metalFramebufferOnly = EditorGUIUtility.TrTextContent("Metal Write-Only Backbuffer*", "Set framebufferOnly flag on backbuffer. This prevents readback from backbuffer but enables some driver optimizations.");
public static readonly GUIContent framebufferDepthMemorylessMode = EditorGUIUtility.TrTextContent("Memoryless Depth*", "Memoryless mode of framebuffer depth");
public static readonly GUIContent[] memorylessModeNames = { EditorGUIUtility.TrTextContent("Unused"), EditorGUIUtility.TrTextContent("Forced"), EditorGUIUtility.TrTextContent("Automatic") };
public static readonly GUIContent vulkanEnableSetSRGBWrite = EditorGUIUtility.TrTextContent("SRGB Write Mode*", "If set, enables Graphics.SetSRGBWrite() for toggling sRGB write mode during the frame but may decrease performance especially on tiled GPUs.");
public static readonly GUIContent vulkanNumSwapchainBuffers = EditorGUIUtility.TrTextContent("Number of swapchain buffers*");
public static readonly GUIContent vulkanEnableLateAcquireNextImage = EditorGUIUtility.TrTextContent("Acquire swapchain image late as possible*", "If set, renders to a staging image to delay acquiring the swapchain buffer.");
public static readonly GUIContent vulkanEnableCommandBufferRecycling = EditorGUIUtility.TrTextContent("Recycle command buffers*", "When enabled, command buffers are recycled after they have been executed as opposed to being freed.");
public static readonly GUIContent mTRendering = EditorGUIUtility.TrTextContent("Multithreaded Rendering*");
public static readonly GUIContent staticBatching = EditorGUIUtility.TrTextContent("Static Batching");
public static readonly GUIContent dynamicBatching = EditorGUIUtility.TrTextContent("Dynamic Batching");
public static readonly GUIContent spriteBatchingVertexThreshold = EditorGUIUtility.TrTextContent("Sprite Batching Threshold", "Dynamic Batching is always enabled for Sprites and this controls max vertex threshold for batching. ");
public static readonly GUIContent graphicsJobsNonExperimental = EditorGUIUtility.TrTextContent("Graphics Jobs");
public static readonly GUIContent graphicsJobsExperimental = EditorGUIUtility.TrTextContent("Graphics Jobs (Experimental)");
public static readonly GUIContent graphicsJobsMode = EditorGUIUtility.TrTextContent("Graphics Jobs Mode");
public static readonly GUIContent applicationIdentifierWarning = EditorGUIUtility.TrTextContent("Invalid characters have been removed from the Application Identifier.");
public static readonly GUIContent applicationIdentifierError = EditorGUIUtility.TrTextContent("The Application Identifier must follow the convention 'com.YourCompanyName.YourProductName' and must contain only alphanumeric and hyphen characters.");
public static readonly GUIContent packageNameError = EditorGUIUtility.TrTextContent("The Package Name must follow the convention 'com.YourCompanyName.YourProductName' and must contain only alphanumeric and underscore characters. Each segment must start with an alphabetical character.");
public static readonly GUIContent applicationBuildNumber = EditorGUIUtility.TrTextContent("Build");
public static readonly GUIContent appleDeveloperTeamID = EditorGUIUtility.TrTextContent("iOS Developer Team ID", "Developers can retrieve their Team ID by visiting the Apple Developer site under Account > Membership.");
public static readonly GUIContent useOnDemandResources = EditorGUIUtility.TrTextContent("Use on-demand resources*");
public static readonly GUIContent gcIncremental = EditorGUIUtility.TrTextContent("Use incremental GC", "With incremental Garbage Collection, the Garbage Collector will try to time-slice the collection task into multiple steps, to avoid long GC times preventing content from running smoothly.");
public static readonly GUIContent accelerometerFrequency = EditorGUIUtility.TrTextContent("Accelerometer Frequency*");
public static readonly GUIContent cameraUsageDescription = EditorGUIUtility.TrTextContent("Camera Usage Description*", "String shown to the user when requesting permission to use the device camera. Written to the NSCameraUsageDescription field in Xcode project's info.plist file");
public static readonly GUIContent locationUsageDescription = EditorGUIUtility.TrTextContent("Location Usage Description*", "String shown to the user when requesting permission to access the device location. Written to the NSLocationWhenInUseUsageDescription field in Xcode project's info.plist file.");
public static readonly GUIContent microphoneUsageDescription = EditorGUIUtility.TrTextContent("Microphone Usage Description*", "String shown to the user when requesting to use the device microphone. Written to the NSMicrophoneUsageDescription field in Xcode project's info.plist file");
public static readonly GUIContent bluetoothUsageDescription = EditorGUIUtility.TrTextContent("Bluetooth Usage Description*", "String shown to the user when requesting to use the device bluetooth. Written to the NSBluetoothAlwaysUsageDescription field in Xcode project's info.plist file");
public static readonly GUIContent muteOtherAudioSources = EditorGUIUtility.TrTextContent("Mute Other Audio Sources*");
public static readonly GUIContent prepareIOSForRecording = EditorGUIUtility.TrTextContent("Prepare iOS for Recording");
public static readonly GUIContent forceIOSSpeakersWhenRecording = EditorGUIUtility.TrTextContent("Force iOS Speakers when Recording");
public static readonly GUIContent UIRequiresPersistentWiFi = EditorGUIUtility.TrTextContent("Requires Persistent WiFi*");
public static readonly GUIContent insecureHttpOption = EditorGUIUtility.TrTextContent("Allow downloads over HTTP*", "");
public static readonly GUIContent insecureHttpWarning = EditorGUIUtility.TrTextContent("Plain text HTTP connections are not secure and can make your application vulnerable to attacks.");
public static readonly GUIContent[] insecureHttpOptions =
{
EditorGUIUtility.TrTextContent("Not allowed"),
EditorGUIUtility.TrTextContent("Allowed in development builds"),
EditorGUIUtility.TrTextContent("Always allowed"),
};
public static readonly GUIContent iOSURLSchemes = EditorGUIUtility.TrTextContent("Supported URL schemes*");
public static readonly GUIContent iOSExternalAudioInputNotSupported = EditorGUIUtility.TrTextContent("Audio input from Bluetooth microphones is not supported when Mute Other Audio Sources and Prepare iOS for Recording are both off.");
public static readonly GUIContent aotOptions = EditorGUIUtility.TrTextContent("AOT Compilation Options*");
public static readonly GUIContent require31 = EditorGUIUtility.TrTextContent("Require ES3.1");
public static readonly GUIContent requireAEP = EditorGUIUtility.TrTextContent("Require ES3.1+AEP");
public static readonly GUIContent require32 = EditorGUIUtility.TrTextContent("Require ES3.2");
public static readonly GUIContent skinOnGPU = EditorGUIUtility.TrTextContent("GPU Skinning*", "Calculate mesh skinning and blend shapes on the GPU via shaders");
public static readonly GUIContent[] meshDeformations = { EditorGUIUtility.TrTextContent("CPU"), EditorGUIUtility.TrTextContent("GPU"), EditorGUIUtility.TrTextContent("GPU (Batched)") };
public static readonly GUIContent scriptingDefineSymbols = EditorGUIUtility.TrTextContent("Scripting Define Symbols", "Preprocessor defines passed to the C# script compiler.");
public static readonly GUIContent additionalCompilerArguments = EditorGUIUtility.TrTextContent("Additional Compiler Arguments", "Additional arguments passed to the C# script compiler.");
public static readonly GUIContent scriptingDefineSymbolsApply = EditorGUIUtility.TrTextContent("Apply");
public static readonly GUIContent scriptingDefineSymbolsApplyRevert = EditorGUIUtility.TrTextContent("Revert");
public static readonly GUIContent scriptingDefineSymbolsCopyDefines = EditorGUIUtility.TrTextContent("Copy Defines", "Copy applied defines");
public static readonly GUIContent suppressCommonWarnings = EditorGUIUtility.TrTextContent("Suppress Common Warnings", "Suppresses C# warnings CS0169, CS0649, and CS0282.");
public static readonly GUIContent scriptingBackend = EditorGUIUtility.TrTextContent("Scripting Backend");
public static readonly GUIContent managedStrippingLevel = EditorGUIUtility.TrTextContent("Managed Stripping Level", "If scripting backend is IL2CPP, managed stripping can't be disabled.");
public static readonly GUIContent il2cppCompilerConfiguration = EditorGUIUtility.TrTextContent("C++ Compiler Configuration");
public static readonly GUIContent il2cppCodeGeneration = EditorGUIUtility.TrTextContent("IL2CPP Code Generation", "Determines whether IL2CPP should generate code optimized for runtime performance or build size/iteration.");
public static readonly GUIContent[] il2cppCodeGenerationNames = new GUIContent[] { EditorGUIUtility.TrTextContent("Faster runtime"), EditorGUIUtility.TrTextContent("Faster (smaller) builds") };
public static readonly GUIContent il2cppStacktraceInformation = EditorGUIUtility.TrTextContent("IL2CPP Stacktrace Information", "Which information to include in stack traces. Including the file name and line number may increase build size.");
public static readonly GUIContent scriptingMono2x = EditorGUIUtility.TrTextContent("Mono");
public static readonly GUIContent scriptingIL2CPP = EditorGUIUtility.TrTextContent("IL2CPP");
public static readonly GUIContent scriptingCoreCLR = EditorGUIUtility.TrTextContent("CoreCLR");
public static readonly GUIContent scriptingDefault = EditorGUIUtility.TrTextContent("Default");
public static readonly GUIContent strippingDisabled = EditorGUIUtility.TrTextContent("Disabled");
public static readonly GUIContent strippingMinimal = EditorGUIUtility.TrTextContent("Minimal");
public static readonly GUIContent strippingLow = EditorGUIUtility.TrTextContent("Low");
public static readonly GUIContent strippingMedium = EditorGUIUtility.TrTextContent("Medium");
public static readonly GUIContent strippingHigh = EditorGUIUtility.TrTextContent("High");
public static readonly GUIContent apiCompatibilityLevel = EditorGUIUtility.TrTextContent("Api Compatibility Level*");
public static readonly GUIContent apiCompatibilityLevel_NET_2_0 = EditorGUIUtility.TrTextContent(".NET 2.0");
public static readonly GUIContent apiCompatibilityLevel_NET_2_0_Subset = EditorGUIUtility.TrTextContent(".NET 2.0 Subset");
public static readonly GUIContent apiCompatibilityLevel_NET_4_6 = EditorGUIUtility.TrTextContent(".NET 4.x");
public static readonly GUIContent apiCompatibilityLevel_NET_Standard_2_0 = EditorGUIUtility.TrTextContent(".NET Standard 2.0");
public static readonly GUIContent apiCompatibilityLevel_NET_FW_Unity = EditorGUIUtility.TrTextContent(".NET Framework");
public static readonly GUIContent apiCompatibilityLevel_NET_Standard = EditorGUIUtility.TrTextContent(".NET Standard 2.1");
public static readonly GUIContent editorAssembliesCompatibilityLevel = EditorGUIUtility.TrTextContent("Editor Assemblies Compatibility Level*");
public static readonly GUIContent editorAssembliesCompatibilityLevel_Default = EditorGUIUtility.TrTextContent("Default (.NET Framework)");
public static readonly GUIContent editorAssembliesCompatibilityLevel_NET_Framework = EditorGUIUtility.TrTextContent(".NET Framework");
public static readonly GUIContent editorAssembliesCompatibilityLevel_NET_Standard = EditorGUIUtility.TrTextContent(".NET Standard");
public static readonly GUIContent scriptCompilationTitle = EditorGUIUtility.TrTextContent("Script Compilation");
public static readonly GUIContent allowUnsafeCode = EditorGUIUtility.TrTextContent("Allow 'unsafe' Code", "Allow compilation of unsafe code for predefined assemblies (Assembly-CSharp.dll, etc.)");
public static readonly GUIContent useDeterministicCompilation = EditorGUIUtility.TrTextContent("Use Deterministic Compilation", "Compile with -deterministic compilation flag");
public static readonly GUIContent activeInputHandling = EditorGUIUtility.TrTextContent("Active Input Handling*");
public static readonly GUIContent[] activeInputHandlingOptions = new GUIContent[] { EditorGUIUtility.TrTextContent("Input Manager (Old)"), EditorGUIUtility.TrTextContent("Input System Package (New)"), EditorGUIUtility.TrTextContent("Both") };
public static readonly GUIContent normalMapEncodingLabel = EditorGUIUtility.TrTextContent("Normal Map Encoding");
public static readonly GUIContent[] normalMapEncodingNames = { EditorGUIUtility.TrTextContent("XYZ"), EditorGUIUtility.TrTextContent("DXT5nm-style") };
public static readonly GUIContent lightmapEncodingLabel = EditorGUIUtility.TrTextContent("Lightmap Encoding", "Affects the encoding scheme and compression format of the lightmaps.");
public static readonly GUIContent[] lightmapEncodingNames = { EditorGUIUtility.TrTextContent("Low Quality"), EditorGUIUtility.TrTextContent("Normal Quality"), EditorGUIUtility.TrTextContent("High Quality") };
public static readonly GUIContent hdrCubemapEncodingLabel = EditorGUIUtility.TrTextContent("HDR Cubemap Encoding", "Determines which encoding scheme Unity uses to encode HDR cubemaps.");
public static readonly GUIContent[] hdrCubemapEncodingNames = { EditorGUIUtility.TrTextContent("Low Quality"), EditorGUIUtility.TrTextContent("Normal Quality"), EditorGUIUtility.TrTextContent("High Quality") };
public static readonly GUIContent lightmapStreamingEnabled = EditorGUIUtility.TrTextContent("Lightmap Streaming", "Only load larger lightmap mipmaps as needed to render the current game cameras. Requires texture streaming to be enabled in quality settings. This value is applied to the light map textures as they are generated.");
public static readonly GUIContent lightmapStreamingPriority = EditorGUIUtility.TrTextContent("Streaming Priority", "Lightmap mipmap streaming priority when there's contention for resources. Positive numbers represent higher priority. Valid range is -128 to 127. This value is applied to the light map textures as they are generated.");
public static readonly GUIContent legacyClampBlendShapeWeights = EditorGUIUtility.TrTextContent("Clamp BlendShapes (Deprecated)*", "If set, the range of BlendShape weights in SkinnedMeshRenderers will be clamped.");
public static readonly GUIContent virtualTexturingSupportEnabled = EditorGUIUtility.TrTextContent("Virtual Texturing (Experimental)*", "Enable Virtual Texturing. This feature is experimental and not ready for production use. Changing this value requires an Editor restart.");
public static readonly GUIContent virtualTexturingUnsupportedPlatformWarning = EditorGUIUtility.TrTextContent("The current target platform does not support Virtual Texturing. To build for this platform, uncheck Enable Virtual Texturing.");
public static readonly GUIContent shaderPrecisionModel = EditorGUIUtility.TrTextContent("Shader Precision Model*", "Controls the default sampler precision and the definition of HLSL half.");
public static readonly GUIContent[] shaderPrecisionModelOptions = { EditorGUIUtility.TrTextContent("Platform Default"), EditorGUIUtility.TrTextContent("Unified") };
public static readonly GUIContent stereo360CaptureCheckbox = EditorGUIUtility.TrTextContent("360 Stereo Capture*");
public static readonly GUIContent forceSRGBBlit = EditorGUIUtility.TrTextContent("Force SRGB blit", "Force SRGB blit for Linear color space.");
public static readonly GUIContent notApplicableInfo = EditorGUIUtility.TrTextContent("Not applicable for this platform.");
public static readonly GUIContent loadStoreDebugModeCheckbox = EditorGUIUtility.TrTextContent("Load/Store Action Debug Mode", "Initializes Framebuffer such that errors in the load/store actions will be visually apparent. (Removed in Release Builds)");
public static readonly GUIContent loadStoreDebugModeEditorOnlyCheckbox = EditorGUIUtility.TrTextContent("Editor Only", "Load/Store Action Debug Mode will only affect the Editor");
public static readonly GUIContent allowHDRDisplay = EditorGUIUtility.TrTextContent("Allow HDR Display Output*", "Enable the use of HDR displays and include all the resources required for them to function correctly.");
public static readonly GUIContent useHDRDisplay = EditorGUIUtility.TrTextContent("Use HDR Display Output*", "Checks if the main display supports HDR and if it does, switches to HDR output at the start of the application.");
public static readonly GUIContent hdrOutputRequireHDRRenderingWarning = EditorGUIUtility.TrTextContent("The active Render Pipeline does not have HDR enabled. Enable HDR in the Render Pipeline Asset to see the changes.");
public static readonly GUIContent captureStartupLogs = EditorGUIUtility.TrTextContent("Capture Startup Logs", "Capture startup logs for later processing (e.g., by com.unity.logging");
public static readonly string undoChangedBatchingString = L10n.Tr("Changed Batching Settings");
public static readonly string undoChangedGraphicsAPIString = L10n.Tr("Changed Graphics API Settings");
public static readonly string undoChangedScriptingDefineString = L10n.Tr("Changed Scripting Define Settings");
public static readonly string undoChangedGraphicsJobsString = L10n.Tr("Changed Graphics Jobs Setting");
public static readonly string undoChangedGraphicsJobModeString = L10n.Tr("Changed Graphics Job Mode Setting");
public static readonly string changeColorSpaceString = L10n.Tr("Changing the color space may take a significant amount of time.");
public static readonly string undoChangedPlatformShaderChunkSizeString = L10n.Tr("Changed Shader Chunk Size Platform Setting");
public static readonly string undoChangedPlatformShaderChunkCountString = L10n.Tr("Changed Shader Chunk Count Platform Setting");
public static readonly string undoChangedDefaultShaderChunkSizeString = L10n.Tr("Changed Shader Chunk Size Default Setting");
public static readonly string undoChangedDefaultShaderChunkCountString = L10n.Tr("Changed Shader Chunk Count Default Setting");
}
class RecompileReason
{
public static readonly string scriptingDefineSymbolsModified = L10n.Tr("Scripting define symbols setting modified");
public static readonly string suppressCommonWarningsModified = L10n.Tr("Suppress common warnings setting modified");
public static readonly string allowUnsafeCodeModified = L10n.Tr("Allow 'unsafe' code setting modified");
public static readonly string apiCompatibilityLevelModified = L10n.Tr("API Compatibility level modified");
public static readonly string editorAssembliesCompatibilityLevelModified = L10n.Tr("Editor Assemblies Compatibility level modified");
public static readonly string useDeterministicCompilationModified = L10n.Tr("Use deterministic compilation modified");
public static readonly string additionalCompilerArgumentsModified = L10n.Tr("Additional compiler arguments modified");
public static readonly string activeBuildTargetGroupModified = L10n.Tr("Active build target group modified");
public static readonly string presetChanged = L10n.Tr("Preset changed");
}
PlayerSettingsSplashScreenEditor m_SplashScreenEditor;
PlayerSettingsSplashScreenEditor splashScreenEditor
{
get
{
if (m_SplashScreenEditor == null)
m_SplashScreenEditor = new PlayerSettingsSplashScreenEditor(this);
return m_SplashScreenEditor;
}
}
PlayerSettingsIconsEditor m_IconsEditor;
PlayerSettingsIconsEditor iconsEditor
{
get
{
if (m_IconsEditor == null)
m_IconsEditor = new PlayerSettingsIconsEditor(this);
return m_IconsEditor;
}
}
private static MeshDeformation[] m_MeshDeformations = { MeshDeformation.CPU, MeshDeformation.GPU, MeshDeformation.GPUBatched };
// Section and tab selection state
SavedInt m_SelectedSection = new SavedInt("PlayerSettings.ShownSection", -1);
BuildPlatform[] validPlatforms;
NamedBuildTarget lastNamedBuildTarget;
// il2cpp
SerializedProperty m_StripEngineCode;
// macOS
SerializedProperty m_ApplicationBundleVersion;
SerializedProperty m_UseMacAppStoreValidation;
SerializedProperty m_MacAppStoreCategory;
SerializedProperty m_MacURLSchemes;
// vulkan
SerializedProperty m_VulkanNumSwapchainBuffers;
SerializedProperty m_VulkanEnableLateAcquireNextImage;
SerializedProperty m_VulkanEnableCommandBufferRecycling;
// iOS, tvOS
#pragma warning disable 169
SerializedProperty m_IPhoneApplicationDisplayName;
SerializedProperty m_CameraUsageDescription;
SerializedProperty m_LocationUsageDescription;
SerializedProperty m_MicrophoneUsageDescription;
SerializedProperty m_BluetoothUsageDescription;
SerializedProperty m_IPhoneScriptCallOptimization;
SerializedProperty m_AotOptions;
SerializedProperty m_DefaultScreenOrientation;
SerializedProperty m_AllowedAutoRotateToPortrait;
SerializedProperty m_AllowedAutoRotateToPortraitUpsideDown;
SerializedProperty m_AllowedAutoRotateToLandscapeRight;
SerializedProperty m_AllowedAutoRotateToLandscapeLeft;
SerializedProperty m_UseOSAutoRotation;
SerializedProperty m_Use32BitDisplayBuffer;
SerializedProperty m_PreserveFramebufferAlpha;
SerializedProperty m_DisableDepthAndStencilBuffers;
SerializedProperty m_AndroidProfiler;
SerializedProperty m_UIRequiresPersistentWiFi;
SerializedProperty m_UIStatusBarHidden;
SerializedProperty m_UIRequiresFullScreen;
SerializedProperty m_UIStatusBarStyle;
SerializedProperty m_InsecureHttpOption;
SerializedProperty m_SubmitAnalytics;
SerializedProperty m_IOSURLSchemes;
SerializedProperty m_AccelerometerFrequency;
SerializedProperty m_useOnDemandResources;
SerializedProperty m_MuteOtherAudioSources;
SerializedProperty m_PrepareIOSForRecording;
SerializedProperty m_ForceIOSSpeakersWhenRecording;
SerializedProperty m_EnableInternalProfiler;
SerializedProperty m_ActionOnDotNetUnhandledException;
SerializedProperty m_LogObjCUncaughtExceptions;
SerializedProperty m_EnableCrashReportAPI;
SerializedProperty m_SuppressCommonWarnings;
SerializedProperty m_AllowUnsafeCode;
SerializedProperty m_GCIncremental;
SerializedProperty m_OverrideDefaultApplicationIdentifier;
SerializedProperty m_ApplicationIdentifier;
SerializedProperty m_BuildNumber;
// General
SerializedProperty m_CompanyName;
SerializedProperty m_ProductName;
// Cursor
SerializedProperty m_DefaultCursor;
SerializedProperty m_CursorHotspot;
// Screen
SerializedProperty m_DefaultScreenWidth;
SerializedProperty m_DefaultScreenHeight;
SerializedProperty m_ActiveColorSpace;
SerializedProperty m_UnsupportedMSAAFallback;
SerializedProperty m_StripUnusedMeshComponents;
SerializedProperty m_StrictShaderVariantMatching;
SerializedProperty m_MipStripping;
SerializedProperty m_VertexChannelCompressionMask;
SerializedProperty m_MetalAPIValidation;
SerializedProperty m_MetalFramebufferOnly;
SerializedProperty m_MetalForceHardShadows;
SerializedProperty m_FramebufferDepthMemorylessMode;
SerializedProperty m_DefaultIsNativeResolution;
SerializedProperty m_MacRetinaSupport;
SerializedProperty m_UsePlayerLog;
SerializedProperty m_CaptureStartupLogs;
SerializedProperty m_KeepLoadedShadersAlive;
SerializedProperty m_PreloadedAssets;
SerializedProperty m_BakeCollisionMeshes;
SerializedProperty m_DedicatedServerOptimizations;
SerializedProperty m_ResizableWindow;
SerializedProperty m_FullscreenMode;
SerializedProperty m_VisibleInBackground;
SerializedProperty m_AllowFullscreenSwitch;
SerializedProperty m_ForceSingleInstance;
SerializedProperty m_UseFlipModelSwapchain;
SerializedProperty m_RunInBackground;
SerializedProperty m_CaptureSingleScreen;
SerializedProperty m_SkinOnGPU;
SerializedProperty m_MeshDeformation;
SerializedProperty m_EnableLoadStoreDebugMode;
// OpenGL ES 3.1+
SerializedProperty m_RequireES31;
SerializedProperty m_RequireES31AEP;
SerializedProperty m_RequireES32;
SerializedProperty m_LightmapEncodingQuality;
SerializedProperty m_HDRCubemapEncodingQuality;
SerializedProperty m_LightmapStreamingEnabled;
SerializedProperty m_LightmapStreamingPriority;
SerializedProperty m_HDRBitDepth;
// WebGPU
SerializedProperty m_WebGPUSupportEnabled;
// Legacy
SerializedProperty m_LegacyClampBlendShapeWeights;
SerializedProperty m_AndroidEnableTango;
SerializedProperty m_Enable360StereoCapture;
SerializedProperty m_VirtualTexturingSupportEnabled;
SerializedProperty m_ShaderPrecisionModel;
// Scripting
SerializedProperty m_UseDeterministicCompilation;
SerializedProperty m_ScriptingBackend;
SerializedProperty m_APICompatibilityLevel;
SerializedProperty m_DefaultAPICompatibilityLevel;
SerializedProperty m_EditorAssembliesCompatibilityLevel;
SerializedProperty m_Il2CppCompilerConfiguration;
SerializedProperty m_Il2CppCodeGeneration;
SerializedProperty m_Il2CppStacktraceInformation;
SerializedProperty m_ScriptingDefines;
SerializedProperty m_AdditionalCompilerArguments;
SerializedProperty m_StackTraceTypes;
SerializedProperty m_ManagedStrippingLevel;
SerializedProperty m_ActiveInputHandler;
// Embedded Linux specific
SerializedProperty m_ForceSRGBBlit;
// Localization Cache
string m_LocalizedTargetName;
// reorderable lists of graphics devices, per platform
static Dictionary<BuildTarget, ReorderableList> s_GraphicsDeviceLists = new Dictionary<BuildTarget, ReorderableList>();
public static void SyncPlatformAPIsList(BuildTarget target)
{
if (!s_GraphicsDeviceLists.ContainsKey(target))
return;
s_GraphicsDeviceLists[target].list = PlayerSettings.GetGraphicsAPIs(target).ToList();
}
static ReorderableList s_ScriptingDefineSymbolsList;
static ReorderableList s_ColorGamutList;
public static void SyncColorGamuts()
{
s_ColorGamutList.list = PlayerSettings.GetColorGamuts().ToList();
}
int scriptingDefinesControlID = 0;
int serializedActiveInputHandler = 0;
string[] serializedAdditionalCompilerArguments;
bool serializedSuppressCommonWarnings = true;
bool serializedAllowUnsafeCode = false;
string serializedScriptingDefines;
bool serializedUseDeterministicCompilation;
List<string> scriptingDefinesList;
bool hasScriptingDefinesBeenModified;
ReorderableList scriptingDefineSymbolsList;
List<string> additionalCompilerArgumentsList;
bool hasAdditionalCompilerArgumentsBeenModified;
ReorderableList additionalCompilerArgumentsReorderableList;
ISettingEditorExtension[] m_SettingsExtensions;
private HashSet<string> m_Reasons = new HashSet<string>();
// Section animation state
const int kNumberGUISections = 7;
List<AnimBool> m_SectionAnimators = new List<AnimBool>(kNumberGUISections);
readonly AnimBool m_ShowDefaultIsNativeResolution = new AnimBool();
readonly AnimBool m_ShowResolution = new AnimBool();
private static Texture2D s_WarningIcon;
// Preset check
bool isPreset = false;
bool isPresetWindowOpen = false;
bool hasPresetWindowClosed = false;
const string kSelectedPlatform = "PlayerSettings.SelectedPlatform";
public SerializedProperty FindPropertyAssert(string name)
{
SerializedProperty property = serializedObject.FindProperty(name);
if (property == null)
Debug.LogError("Failed to find:" + name);
return property;
}
private static List<PlayerSettingsEditor> s_activeEditors = new List<PlayerSettingsEditor>();
void OnEnable()
{
s_activeEditors.Add(this);
isPreset = Preset.IsEditorTargetAPreset(target);
validPlatforms = BuildPlatforms.instance.GetValidPlatforms(true).ToArray();
m_StripEngineCode = FindPropertyAssert("stripEngineCode");
m_IPhoneScriptCallOptimization = FindPropertyAssert("iPhoneScriptCallOptimization");
m_AndroidProfiler = FindPropertyAssert("AndroidProfiler");
m_CompanyName = FindPropertyAssert("companyName");
m_ProductName = FindPropertyAssert("productName");
m_DefaultCursor = FindPropertyAssert("defaultCursor");
m_CursorHotspot = FindPropertyAssert("cursorHotspot");
m_UIRequiresFullScreen = FindPropertyAssert("uIRequiresFullScreen");
m_UIStatusBarHidden = FindPropertyAssert("uIStatusBarHidden");
m_UIStatusBarStyle = FindPropertyAssert("uIStatusBarStyle");
m_ActiveColorSpace = FindPropertyAssert("m_ActiveColorSpace");
m_UnsupportedMSAAFallback = FindPropertyAssert("unsupportedMSAAFallback");
m_StripUnusedMeshComponents = FindPropertyAssert("StripUnusedMeshComponents");
m_StrictShaderVariantMatching = FindPropertyAssert("strictShaderVariantMatching");
m_MipStripping = FindPropertyAssert("mipStripping");
m_VertexChannelCompressionMask = FindPropertyAssert("VertexChannelCompressionMask");
m_MetalAPIValidation = FindPropertyAssert("metalAPIValidation");
m_MetalFramebufferOnly = FindPropertyAssert("metalFramebufferOnly");
m_MetalForceHardShadows = FindPropertyAssert("iOSMetalForceHardShadows");
m_FramebufferDepthMemorylessMode = FindPropertyAssert("framebufferDepthMemorylessMode");
m_OverrideDefaultApplicationIdentifier = FindPropertyAssert("overrideDefaultApplicationIdentifier");
m_ApplicationIdentifier = FindPropertyAssert("applicationIdentifier");
m_BuildNumber = FindPropertyAssert("buildNumber");
m_ApplicationBundleVersion = serializedObject.FindProperty("bundleVersion");
if (m_ApplicationBundleVersion == null)
m_ApplicationBundleVersion = FindPropertyAssert("iPhoneBundleVersion");
m_useOnDemandResources = FindPropertyAssert("useOnDemandResources");
m_AccelerometerFrequency = FindPropertyAssert("accelerometerFrequency");
m_MuteOtherAudioSources = FindPropertyAssert("muteOtherAudioSources");
m_PrepareIOSForRecording = FindPropertyAssert("Prepare IOS For Recording");
m_ForceIOSSpeakersWhenRecording = FindPropertyAssert("Force IOS Speakers When Recording");
m_UIRequiresPersistentWiFi = FindPropertyAssert("uIRequiresPersistentWiFi");
m_InsecureHttpOption = FindPropertyAssert("insecureHttpOption");
m_SubmitAnalytics = FindPropertyAssert("submitAnalytics");
m_IOSURLSchemes = FindPropertyAssert("iOSURLSchemes");
m_AotOptions = FindPropertyAssert("aotOptions");
m_CameraUsageDescription = FindPropertyAssert("cameraUsageDescription");
m_LocationUsageDescription = FindPropertyAssert("locationUsageDescription");
m_MicrophoneUsageDescription = FindPropertyAssert("microphoneUsageDescription");
m_BluetoothUsageDescription = FindPropertyAssert("bluetoothUsageDescription");
m_EnableInternalProfiler = FindPropertyAssert("enableInternalProfiler");
m_ActionOnDotNetUnhandledException = FindPropertyAssert("actionOnDotNetUnhandledException");
m_LogObjCUncaughtExceptions = FindPropertyAssert("logObjCUncaughtExceptions");
m_EnableCrashReportAPI = FindPropertyAssert("enableCrashReportAPI");
m_SuppressCommonWarnings = FindPropertyAssert("suppressCommonWarnings");
m_AllowUnsafeCode = FindPropertyAssert("allowUnsafeCode");
m_GCIncremental = FindPropertyAssert("gcIncremental");
m_UseDeterministicCompilation = FindPropertyAssert("useDeterministicCompilation");
m_ScriptingBackend = FindPropertyAssert("scriptingBackend");
m_APICompatibilityLevel = FindPropertyAssert("apiCompatibilityLevelPerPlatform");
m_DefaultAPICompatibilityLevel = FindPropertyAssert("apiCompatibilityLevel");
m_EditorAssembliesCompatibilityLevel = FindPropertyAssert("editorAssembliesCompatibilityLevel");
m_Il2CppCompilerConfiguration = FindPropertyAssert("il2cppCompilerConfiguration");
m_Il2CppCodeGeneration = FindPropertyAssert("il2cppCodeGeneration");
m_Il2CppStacktraceInformation = FindPropertyAssert("il2cppStacktraceInformation");
m_ScriptingDefines = FindPropertyAssert("scriptingDefineSymbols");
m_StackTraceTypes = FindPropertyAssert("m_StackTraceTypes");
m_ManagedStrippingLevel = FindPropertyAssert("managedStrippingLevel");
m_ActiveInputHandler = FindPropertyAssert("activeInputHandler");
m_AdditionalCompilerArguments = FindPropertyAssert("additionalCompilerArguments");
m_DefaultScreenWidth = FindPropertyAssert("defaultScreenWidth");
m_DefaultScreenHeight = FindPropertyAssert("defaultScreenHeight");
m_RunInBackground = FindPropertyAssert("runInBackground");
m_DefaultScreenOrientation = FindPropertyAssert("defaultScreenOrientation");
m_AllowedAutoRotateToPortrait = FindPropertyAssert("allowedAutorotateToPortrait");
m_AllowedAutoRotateToPortraitUpsideDown = FindPropertyAssert("allowedAutorotateToPortraitUpsideDown");
m_AllowedAutoRotateToLandscapeRight = FindPropertyAssert("allowedAutorotateToLandscapeRight");
m_AllowedAutoRotateToLandscapeLeft = FindPropertyAssert("allowedAutorotateToLandscapeLeft");
m_UseOSAutoRotation = FindPropertyAssert("useOSAutorotation");
m_Use32BitDisplayBuffer = FindPropertyAssert("use32BitDisplayBuffer");
m_PreserveFramebufferAlpha = FindPropertyAssert("preserveFramebufferAlpha");
m_DisableDepthAndStencilBuffers = FindPropertyAssert("disableDepthAndStencilBuffers");
m_DefaultIsNativeResolution = FindPropertyAssert("defaultIsNativeResolution");
m_MacRetinaSupport = FindPropertyAssert("macRetinaSupport");
m_CaptureSingleScreen = FindPropertyAssert("captureSingleScreen");
m_UsePlayerLog = FindPropertyAssert("usePlayerLog");
m_CaptureStartupLogs = FindPropertyAssert("captureStartupLogs");
m_KeepLoadedShadersAlive = FindPropertyAssert("keepLoadedShadersAlive");
m_PreloadedAssets = FindPropertyAssert("preloadedAssets");
m_BakeCollisionMeshes = FindPropertyAssert("bakeCollisionMeshes");
m_DedicatedServerOptimizations = FindPropertyAssert("dedicatedServerOptimizations");
m_ResizableWindow = FindPropertyAssert("resizableWindow");
m_UseMacAppStoreValidation = FindPropertyAssert("useMacAppStoreValidation");
m_MacAppStoreCategory = FindPropertyAssert("macAppStoreCategory");
m_MacURLSchemes = FindPropertyAssert("macOSURLSchemes");
m_VulkanNumSwapchainBuffers = FindPropertyAssert("vulkanNumSwapchainBuffers");
m_VulkanEnableLateAcquireNextImage = FindPropertyAssert("vulkanEnableLateAcquireNextImage");
m_VulkanEnableCommandBufferRecycling = FindPropertyAssert("vulkanEnableCommandBufferRecycling");
m_FullscreenMode = FindPropertyAssert("fullscreenMode");
m_VisibleInBackground = FindPropertyAssert("visibleInBackground");
m_AllowFullscreenSwitch = FindPropertyAssert("allowFullscreenSwitch");
m_SkinOnGPU = FindPropertyAssert("gpuSkinning");
m_MeshDeformation = FindPropertyAssert("meshDeformation");
m_ForceSingleInstance = FindPropertyAssert("forceSingleInstance");
m_UseFlipModelSwapchain = FindPropertyAssert("useFlipModelSwapchain");
m_RequireES31 = FindPropertyAssert("openGLRequireES31");
m_RequireES31AEP = FindPropertyAssert("openGLRequireES31AEP");
m_RequireES32 = FindPropertyAssert("openGLRequireES32");
// WebGPU - Forcibly enable in source builds to make it easier to test.
m_WebGPUSupportEnabled = FindPropertyAssert("webGLEnableWebGPU");
m_LegacyClampBlendShapeWeights = FindPropertyAssert("legacyClampBlendShapeWeights");
m_AndroidEnableTango = FindPropertyAssert("AndroidEnableTango");
SerializedProperty property = FindPropertyAssert("vrSettings");
if (property != null)
m_Enable360StereoCapture = property.FindPropertyRelative("enable360StereoCapture");
m_VirtualTexturingSupportEnabled = FindPropertyAssert("virtualTexturingSupportEnabled");
m_ShaderPrecisionModel = FindPropertyAssert("shaderPrecisionModel");
m_ForceSRGBBlit = FindPropertyAssert("hmiForceSRGBBlit");
var validPlatformsLength = validPlatforms.Length;
m_SettingsExtensions = new ISettingEditorExtension[validPlatformsLength];
var currentPlatform = 0;
for (int i = 0; i < validPlatformsLength; i++)
{
string module = ModuleManager.GetTargetStringFromBuildTargetGroup(validPlatforms[i].namedBuildTarget.ToBuildTargetGroup());
m_SettingsExtensions[i] = ModuleManager.GetEditorSettingsExtension(module);
if (m_SettingsExtensions[i] != null)
m_SettingsExtensions[i].OnEnable(this);
if (validPlatforms[i].IsActive())
currentPlatform = i;
}
for (int i = 0; i < kNumberGUISections; i++)
m_SectionAnimators.Add(new AnimBool(m_SelectedSection.value == i));
SetValueChangeListeners(Repaint);
splashScreenEditor.OnEnable();
iconsEditor.OnEnable();
// we clear it just to be on the safe side:
// we access this cache both from player settings editor and script side when changing api
s_GraphicsDeviceLists.Clear();
var selectedPlatform = SessionState.GetInt(kSelectedPlatform, currentPlatform);
if (selectedPlatform < 0)
selectedPlatform = 0;
if (selectedPlatform >= validPlatformsLength)
selectedPlatform = validPlatformsLength - 1;
// Setup initial values to prevent immediate script recompile (or editor restart)
NamedBuildTarget namedBuildTarget = validPlatforms[selectedPlatform].namedBuildTarget;
serializedActiveInputHandler = m_ActiveInputHandler.intValue;
serializedSuppressCommonWarnings = m_SuppressCommonWarnings.boolValue;
serializedAllowUnsafeCode = m_AllowUnsafeCode.boolValue;
serializedAdditionalCompilerArguments = GetAdditionalCompilerArgumentsForGroup(namedBuildTarget);
serializedScriptingDefines = GetScriptingDefineSymbolsForGroup(namedBuildTarget);
serializedUseDeterministicCompilation = m_UseDeterministicCompilation.boolValue;
InitReorderableScriptingDefineSymbolsList(namedBuildTarget);
InitReorderableAdditionalCompilerArgumentsList(namedBuildTarget);
FindPlayerSettingsAttributeSections();
}
void OnDisable()
{
s_activeEditors.Remove(this);
HandlePendingChangesRequiringRecompilation();
// Ensure script compilation handling is returned to to EditorOnlyPlayerSettings
if (!isPreset)
PlayerSettings.isHandlingScriptRecompile = true;
}
[RequiredByNativeCode]
private static void HandlePendingChangesBeforeEnterPlaymode()
{
foreach (var editor in s_activeEditors)
{
editor.HandlePendingChangesRequiringRecompilation();
}
}
private void HandlePendingChangesRequiringRecompilation()
{
if (hasScriptingDefinesBeenModified)
{
if (EditorUtility.DisplayDialog("Scripting Define Symbols Have Been Modified", "Do you want to apply changes?", "Apply", "Revert"))
{
SetScriptingDefineSymbolsForGroup(lastNamedBuildTarget, scriptingDefinesList.ToArray());
SetReason(RecompileReason.scriptingDefineSymbolsModified);
}
else
{
InitReorderableScriptingDefineSymbolsList(lastNamedBuildTarget);
}
hasScriptingDefinesBeenModified = false;
}
if (hasAdditionalCompilerArgumentsBeenModified)
{
if (EditorUtility.DisplayDialog("Additional Compiler Arguments Have Been Modified", "Do you want to apply changes?", "Apply", "Revert"))
{
SetAdditionalCompilerArgumentsForGroup(lastNamedBuildTarget, additionalCompilerArgumentsList.ToArray());
SetReason(RecompileReason.additionalCompilerArgumentsModified);
}
else
{
InitReorderableAdditionalCompilerArgumentsList(lastNamedBuildTarget);
}
hasAdditionalCompilerArgumentsBeenModified = false;
}
if (HasReasonToCompile())
{
serializedObject.ApplyModifiedProperties();
RecompileScripts();
}
}
public void SetValueChangeListeners(UnityAction action)
{
for (int i = 0; i < m_SectionAnimators.Count; i++)
{
m_SectionAnimators[i].valueChanged.RemoveAllListeners();
m_SectionAnimators[i].valueChanged.AddListener(action);
}
m_ShowDefaultIsNativeResolution.valueChanged.RemoveAllListeners();
m_ShowDefaultIsNativeResolution.valueChanged.AddListener(action);
m_ShowResolution.valueChanged.RemoveAllListeners();
m_ShowResolution.valueChanged.AddListener(action);
}
public override bool UseDefaultMargins()
{
return false;
}
internal override string targetTitle
{
get
{
if (m_LocalizedTargetName == null)
m_LocalizedTargetName = L10n.Tr(target.name);
return m_LocalizedTargetName;
}
}
private void CheckUpdatePresetSelectorStatus()
{
if (isPreset)
return;
bool isOpen = PresetEditorHelper.presetEditorOpen;
hasPresetWindowClosed = (isPresetWindowOpen && !isOpen);
isPresetWindowOpen = isOpen;
if (isPresetWindowOpen)
PlayerSettings.isHandlingScriptRecompile = false;
}
private void SetReason(string reason)
{
if (isPreset)
{
return;
}
m_Reasons.Add(reason);
}
private string ConvertReasonsToString()
{
var sb = new StringBuilder();
foreach (var reason in m_Reasons)
{
sb.AppendLine(reason);
}
return sb.ToString();
}
private void RecompileScripts()
{
if (isPreset || isPresetWindowOpen)
{
return;
}
var reasons = ConvertReasonsToString();
PlayerSettings.RecompileScripts(reasons);
m_Reasons.Clear();
}
private bool HasReasonToCompile()
{
return m_Reasons.Count > 0;
}
private bool SupportsRunInBackground(NamedBuildTarget buildTarget)
{
return buildTarget == NamedBuildTarget.Standalone || buildTarget == NamedBuildTarget.Android;
}
private void OnPresetSelectorClosed()
{
hasPresetWindowClosed = false;
if (isPreset)
return;
if (HasReasonToCompile())
{
RecompileScripts();
}
PlayerSettings.isHandlingScriptRecompile = true;
}
public override void OnInspectorGUI()
{
var serializedObjectUpdated = serializedObject.UpdateIfRequiredOrScript();
EditorGUILayout.BeginVertical();
{
CommonSettings();
}
EditorGUILayout.EndVertical();
EditorGUILayout.Space();
EditorGUI.BeginChangeCheck();
int oldPlatform = SessionState.GetInt(kSelectedPlatform, 0);
int selectedPlatformValue = EditorGUILayout.BeginPlatformGrouping(validPlatforms, null);
if (selectedPlatformValue != oldPlatform)
{
SessionState.SetInt(kSelectedPlatform, selectedPlatformValue);
}
if (EditorGUI.EndChangeCheck())
{
// Awesome hackery to get string from delayed textfield when switching platforms
if (EditorGUI.s_DelayedTextEditor.IsEditingControl(scriptingDefinesControlID))
{
EditorGUI.EndEditingActiveTextField();
GUIUtility.keyboardControl = 0;
string[] defines = ScriptingDefinesHelper.ConvertScriptingDefineStringToArray(EditorGUI.s_DelayedTextEditor.text);
SetScriptingDefineSymbolsForGroup(validPlatforms[oldPlatform].namedBuildTarget, defines);
}
// Reset focus when changing between platforms.
// If we don't do this, the resolution width/height value will not update correctly when they have the focus
GUI.FocusControl("");
m_SerializedObject.ApplyModifiedPropertiesWithoutUndo();
}
BuildPlatform platform = validPlatforms[selectedPlatformValue];
if (!isPreset)
{
CheckUpdatePresetSelectorStatus();
}
GUILayout.Label(string.Format(L10n.Tr("Settings for {0}"), validPlatforms[selectedPlatformValue].title.text));
// Increase the offset to accomodate large labels, though keep a minimum of 150.
EditorGUIUtility.labelWidth = Mathf.Max(150, EditorGUIUtility.labelWidth + 4);
int sectionIndex = 0;
if (serializedObjectUpdated)
{
m_IconsEditor.SerializedObjectUpdated();
foreach (var settingsExtension in m_SettingsExtensions)
{
settingsExtension?.SerializedObjectUpdated();
}
}
m_IconsEditor.IconSectionGUI(platform.namedBuildTarget, m_SettingsExtensions[selectedPlatformValue], selectedPlatformValue, sectionIndex++);
ResolutionSectionGUI(platform.namedBuildTarget, m_SettingsExtensions[selectedPlatformValue], sectionIndex++);
m_SplashScreenEditor.SplashSectionGUI(platform, m_SettingsExtensions[selectedPlatformValue], sectionIndex++);
DebugAndCrashReportingGUI(platform, m_SettingsExtensions[selectedPlatformValue], sectionIndex++);
OtherSectionGUI(platform, m_SettingsExtensions[selectedPlatformValue], sectionIndex++);
PublishSectionGUI(platform, m_SettingsExtensions[selectedPlatformValue], sectionIndex++);
PlayerSettingsAttributeSectionsGUI(platform.namedBuildTarget, m_SettingsExtensions[selectedPlatformValue], ref sectionIndex);
EditorGUILayout.EndPlatformGrouping();
serializedObject.ApplyModifiedProperties();
if (hasPresetWindowClosed)
{
// We recompile after the window is closed just to make sure all the values are set/shown correctly.
// There might be a smarter idea where you detect the values that have changed and only do it if it's required,
// but the way the Preset window applies those changes as well as the way IMGUI works makes it difficult to track.
SetReason(RecompileReason.presetChanged);
OnPresetSelectorClosed();
}
else if (HasReasonToCompile())
{
RecompileScripts();
}
}
private void CommonSettings()
{
EditorGUILayout.PropertyField(m_CompanyName);
EditorGUILayout.PropertyField(m_ProductName);
EditorGUILayout.PropertyField(m_ApplicationBundleVersion, EditorGUIUtility.TrTextContent("Version"));
EditorGUILayout.Space();
m_IconsEditor.LegacyIconSectionGUI();
GUILayout.Space(3);
Rect cursorPropertyRect = EditorGUILayout.GetControlRect(true, EditorGUI.kObjectFieldThumbnailHeight);
EditorGUI.BeginProperty(cursorPropertyRect, SettingsContent.defaultCursor, m_DefaultCursor);
m_DefaultCursor.objectReferenceValue = EditorGUI.ObjectField(cursorPropertyRect, SettingsContent.defaultCursor, m_DefaultCursor.objectReferenceValue, typeof(Texture2D), false);
EditorGUI.EndProperty();
Rect rect = EditorGUILayout.GetControlRect();
rect = EditorGUI.PrefixLabel(rect, 0, SettingsContent.cursorHotspot);
EditorGUI.PropertyField(rect, m_CursorHotspot, GUIContent.none);
}
public bool BeginSettingsBox(int nr, GUIContent header)
{
if (nr >= m_SectionAnimators.Count)
m_SectionAnimators.Add(new AnimBool());
bool enabled = GUI.enabled;
GUI.enabled = true; // we don't want to disable the expand behavior
EditorGUILayout.BeginVertical(Styles.categoryBox);
Rect r = GUILayoutUtility.GetRect(20, 21);
EditorGUI.BeginChangeCheck();
bool expanded = EditorGUI.FoldoutTitlebar(r, header, m_SelectedSection.value == nr, true, EditorStyles.inspectorTitlebarFlat, EditorStyles.inspectorTitlebarText);
if (EditorGUI.EndChangeCheck())
{
m_SelectedSection.value = (expanded ? nr : -1);
GUIUtility.keyboardControl = 0;
}
m_SectionAnimators[nr].target = expanded;
GUI.enabled = enabled;
EditorGUI.indentLevel++;
return EditorGUILayout.BeginFadeGroup(m_SectionAnimators[nr].faded);
}
public void EndSettingsBox()
{
EditorGUILayout.EndFadeGroup();
EditorGUI.indentLevel--;
EditorGUILayout.EndVertical();
}
public void ShowSharedNote()
{
GUILayout.Label(SettingsContent.sharedBetweenPlatformsInfo, EditorStyles.miniLabel);
}
internal static void ShowNoSettings()
{
GUILayout.Label(SettingsContent.notApplicableInfo, EditorStyles.miniLabel);
}
private static bool TargetSupportsOptionalBuiltinSplashScreen(BuildTargetGroup targetGroup, ISettingEditorExtension settingsExtension)
{
if (settingsExtension != null)
return settingsExtension.CanShowUnitySplashScreen();
return targetGroup == BuildTargetGroup.Standalone;
}
public void ResolutionSectionGUI(NamedBuildTarget namedBuildTarget, ISettingEditorExtension settingsExtension, int sectionIndex = 0)
{
if (BeginSettingsBox(sectionIndex, SettingsContent.resolutionPresentationTitle))
{
// PLEASE DO NOT COPY SETTINGS TO APPEAR MULTIPLE PLACES IN THE CODE! See top of file for more info.
if (namedBuildTarget == NamedBuildTarget.Server)
{
ShowNoSettings();
EditorGUILayout.Space();
}
else
{
GUILayout.Label(SettingsContent.resolutionTitle, EditorStyles.boldLabel);
if (SupportsRunInBackground(namedBuildTarget))
EditorGUILayout.PropertyField(m_RunInBackground, SettingsContent.runInBackground);
// Resolution itself
if (settingsExtension != null)
{
float h = EditorGUI.kSingleLineHeight;
float kLabelFloatMinW = EditorGUI.kLabelW + EditorGUIUtility.fieldWidth + EditorGUI.kSpacing;
float kLabelFloatMaxW = EditorGUI.kLabelW + EditorGUIUtility.fieldWidth + EditorGUI.kSpacing;
settingsExtension.ResolutionSectionGUI(h, kLabelFloatMinW, kLabelFloatMaxW);
}
if (namedBuildTarget == NamedBuildTarget.Standalone)
{
var fullscreenModes = new[] { FullScreenMode.FullScreenWindow, FullScreenMode.ExclusiveFullScreen, FullScreenMode.MaximizedWindow, FullScreenMode.Windowed };
var fullscreenModeNames = new[] { SettingsContent.fullscreenWindow, SettingsContent.exclusiveFullscreen, SettingsContent.maximizedWindow, SettingsContent.windowed };
var fullscreenModeNew = FullScreenMode.FullScreenWindow;
using (var horizontal = new EditorGUILayout.HorizontalScope())
{
using (new EditorGUI.PropertyScope(horizontal.rect, GUIContent.none, m_FullscreenMode))
{
fullscreenModeNew = BuildEnumPopup(m_FullscreenMode, SettingsContent.fullscreenMode, fullscreenModes, fullscreenModeNames);
}
}
bool defaultIsFullScreen = fullscreenModeNew != FullScreenMode.Windowed;
m_ShowDefaultIsNativeResolution.target = defaultIsFullScreen;
if (EditorGUILayout.BeginFadeGroup(m_ShowDefaultIsNativeResolution.faded))
EditorGUILayout.PropertyField(m_DefaultIsNativeResolution);
EditorGUILayout.EndFadeGroup();
m_ShowResolution.target = !(defaultIsFullScreen && m_DefaultIsNativeResolution.boolValue);
if (EditorGUILayout.BeginFadeGroup(m_ShowResolution.faded))
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_DefaultScreenWidth, SettingsContent.defaultScreenWidth);
if (EditorGUI.EndChangeCheck() && m_DefaultScreenWidth.intValue < 1)
m_DefaultScreenWidth.intValue = 1;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_DefaultScreenHeight, SettingsContent.defaultScreenHeight);
if (EditorGUI.EndChangeCheck() && m_DefaultScreenHeight.intValue < 1)
m_DefaultScreenHeight.intValue = 1;
}
EditorGUILayout.EndFadeGroup();
}
if (namedBuildTarget == NamedBuildTarget.Standalone)
EditorGUILayout.PropertyField(m_MacRetinaSupport, SettingsContent.macRetinaSupport);
if (settingsExtension != null && settingsExtension.SupportsOrientation())
{
GUILayout.Label(SettingsContent.orientationTitle, EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_DefaultScreenOrientation, SettingsContent.defaultScreenOrientation);
if (m_DefaultScreenOrientation.enumValueIndex == (int)UIOrientation.AutoRotation)
{
if (namedBuildTarget == NamedBuildTarget.iOS)
EditorGUILayout.PropertyField(m_UseOSAutoRotation, SettingsContent.useOSAutoRotation);
if (settingsExtension != null)
settingsExtension.AutoRotationSectionGUI();
EditorGUI.indentLevel++;
GUILayout.Label(SettingsContent.allowedOrientationTitle, EditorStyles.boldLabel);
bool somethingAllowed = m_AllowedAutoRotateToPortrait.boolValue
|| m_AllowedAutoRotateToPortraitUpsideDown.boolValue
|| m_AllowedAutoRotateToLandscapeRight.boolValue
|| m_AllowedAutoRotateToLandscapeLeft.boolValue;
if (!somethingAllowed)
{
m_AllowedAutoRotateToPortrait.boolValue = true;
Debug.LogError("All orientations are disabled. Allowing portrait");
}
EditorGUILayout.PropertyField(m_AllowedAutoRotateToPortrait, SettingsContent.allowedAutoRotateToPortrait);
EditorGUILayout.PropertyField(m_AllowedAutoRotateToPortraitUpsideDown, SettingsContent.allowedAutoRotateToPortraitUpsideDown);
EditorGUILayout.PropertyField(m_AllowedAutoRotateToLandscapeRight, SettingsContent.allowedAutoRotateToLandscapeRight);
EditorGUILayout.PropertyField(m_AllowedAutoRotateToLandscapeLeft, SettingsContent.allowedAutoRotateToLandscapeLeft);
EditorGUI.indentLevel--;
}
}
if (namedBuildTarget == NamedBuildTarget.iOS)
{
GUILayout.Label(SettingsContent.multitaskingSupportTitle, EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_UIRequiresFullScreen, SettingsContent.UIRequiresFullScreen);
EditorGUILayout.Space();
GUILayout.Label(SettingsContent.statusBarTitle, EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_UIStatusBarHidden, SettingsContent.UIStatusBarHidden);
EditorGUILayout.PropertyField(m_UIStatusBarStyle, SettingsContent.UIStatusBarStyle);
EditorGUILayout.Space();
}
EditorGUILayout.Space();
// Standalone Player
if (namedBuildTarget == NamedBuildTarget.Standalone)
{
GUILayout.Label(SettingsContent.standalonePlayerOptionsTitle, EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_CaptureSingleScreen);
EditorGUILayout.PropertyField(m_UsePlayerLog);
EditorGUILayout.PropertyField(m_ResizableWindow);
EditorGUILayout.PropertyField(m_VisibleInBackground, SettingsContent.visibleInBackground);
EditorGUILayout.PropertyField(m_AllowFullscreenSwitch, SettingsContent.allowFullscreenSwitch);
EditorGUILayout.PropertyField(m_ForceSingleInstance);
EditorGUILayout.PropertyField(m_UseFlipModelSwapchain, SettingsContent.useFlipModelSwapChain);
if (!PlayerSettings.useFlipModelSwapchain)
{
EditorGUILayout.HelpBox(SettingsContent.flipModelSwapChainWarning.text, MessageType.Warning, true);
}
EditorGUILayout.Space();
}
// integrated gpu color/depth bits setup
if (BuildTargetDiscovery.PlatformGroupHasFlag(namedBuildTarget.ToBuildTargetGroup(), TargetAttributes.HasIntegratedGPU))
{
// iOS, while supports 16bit FB through GL interface, use 32bit in hardware, so there is no need in 16bit
if (namedBuildTarget != NamedBuildTarget.iOS &&
namedBuildTarget != NamedBuildTarget.tvOS)
{
EditorGUILayout.PropertyField(m_Use32BitDisplayBuffer, SettingsContent.use32BitDisplayBuffer);
}
EditorGUILayout.PropertyField(m_DisableDepthAndStencilBuffers, SettingsContent.disableDepthAndStencilBuffers);
EditorGUILayout.PropertyField(m_PreserveFramebufferAlpha, SettingsContent.preserveFramebufferAlpha);
}
ShowSharedNote();
}
}
EndSettingsBox();
}
// Converts a GraphicsDeviceType to a string, along with visual modifiers for given target platform
static private string GraphicsDeviceTypeToString(BuildTarget target, GraphicsDeviceType graphicsDeviceType)
{
if (graphicsDeviceType == GraphicsDeviceType.WebGPU)
{
return "WebGPU";
}
else if (target == BuildTarget.WebGL)
{
return "WebGL 2";
}
switch (target)
{
case BuildTarget.StandaloneWindows:
case BuildTarget.StandaloneWindows64:
if (graphicsDeviceType == GraphicsDeviceType.OpenGLCore)
return graphicsDeviceType.ToString() + " (Deprecated)";
break;
}
return graphicsDeviceType.ToString();
}
// Parses a GraphicsDeviceType from a string.
static private GraphicsDeviceType GraphicsDeviceTypeFromString(string graphicsDeviceType)
{
graphicsDeviceType = graphicsDeviceType.Replace(" (Deprecated)", "");
graphicsDeviceType = graphicsDeviceType.Replace(" (Experimental)", "");
if (graphicsDeviceType.Contains("WebGPU")) return GraphicsDeviceType.WebGPU;
if (graphicsDeviceType == "WebGL 2") return GraphicsDeviceType.OpenGLES3;
return (GraphicsDeviceType)Enum.Parse(typeof(GraphicsDeviceType), graphicsDeviceType, true);
}
private void AddGraphicsDeviceMenuSelected(object userData, string[] options, int selected)
{
var target = (BuildTarget)userData;
var apis = PlayerSettings.GetGraphicsAPIs(target);
if (apis == null)
return;
var apiToAdd = GraphicsDeviceTypeFromString(options[selected]);
apis = apis.Append(apiToAdd).ToArray();
PlayerSettings.SetGraphicsAPIs(target, apis);
}
private void AddGraphicsDeviceElement(BuildTarget target, Rect rect, ReorderableList list)
{
GraphicsDeviceType[] availableDevices = PlayerSettings.GetSupportedGraphicsAPIs(target);
if (availableDevices == null || availableDevices.Length == 0)
return;
//As part of OpenGL deprection from MacOS, hide the option of adding OpenGL
if (target == BuildTarget.StandaloneOSX)
{
var availableDeviceList = availableDevices.ToList();
availableDeviceList.Remove(GraphicsDeviceType.OpenGLCore);
availableDevices = availableDeviceList.ToArray();
}
// Gate the display of WebGPU based on the WebGL.enableWebGPU flag or if we are in a source build
if (!PlayerSettings.WebGL.enableWebGPU && !Unsupported.IsSourceBuild())
{
var availableDeviceList = availableDevices.ToList();
availableDeviceList.Remove(GraphicsDeviceType.WebGPU);
availableDevices = availableDeviceList.ToArray();
}
var names = new string[availableDevices.Length];
var enabled = new bool[availableDevices.Length];
for (int i = 0; i < availableDevices.Length; ++i)
{
names[i] = L10n.Tr(GraphicsDeviceTypeToString(target, availableDevices[i]));
enabled[i] = !list.list.Contains(availableDevices[i]);
}
EditorUtility.DisplayCustomMenu(rect, names, enabled, null, AddGraphicsDeviceMenuSelected, target);
}
private bool CanRemoveGraphicsDeviceElement(ReorderableList list)
{
// don't allow removing the last API
return list.list.Count >= 2;
}
private void RemoveGraphicsDeviceElement(BuildTarget target, ReorderableList list)
{
var apis = PlayerSettings.GetGraphicsAPIs(target);
if (apis == null)
return;
// don't allow removing the last API
if (apis.Length < 2)
{
EditorApplication.Beep();
return;
}
var apiList = apis.ToList();
apiList.RemoveAt(list.index);
apis = apiList.ToArray();
ApplyChangedGraphicsAPIList(target, apis, list.index == 0);
}
private void ReorderGraphicsDeviceElement(BuildTarget target, ReorderableList list)
{
var previousAPIs = PlayerSettings.GetGraphicsAPIs(target);
var apiList = (List<GraphicsDeviceType>)list.list;
var apis = apiList.ToArray();
var firstAPIDifferent = (previousAPIs[0] != apis[0]);
ApplyChangedGraphicsAPIList(target, apis, firstAPIDifferent);
}
// these two methods are needed for cases when you want to take some action depending on user choice
// as changing graphics api will call GUIUtility.ExitGUI
private struct ChangeGraphicsApiAction
{
public readonly bool changeList, reloadGfx;
public ChangeGraphicsApiAction(bool doChange, bool doReload) { changeList = doChange; reloadGfx = doReload; }
}
private ChangeGraphicsApiAction CheckApplyGraphicsAPIList(BuildTarget target, bool firstEntryChanged)
{
bool doRestart = false;
// If we're changing the first API for relevant editor, this will cause editor to switch: ask for scene save & confirmation
if (firstEntryChanged && WillEditorUseFirstGraphicsAPI(target))
{
// If we have dirty scenes we need to save or discard changes before we restart editor.
// Otherwise user will get a dialog later on where they can click cancel and put editor in a bad device state.
var dirtyScenes = new List<Scene>();
for (int i = 0; i < EditorSceneManager.sceneCount; ++i)
{
var scene = EditorSceneManager.GetSceneAt(i);
if (scene.isDirty)
dirtyScenes.Add(scene);
}
if (dirtyScenes.Count != 0)
{
var result = EditorUtility.DisplayDialogComplex("Changing editor graphics API",
"You've changed the active graphics API. This requires a restart of the Editor. Do you want to save the Scene when restarting?",
"Save and Restart", "Cancel Changing API", "Discard Changes and Restart");
if (result == 1)
{
doRestart = false; // Cancel was selected
}
else
{
doRestart = true;
if (result == 0) // Save and Restart was selected
{
for (int i = 0; i < dirtyScenes.Count; ++i)
{
var saved = EditorSceneManager.SaveScene(dirtyScenes[i]);
if (saved == false)
{
doRestart = false;
}
}
}
else // Discard Changes and Restart was selected
{
for (int i = 0; i < dirtyScenes.Count; ++i)
EditorSceneManager.ClearSceneDirtiness(dirtyScenes[i]);
}
}
}
else
{
doRestart = EditorUtility.DisplayDialog("Changing editor graphics API",
"You've changed the active graphics API. This requires a restart of the Editor.",
"Restart Editor", "Not now");
}
return new ChangeGraphicsApiAction(doRestart, doRestart);
}
else
{
return new ChangeGraphicsApiAction(true, false);
}
}
private void ApplyChangeGraphicsApiAction(BuildTarget target, GraphicsDeviceType[] apis, ChangeGraphicsApiAction action)
{
if (action.changeList)
PlayerSettings.SetGraphicsAPIs(target, apis);
else
s_GraphicsDeviceLists.Remove(target); // we cancelled the list change, so remove the cached one
if (action.reloadGfx)
{
EditorApplication.RequestCloseAndRelaunchWithCurrentArguments();
GUIUtility.ExitGUI();
}
}
private void ApplyChangedGraphicsAPIList(BuildTarget target, GraphicsDeviceType[] apis, bool firstEntryChanged)
{
ChangeGraphicsApiAction action = CheckApplyGraphicsAPIList(target, firstEntryChanged);
ApplyChangeGraphicsApiAction(target, apis, action);
}
private void DrawGraphicsDeviceElement(BuildTarget target, Rect rect, int index, bool selected, bool focused)
{
var name = GraphicsDeviceTypeToString(target, (GraphicsDeviceType)s_GraphicsDeviceLists[target].list[index]);
GUI.Label(rect, name, EditorStyles.label);
}
private static bool WillEditorUseFirstGraphicsAPI(BuildTarget targetPlatform)
{
return
Application.platform == RuntimePlatform.WindowsEditor && targetPlatform == BuildTarget.StandaloneWindows ||
Application.platform == RuntimePlatform.LinuxEditor && targetPlatform == BuildTarget.StandaloneLinux64 ||
Application.platform == RuntimePlatform.OSXEditor && targetPlatform == BuildTarget.StandaloneOSX;
}
private bool CheckApplyGraphicsJobsModeChange()
{
bool doRestart = false;
// If we have dirty scenes we need to save or discard changes before we restart editor.
// Otherwise user will get a dialog later on where they can click cancel and put editor in a bad device state.
var dirtyScenes = new List<Scene>();
for (int i = 0; i < EditorSceneManager.sceneCount; ++i)
{
var scene = EditorSceneManager.GetSceneAt(i);
if (scene.isDirty)
dirtyScenes.Add(scene);
}
if (dirtyScenes.Count != 0)
{
var result = EditorUtility.DisplayDialogComplex("Changing editor graphics jobs mode",
"You've changed the active graphics jobs mode. This requires a restart of the Editor. Do you want to save the Scene when restarting?",
"Save and Restart", "Cancel Changing API", "Discard Changes and Restart");
if (result == 1)
{
doRestart = false; // Cancel was selected
}
else
{
doRestart = true;
if (result == 0) // Save and Restart was selected
{
for (int i = 0; i < dirtyScenes.Count; ++i)
{
var saved = EditorSceneManager.SaveScene(dirtyScenes[i]);
if (saved == false)
{
doRestart = false;
}
}
}
else // Discard Changes and Restart was selected
{
for (int i = 0; i < dirtyScenes.Count; ++i)
EditorSceneManager.ClearSceneDirtiness(dirtyScenes[i]);
}
}
}
else
{
doRestart = EditorUtility.DisplayDialog("Changing editor graphics jobs mode",
"You've changed the active graphics josb mode. This requires a restart of the Editor.",
"Restart Editor", "Not now");
}
return doRestart;
}
void OpenGLES31OptionsGUI(BuildTargetGroup targetGroup, BuildTarget targetPlatform)
{
// ES3.1 options only applicable on some platforms now
var hasES31Options = (targetGroup == BuildTargetGroup.Android);
if (!hasES31Options)
return;
var apis = PlayerSettings.GetGraphicsAPIs(targetPlatform);
// only available if we include ES3
var hasMinES3 = apis.Contains(GraphicsDeviceType.OpenGLES3);
if (!hasMinES3)
return;
EditorGUILayout.PropertyField(m_RequireES31, SettingsContent.require31);
EditorGUILayout.PropertyField(m_RequireES31AEP, SettingsContent.requireAEP);
EditorGUILayout.PropertyField(m_RequireES32, SettingsContent.require32);
}
void ExclusiveGraphicsAPIsGUI(BuildTarget targetPlatform, string displayTitle)
{
EditorGUI.BeginChangeCheck();
GraphicsDeviceType[] currentDevices = PlayerSettings.GetGraphicsAPIs(targetPlatform);
GraphicsDeviceType[] availableDevices = PlayerSettings.GetSupportedGraphicsAPIs(targetPlatform);
GUIContent[] names = new GUIContent[availableDevices.Length];
for (int i = 0; i < availableDevices.Length; ++i)
{
names[i] = EditorGUIUtility.TrTextContent(L10n.Tr(GraphicsDeviceTypeToString(targetPlatform, availableDevices[i])));
}
GraphicsDeviceType selected = BuildEnumPopup(EditorGUIUtility.TrTextContent(displayTitle), currentDevices[0], availableDevices, names);
if (EditorGUI.EndChangeCheck() && selected != currentDevices[0])
{
Undo.RecordObject(target, SettingsContent.undoChangedGraphicsAPIString);
PlayerSettings.SetGraphicsAPIs(targetPlatform, new GraphicsDeviceType[] { selected });
}
}
void GraphicsAPIsGUIOnePlatform(BuildTargetGroup targetGroup, BuildTarget targetPlatform, string platformTitle)
{
if (isPreset)
return;
GraphicsDeviceType[] availableDevices = PlayerSettings.GetSupportedGraphicsAPIs(targetPlatform);
// if no devices (e.g. no platform module), or we only have one possible choice, then no
// point in having any UI
if (availableDevices == null || availableDevices.Length < 2)
return;
// toggle for automatic API selection
EditorGUI.BeginChangeCheck();
var automatic = PlayerSettings.GetUseDefaultGraphicsAPIs(targetPlatform);
automatic = EditorGUILayout.Toggle(string.Format(L10n.Tr("Auto Graphics API {0}"), (platformTitle ?? string.Empty)), automatic);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, SettingsContent.undoChangedGraphicsAPIString);
PlayerSettings.SetUseDefaultGraphicsAPIs(targetPlatform, automatic);
}
// graphics API list if not automatic
if (!automatic)
{
// note that editor will use first item, when we're in standalone settings
if (WillEditorUseFirstGraphicsAPI(targetPlatform))
{
EditorGUILayout.HelpBox(SettingsContent.recordingInfo.text, MessageType.Info, true);
}
var displayTitle = "Graphics APIs";
if (platformTitle != null)
displayTitle += platformTitle;
if (targetPlatform == BuildTarget.PS5)
{
ExclusiveGraphicsAPIsGUI(targetPlatform, displayTitle);
return;
}
// create reorderable list for this target if needed
if (!s_GraphicsDeviceLists.ContainsKey(targetPlatform))
{
GraphicsDeviceType[] devices = PlayerSettings.GetGraphicsAPIs(targetPlatform);
var devicesList = (devices != null) ? devices.ToList() : new List<GraphicsDeviceType>();
var rlist = new ReorderableList(devicesList, typeof(GraphicsDeviceType), true, true, true, true);
rlist.onAddDropdownCallback = (rect, list) => AddGraphicsDeviceElement(targetPlatform, rect, list);
rlist.onCanRemoveCallback = CanRemoveGraphicsDeviceElement;
rlist.onRemoveCallback = (list) => RemoveGraphicsDeviceElement(targetPlatform, list);
rlist.onReorderCallback = (list) => ReorderGraphicsDeviceElement(targetPlatform, list);
rlist.drawElementCallback = (rect, index, isActive, isFocused) => DrawGraphicsDeviceElement(targetPlatform, rect, index, isActive, isFocused);
rlist.drawHeaderCallback = (rect) => GUI.Label(rect, displayTitle, EditorStyles.label);
rlist.elementHeight = 16;
s_GraphicsDeviceLists.Add(targetPlatform, rlist);
}
if (targetPlatform == BuildTarget.StandaloneOSX && s_GraphicsDeviceLists[BuildTarget.StandaloneOSX].list.Contains(GraphicsDeviceType.OpenGLCore))
{
EditorGUILayout.HelpBox(SettingsContent.appleSiliconOpenGLWarning.text, MessageType.Warning, true);
}
s_GraphicsDeviceLists[targetPlatform].DoLayoutList();
//@TODO: undo
}
// ES3.1 options
OpenGLES31OptionsGUI(targetGroup, targetPlatform);
}
void GraphicsAPIsGUI(BuildTargetGroup targetGroup, BuildTarget target)
{
// "standalone" is a generic group;
// split it into win/mac/linux manually
if (targetGroup == BuildTargetGroup.Standalone)
{
GraphicsAPIsGUIOnePlatform(targetGroup, BuildTarget.StandaloneWindows, " for Windows");
GraphicsAPIsGUIOnePlatform(targetGroup, BuildTarget.StandaloneOSX, " for Mac");
GraphicsAPIsGUIOnePlatform(targetGroup, BuildTarget.StandaloneLinux64, " for Linux");
}
else
{
GraphicsAPIsGUIOnePlatform(targetGroup, target, null);
}
}
// Contains information about color gamuts supported by each platform.
// If platform group is not in the dictionary, then it's assumed it supports only sRGB.
// Color gamut player setting is not displayed for such platforms.
//
// This information might be useful for users that use the color gamut APIs,
// we could expose it somehow
private static Dictionary<BuildTargetGroup, List<ColorGamut>> s_SupportedColorGamuts =
new Dictionary<BuildTargetGroup, List<ColorGamut>>
{
{ BuildTargetGroup.Standalone, new List<ColorGamut> { ColorGamut.sRGB, ColorGamut.DisplayP3 } },
{ BuildTargetGroup.iOS, new List<ColorGamut> { ColorGamut.sRGB, ColorGamut.DisplayP3 } },
{ BuildTargetGroup.tvOS, new List<ColorGamut> { ColorGamut.sRGB, ColorGamut.DisplayP3 } },
{ BuildTargetGroup.VisionOS, new List<ColorGamut> { ColorGamut.sRGB, ColorGamut.DisplayP3 } },
{ BuildTargetGroup.Android, new List<ColorGamut> {ColorGamut.sRGB, ColorGamut.DisplayP3 } }
};
private static bool IsColorGamutSupportedOnTargetGroup(BuildTargetGroup targetGroup, ColorGamut gamut)
{
if (gamut == ColorGamut.sRGB)
return true;
if (s_SupportedColorGamuts.ContainsKey(targetGroup) && s_SupportedColorGamuts[targetGroup].Contains(gamut))
return true;
return false;
}
private static string GetColorGamutDisplayString(BuildTargetGroup targetGroup, ColorGamut gamut)
{
string name = gamut.ToString();
if (!IsColorGamutSupportedOnTargetGroup(targetGroup, gamut))
name += L10n.Tr(" (not supported on this platform)");
return name;
}
private void AddColorGamutElement(BuildTargetGroup targetGroup, Rect rect, ReorderableList list)
{
var availableColorGamuts = new ColorGamut[]
{
// Enable the gamuts when at least one platform supports them
ColorGamut.sRGB,
//ColorGamut.Rec709,
//ColorGamut.Rec2020,
ColorGamut.DisplayP3,
//ColorGamut.HDR10,
//ColorGamut.DolbyHDR
};
var names = new string[availableColorGamuts.Length];
var enabled = new bool[availableColorGamuts.Length];
for (int i = 0; i < availableColorGamuts.Length; ++i)
{
names[i] = GetColorGamutDisplayString(targetGroup, availableColorGamuts[i]);
enabled[i] = !list.list.Contains(availableColorGamuts[i]);
}
EditorUtility.DisplayCustomMenu(rect, names, enabled, null, AddColorGamutMenuSelected, availableColorGamuts);
}
private void AddColorGamutMenuSelected(object userData, string[] options, int selected)
{
var colorGamuts = (ColorGamut[])userData;
var colorGamutList = PlayerSettings.GetColorGamuts().ToList();
colorGamutList.Add(colorGamuts[selected]);
PlayerSettings.SetColorGamuts(colorGamutList.ToArray());
}
private bool CanRemoveColorGamutElement(ReorderableList list)
{
// don't allow removing the sRGB
var colorGamutList = (List<ColorGamut>)list.list;
return colorGamutList[list.index] != ColorGamut.sRGB;
}
private void RemoveColorGamutElement(ReorderableList list)
{
var colorGamutList = PlayerSettings.GetColorGamuts().ToList();
// don't allow removing the last ColorGamut
if (colorGamutList.Count < 2)
{
EditorApplication.Beep();
return;
}
colorGamutList.RemoveAt(list.index);
PlayerSettings.SetColorGamuts(colorGamutList.ToArray());
}
private void ReorderColorGamutElement(ReorderableList list)
{
var colorGamutList = (List<ColorGamut>)list.list;
PlayerSettings.SetColorGamuts(colorGamutList.ToArray());
}
private void DrawColorGamutElement(BuildTargetGroup targetGroup, Rect rect, int index, bool selected, bool focused)
{
var colorGamut = s_ColorGamutList.list[index];
GUI.Label(rect, GetColorGamutDisplayString(targetGroup, (ColorGamut)colorGamut), EditorStyles.label);
}
void ColorGamutGUI(BuildTargetGroup targetGroup)
{
if (isPreset)
return;
if (!s_SupportedColorGamuts.ContainsKey(targetGroup))
return;
if (s_ColorGamutList == null)
{
ColorGamut[] colorGamuts = PlayerSettings.GetColorGamuts();
var colorGamutsList = (colorGamuts != null) ? colorGamuts.ToList() : new List<ColorGamut>();
var rlist = new ReorderableList(colorGamutsList, typeof(ColorGamut), true, true, true, true);
rlist.onCanRemoveCallback = CanRemoveColorGamutElement;
rlist.onRemoveCallback = RemoveColorGamutElement;
rlist.onReorderCallback = ReorderColorGamutElement;
rlist.elementHeight = 16;
s_ColorGamutList = rlist;
}
// On standalone inspector mention that the setting applies only to Mac
// (Temporarily until other standalones support this setting)
GUIContent header = targetGroup == BuildTargetGroup.Standalone ? SettingsContent.colorGamutForMac : SettingsContent.colorGamut;
s_ColorGamutList.drawHeaderCallback = (rect) =>
GUI.Label(rect, header, EditorStyles.label);
// we want to change the displayed text per platform, to indicate unsupported gamuts
s_ColorGamutList.onAddDropdownCallback = (rect, list) =>
AddColorGamutElement(targetGroup, rect, list);
s_ColorGamutList.drawElementCallback = (rect, index, selected, focused) =>
DrawColorGamutElement(targetGroup, rect, index, selected, focused);
s_ColorGamutList.DoLayoutList();
}
public void DebugAndCrashReportingGUI(BuildPlatform platform,
ISettingEditorExtension settingsExtension, int sectionIndex = 3)
{
if (platform.namedBuildTarget != NamedBuildTarget.iOS && platform.namedBuildTarget != NamedBuildTarget.tvOS)
return;
if (BeginSettingsBox(sectionIndex, SettingsContent.debuggingCrashReportingTitle))
{
// PLEASE DO NOT COPY SETTINGS TO APPEAR MULTIPLE PLACES IN THE CODE! See top of file for more info.
{
// Debugging
GUILayout.Label(SettingsContent.debuggingTitle, EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_EnableInternalProfiler, SettingsContent.enableInternalProfiler);
EditorGUILayout.Space();
}
{
// Crash reporting
GUILayout.Label(SettingsContent.crashReportingTitle, EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_ActionOnDotNetUnhandledException, SettingsContent.actionOnDotNetUnhandledException);
EditorGUILayout.PropertyField(m_LogObjCUncaughtExceptions, SettingsContent.logObjCUncaughtExceptions);
GUIContent crashReportApiContent = SettingsContent.enableCrashReportAPI;
bool apiFieldDisabled = false;
if (UnityEditor.CrashReporting.CrashReportingSettings.enabled)
{
// CrashReport API must be enabled if cloud crash reporting is enabled,
// so don't let them change the value of the checkbox
crashReportApiContent = new GUIContent(crashReportApiContent); // Create a copy so we don't alter the style definition
apiFieldDisabled = true;
crashReportApiContent.tooltip = "CrashReport API must be enabled for Performance Reporting service.";
m_EnableCrashReportAPI.boolValue = true;
}
EditorGUI.BeginDisabledGroup(apiFieldDisabled);
EditorGUILayout.PropertyField(m_EnableCrashReportAPI, crashReportApiContent);
EditorGUI.EndDisabledGroup();
EditorGUILayout.Space();
}
}
EndSettingsBox();
}
public static void BuildDisabledEnumPopup(GUIContent selected, GUIContent uiString)
{
using (new EditorGUI.DisabledScope(true))
{
EditorGUI.Popup(EditorGUILayout.GetControlRect(true), uiString, 0, new GUIContent[] { selected });
}
}
public static T BuildEnumPopup<T>(SerializedProperty prop, GUIContent uiString, T[] options, GUIContent[] optionNames)
{
T val = (T)(object)prop.intValue;
T newVal = BuildEnumPopup(uiString, val, options, optionNames);
// Update property if the popup value has changed
if (!newVal.Equals(val))
{
prop.intValue = (int)(object)newVal;
prop.serializedObject.ApplyModifiedProperties();
}
return newVal;
}
public static T BuildEnumPopup<T>(GUIContent uiString, T selected, T[] options, GUIContent[] optionNames)
{
// Display dropdown
int idx = 0; // pick the first property when not found
for (int i = 1; i < options.Length; ++i)
{
if (selected.Equals(options[i]))
{
idx = i;
break;
}
}
int newIdx = EditorGUILayout.Popup(uiString, idx, optionNames);
return options[newIdx];
}
public static void EnumPropertyField<T>(SerializedProperty property, GUIContent name) where T : Enum
{
using (var horizontal = new EditorGUILayout.HorizontalScope())
{
using (new EditorGUI.PropertyScope(horizontal.rect, GUIContent.none, property))
{
var values = (T[])Enum.GetValues(typeof(T));
var valueNames = Enum.GetNames(typeof(T)).Select(e => new GUIContent(e)).ToArray();
PlayerSettingsEditor.BuildEnumPopup(property, name, values, valueNames);
}
}
}
public void OtherSectionGUI(BuildPlatform platform, ISettingEditorExtension settingsExtension, int sectionIndex = 4)
{
if (BeginSettingsBox(sectionIndex, SettingsContent.otherSettingsTitle))
{
// PLEASE DO NOT COPY SETTINGS TO APPEAR MULTIPLE PLACES IN THE CODE! See top of file for more info.
if (platform.namedBuildTarget != NamedBuildTarget.Server)
{
OtherSectionRenderingGUI(platform, settingsExtension);
OtherSectionVulkanSettingsGUI(platform, settingsExtension);
OtherSectionIdentificationGUI(platform, settingsExtension);
}
OtherSectionConfigurationGUI(platform, settingsExtension);
OtherSectionShaderSettingsGUI(platform);
OtherSectionScriptCompilationGUI(platform);
OtherSectionOptimizationGUI(platform);
OtherSectionLoggingGUI();
OtherSectionLegacyGUI(platform);
if (platform.namedBuildTarget == NamedBuildTarget.Standalone || platform.namedBuildTarget == NamedBuildTarget.Server)
{
OtherSectionCaptureLogsGUI(platform.namedBuildTarget);
}
ShowSharedNote();
}
EndSettingsBox();
}
public void PlayerSettingsAttributeSectionsGUI(NamedBuildTarget namedBuildTarget, ISettingEditorExtension settingsExtension, ref int sectionIndex)
{
foreach (var box in m_boxes)
{
if (box.TargetName == namedBuildTarget.TargetName)
{
if (BeginSettingsBox(sectionIndex, box.title))
{
box.mi.Invoke(null, null);
}
EndSettingsBox();
sectionIndex++;
}
}
}
private void OtherSectionShaderSettingsGUI(BuildPlatform platform)
{
GUILayout.Label(SettingsContent.shaderSectionTitle, EditorStyles.boldLabel);
using (new EditorGUI.DisabledScope(EditorApplication.isPlaying || EditorApplication.isCompiling))
{
EditorGUI.BeginChangeCheck();
ShaderPrecisionModel currShaderPrecisionModel = PlayerSettings.GetShaderPrecisionModel();
ShaderPrecisionModel[] shaderPrecisionModelValues = { ShaderPrecisionModel.PlatformDefault, ShaderPrecisionModel.Unified };
ShaderPrecisionModel newShaderPrecisionModel = BuildEnumPopup(SettingsContent.shaderPrecisionModel, currShaderPrecisionModel, shaderPrecisionModelValues, SettingsContent.shaderPrecisionModelOptions);
if (EditorGUI.EndChangeCheck() && currShaderPrecisionModel != newShaderPrecisionModel)
{
PlayerSettings.SetShaderPrecisionModel(newShaderPrecisionModel);
}
}
EditorGUILayout.PropertyField(m_StrictShaderVariantMatching, SettingsContent.strictShaderVariantMatching);
EditorGUILayout.PropertyField(m_KeepLoadedShadersAlive, SettingsContent.keepLoadedShadersAlive);
GUILayout.Label(SettingsContent.shaderVariantLoadingTitle, EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
int defaultChunkSize = PlayerSettings.GetDefaultShaderChunkSizeInMB();
int newDefaultChunkSize = EditorGUILayout.IntField(SettingsContent.defaultShaderChunkSize, defaultChunkSize);
if (EditorGUI.EndChangeCheck() && newDefaultChunkSize > 0 && newDefaultChunkSize != defaultChunkSize)
{
Undo.RecordObject(target, SettingsContent.undoChangedDefaultShaderChunkSizeString);
PlayerSettings.SetDefaultShaderChunkSizeInMB(newDefaultChunkSize);
}
EditorGUI.BeginChangeCheck();
int defaultChunkCount = PlayerSettings.GetDefaultShaderChunkCount();
int newDefaultChunkCount = EditorGUILayout.IntField(SettingsContent.defaultShaderChunkCount, defaultChunkCount);
if (EditorGUI.EndChangeCheck() && newDefaultChunkCount >= 0 && newDefaultChunkCount != defaultChunkCount)
{
Undo.RecordObject(target, SettingsContent.undoChangedDefaultShaderChunkCountString);
PlayerSettings.SetDefaultShaderChunkCount(newDefaultChunkCount);
}
bool oldOverride = PlayerSettings.GetOverrideShaderChunkSettingsForPlatform(platform.defaultTarget);
bool newOverride = EditorGUILayout.Toggle(SettingsContent.overrideDefaultChunkSettings, oldOverride);
if (oldOverride != newOverride)
PlayerSettings.SetOverrideShaderChunkSettingsForPlatform(platform.defaultTarget, newOverride);
if (newOverride)
{
int currentChunkSize = PlayerSettings.GetShaderChunkSizeInMBForPlatform(platform.defaultTarget);
int newChunkSize = EditorGUILayout.IntField(SettingsContent.platformShaderChunkSize, currentChunkSize);
if (EditorGUI.EndChangeCheck() && newChunkSize > 0 && newChunkSize != currentChunkSize)
{
Undo.RecordObject(target, SettingsContent.undoChangedPlatformShaderChunkSizeString);
PlayerSettings.SetShaderChunkSizeInMBForPlatform(platform.defaultTarget, newChunkSize);
}
EditorGUI.BeginChangeCheck();
int currentChunkCount = PlayerSettings.GetShaderChunkCountForPlatform(platform.defaultTarget);
int newChunkCount = EditorGUILayout.IntField(SettingsContent.platformShaderChunkCount, currentChunkCount);
if (EditorGUI.EndChangeCheck() && newChunkCount >= 0 && newChunkCount != currentChunkCount)
{
Undo.RecordObject(target, SettingsContent.undoChangedPlatformShaderChunkCountString);
PlayerSettings.SetShaderChunkCountForPlatform(platform.defaultTarget, newChunkCount);
}
}
}
private void OtherSectionRenderingGUI(BuildPlatform platform, ISettingEditorExtension settingsExtension)
{
// Rendering related settings
GUILayout.Label(SettingsContent.renderingTitle, EditorStyles.boldLabel);
// Color space (supported by all non deprecated platforms)
using (new EditorGUI.DisabledScope(EditorApplication.isPlaying)) // switching color spaces in play mode is not supported
{
EditorGUI.BeginChangeCheck();
int selectedValue = m_ActiveColorSpace.enumValueIndex;
EditorGUILayout.PropertyField(m_ActiveColorSpace, SettingsContent.activeColorSpace);
if (EditorGUI.EndChangeCheck())
{
if (m_ActiveColorSpace.enumValueIndex != selectedValue && EditorUtility.DisplayDialog("Changing Color Space", SettingsContent.changeColorSpaceString, $"Change to {(ColorSpace)m_ActiveColorSpace.enumValueIndex}", "Cancel"))
{
serializedObject.ApplyModifiedProperties();
}
else m_ActiveColorSpace.enumValueIndex = selectedValue;
GUIUtility.ExitGUI(); // Fixes case 690421
}
}
using (new EditorGUI.DisabledScope(EditorApplication.isPlaying))
{
if (BuildTargetDiscovery.TryGetBuildTarget(platform.defaultTarget, out IBuildTarget iBuildTarget) && (iBuildTarget.GraphicsPlatformProperties?.HasUnsupportedMSAAFallback ?? false))
EditorGUILayout.PropertyField(m_UnsupportedMSAAFallback, SettingsContent.unsupportedMSAAFallback);
}
// Special cases for some platform with limitations regarding linear colorspace
if ((PlayerSettings.colorSpace == ColorSpace.Linear) &&
(null != settingsExtension) && settingsExtension.SupportsForcedSrgbBlit())
{
EditorGUILayout.PropertyField(m_ForceSRGBBlit, SettingsContent.forceSRGBBlit);
}
// Graphics APIs
using (new EditorGUI.DisabledScope(EditorApplication.isPlaying))
{
GraphicsAPIsGUI(platform.namedBuildTarget.ToBuildTargetGroup(), platform.defaultTarget);
}
// Output color spaces
ColorGamutGUI(platform.namedBuildTarget.ToBuildTargetGroup());
// What we call "Metal Validation" is a random bunch of extra checks we do in editor in metal code
if (Application.platform == RuntimePlatform.OSXEditor && BuildTargetDiscovery.BuildTargetSupportsRenderer(platform, GraphicsDeviceType.Metal))
m_MetalAPIValidation.boolValue = EditorGUILayout.Toggle(SettingsContent.metalAPIValidation, m_MetalAPIValidation.boolValue);
// Metal
if (BuildTargetDiscovery.BuildTargetSupportsRenderer(platform, GraphicsDeviceType.Metal))
{
EditorGUILayout.PropertyField(m_MetalFramebufferOnly, SettingsContent.metalFramebufferOnly);
if (platform.namedBuildTarget == NamedBuildTarget.iOS || platform.namedBuildTarget == NamedBuildTarget.tvOS)
EditorGUILayout.PropertyField(m_MetalForceHardShadows, SettingsContent.metalForceHardShadows);
int[] memorylessModeValues = { 0, 1, 2 };
BuildEnumPopup(m_FramebufferDepthMemorylessMode, SettingsContent.framebufferDepthMemorylessMode, memorylessModeValues, SettingsContent.memorylessModeNames);
}
if (!isPreset)
{
// Multithreaded rendering
if (settingsExtension != null && settingsExtension.SupportsMultithreadedRendering())
settingsExtension.MultithreadedRenderingGUI(platform.namedBuildTarget);
// Batching section
{
int staticBatching, dynamicBatching;
bool staticBatchingSupported = true;
bool dynamicBatchingSupported = true;
if (settingsExtension != null)
{
staticBatchingSupported = settingsExtension.SupportsStaticBatching();
dynamicBatchingSupported = settingsExtension.SupportsDynamicBatching();
}
PlayerSettings.GetBatchingForPlatform(platform.defaultTarget, out staticBatching, out dynamicBatching);
bool reset = false;
if (staticBatchingSupported == false && staticBatching == 1)
{
staticBatching = 0;
reset = true;
}
if (dynamicBatchingSupported == false && dynamicBatching == 1)
{
dynamicBatching = 0;
reset = true;
}
if (reset)
{
PlayerSettings.SetBatchingForPlatform(platform.defaultTarget, staticBatching, dynamicBatching);
}
EditorGUI.BeginChangeCheck();
using (new EditorGUI.DisabledScope(!staticBatchingSupported))
{
if (GUI.enabled)
staticBatching = EditorGUILayout.Toggle(SettingsContent.staticBatching, staticBatching != 0) ? 1 : 0;
else
EditorGUILayout.Toggle(SettingsContent.staticBatching, false);
}
if (GraphicsSettings.currentRenderPipeline == null)
{
using (new EditorGUI.DisabledScope(!dynamicBatchingSupported))
{
dynamicBatching = EditorGUILayout.Toggle(SettingsContent.dynamicBatching, dynamicBatching != 0) ? 1 : 0;
}
}
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, SettingsContent.undoChangedBatchingString);
PlayerSettings.SetBatchingForPlatform(platform.defaultTarget, staticBatching, dynamicBatching);
}
}
int spriteVertexBatchingThreshold = PlayerSettings.spriteBatchVertexThreshold;
EditorGUI.BeginChangeCheck();
spriteVertexBatchingThreshold = EditorGUILayout.IntSlider(SettingsContent.spriteBatchingVertexThreshold, spriteVertexBatchingThreshold, 300, 8000);
if (EditorGUI.EndChangeCheck())
PlayerSettings.spriteBatchVertexThreshold = spriteVertexBatchingThreshold;
}
bool hdrDisplaySupported = false;
bool gfxJobModesSupported = false;
bool hdrEncodingSupportedByPlatform = (platform.namedBuildTarget.ToBuildTargetGroup() == BuildTargetGroup.Standalone || platform.namedBuildTarget == NamedBuildTarget.WebGL);
if (settingsExtension != null)
{
hdrDisplaySupported = settingsExtension.SupportsHighDynamicRangeDisplays();
gfxJobModesSupported = settingsExtension.SupportsGfxJobModes();
hdrEncodingSupportedByPlatform = hdrEncodingSupportedByPlatform || settingsExtension.SupportsCustomLightmapEncoding();
}
else
{
if (platform.namedBuildTarget.ToBuildTargetGroup() == BuildTargetGroup.Standalone)
{
GraphicsDeviceType[] gfxAPIs = PlayerSettings.GetGraphicsAPIs(platform.defaultTarget);
hdrDisplaySupported = gfxAPIs[0] == GraphicsDeviceType.Direct3D11 || gfxAPIs[0] == GraphicsDeviceType.Direct3D12 || gfxAPIs[0] == GraphicsDeviceType.Vulkan || gfxAPIs[0] == GraphicsDeviceType.Metal;
}
}
if (platform.namedBuildTarget.ToBuildTargetGroup() == BuildTargetGroup.Standalone)
{
GraphicsDeviceType[] gfxAPIs = PlayerSettings.GetGraphicsAPIs(platform.defaultTarget);
gfxJobModesSupported = (gfxAPIs[0] == GraphicsDeviceType.Direct3D12) || (gfxAPIs[0] == GraphicsDeviceType.Vulkan);
}
else if (platform.namedBuildTarget.ToBuildTargetGroup() == BuildTargetGroup.Android)
{
GraphicsDeviceType[] gfxAPIs = PlayerSettings.GetGraphicsAPIs(platform.defaultTarget);
gfxJobModesSupported = (gfxAPIs[0] == GraphicsDeviceType.Vulkan);
}
// GPU Skinning toggle (only show on relevant platforms)
if (!BuildTargetDiscovery.PlatformHasFlag(platform.defaultTarget, TargetAttributes.GPUSkinningNotSupported))
{
bool platformSupportsBatching = false;
GraphicsDeviceType[] gfxAPIs = PlayerSettings.GetGraphicsAPIs(platform.defaultTarget);
foreach (GraphicsDeviceType api in gfxAPIs)
{
if (api == GraphicsDeviceType.Switch ||
api == GraphicsDeviceType.PlayStation5 ||
api == GraphicsDeviceType.PlayStation5NGGC ||
api == GraphicsDeviceType.Direct3D11 ||
api == GraphicsDeviceType.Metal ||
api == GraphicsDeviceType.Vulkan ||
api == GraphicsDeviceType.OpenGLES3)
{
platformSupportsBatching = true;
break;
}
// TODO: GraphicsDeviceType.OpenGLCore does not have GPU skinning enabled yet
}
if (platformSupportsBatching)
{
MeshDeformation currentDeformation = (MeshDeformation)m_MeshDeformation.intValue;
EditorGUI.BeginChangeCheck();
MeshDeformation newDeformation = BuildEnumPopup(SettingsContent.skinOnGPU, currentDeformation, m_MeshDeformations, SettingsContent.meshDeformations);
if (EditorGUI.EndChangeCheck())
{
m_SkinOnGPU.boolValue = newDeformation != MeshDeformation.CPU;
m_MeshDeformation.intValue = (int)newDeformation;
serializedObject.ApplyModifiedProperties();
ShaderUtil.RecreateSkinnedMeshResources();
}
}
else
{
// Use the original checkbox UI but preserve underlying batching mode whenever possible.
// We need to do this because gpuSkinning/meshDeformation are properties which are shared between all platforms
// and if the user sets gpuSkinning mode to "enabled", we actually want to preserve "batchEnabled" if it was set for other platforms.
// Platforms that do not support batching but have meshDeformation == GPUBatched just silently use original non-batched code.
// WebGPU is kept behind a settings gate for now while it's in development.
if (platform.namedBuildTarget != NamedBuildTarget.WebGL || PlayerSettings.WebGL.enableWebGPU)
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_SkinOnGPU, SettingsContent.skinOnGPU);
if (EditorGUI.EndChangeCheck())
{
// Preserve the value of m_MeshDeformation when possible.
if (!m_SkinOnGPU.boolValue)
m_MeshDeformation.intValue = (int)MeshDeformation.CPU;
else
m_MeshDeformation.intValue = m_MeshDeformation.intValue != (int)MeshDeformation.CPU ? m_MeshDeformation.intValue : (int)MeshDeformation.GPUBatched;
serializedObject.ApplyModifiedProperties();
ShaderUtil.RecreateSkinnedMeshResources();
}
}
}
}
bool graphicsJobsOptionEnabled = true;
bool graphicsJobs = PlayerSettings.GetGraphicsJobsForPlatform(platform.defaultTarget);
bool newGraphicsJobs = graphicsJobs;
if (platform.namedBuildTarget == NamedBuildTarget.XboxOne)
{
// on XBoxOne, we only have kGfxJobModeNative active for DX12 API and kGfxJobModeLegacy for the DX11 API
// no need for a drop down popup for XBoxOne
// also if XboxOneD3D12 is selected as GraphicsAPI, then we want to set graphics jobs and disable the user option
GraphicsDeviceType[] gfxAPIs = PlayerSettings.GetGraphicsAPIs(platform.defaultTarget);
GraphicsJobMode newGfxJobMode = GraphicsJobMode.Legacy;
if (gfxAPIs[0] == GraphicsDeviceType.XboxOneD3D12)
{
newGfxJobMode = GraphicsJobMode.Split;
if (graphicsJobs == false)
{
PlayerSettings.SetGraphicsJobsForPlatform(platform.defaultTarget, true);
graphicsJobs = true;
newGraphicsJobs = true;
}
}
PlayerSettings.SetGraphicsJobModeForPlatform(platform.defaultTarget, newGfxJobMode);
PlayerSettings.SetGraphicsThreadingModeForPlatform(platform.defaultTarget, GfxThreadingMode.SplitJobs);
}
else if (platform.namedBuildTarget == NamedBuildTarget.PS5)
{
// On PS5NGGC, we always have graphics jobs enabled so we disable the option in that case
GraphicsDeviceType[] gfxAPIs = PlayerSettings.GetGraphicsAPIs(platform.defaultTarget);
if (gfxAPIs[0] == GraphicsDeviceType.PlayStation5NGGC)
{
graphicsJobsOptionEnabled = false;
if (graphicsJobs == false)
{
PlayerSettings.SetGraphicsJobsForPlatform(platform.defaultTarget, true);
graphicsJobs = true;
newGraphicsJobs = true;
}
}
}
if (!isPreset)
{
EditorGUI.BeginChangeCheck();
GUIContent graphicsJobsGUI = SettingsContent.graphicsJobsNonExperimental;
if (BuildTargetDiscovery.TryGetBuildTarget(platform.defaultTarget, out IBuildTarget iBuildTarget) && (iBuildTarget.GraphicsPlatformProperties?.AreGraphicsJobsExperimental ?? false))
graphicsJobsGUI = SettingsContent.graphicsJobsExperimental;
using (new EditorGUI.DisabledScope(!graphicsJobsOptionEnabled))
{
if (GUI.enabled)
{
newGraphicsJobs = EditorGUILayout.Toggle(graphicsJobsGUI, graphicsJobs);
}
else
{
EditorGUILayout.Toggle(graphicsJobsGUI, graphicsJobs);
}
}
if (EditorGUI.EndChangeCheck() && (newGraphicsJobs != graphicsJobs))
{
Undo.RecordObject(target, SettingsContent.undoChangedGraphicsJobsString);
PlayerSettings.SetGraphicsJobsForPlatform(platform.defaultTarget, newGraphicsJobs);
bool restartEditor = CheckApplyGraphicsJobsModeChange();
if (restartEditor)
{
EditorApplication.RequestCloseAndRelaunchWithCurrentArguments();
GUIUtility.ExitGUI();
}
}
}
if (gfxJobModesSupported && newGraphicsJobs)
{
// For a platform extension to support a gfx job mode, it means it wouldn't modify it. So we check if it's the same after adjustments.
var checkGfxJobModeSupport = (Enum value) => { return settingsExtension != null ? settingsExtension.AdjustGfxJobMode((GraphicsJobMode)value) == (GraphicsJobMode)value : true; };
EditorGUI.BeginChangeCheck();
GraphicsJobMode currGfxJobMode = PlayerSettings.GetGraphicsJobModeForPlatform(platform.defaultTarget);
GraphicsJobMode newGfxJobMode = (GraphicsJobMode)EditorGUILayout.EnumPopup(SettingsContent.graphicsJobsMode, currGfxJobMode, checkGfxJobModeSupport, false);
if (EditorGUI.EndChangeCheck() && (newGfxJobMode != currGfxJobMode))
{
Undo.RecordObject(target, SettingsContent.undoChangedGraphicsJobModeString);
}
GraphicsJobMode fallbackGfxJobMode = settingsExtension != null ? settingsExtension.AdjustGfxJobMode(currGfxJobMode) : currGfxJobMode;
// If we changed other settings and the selected gfx job mode is suddently not supported, we fallback to what the platform settings extension wants
if (fallbackGfxJobMode != currGfxJobMode)
{
newGfxJobMode = fallbackGfxJobMode;
}
// Finally we apply the change of gfx job mode
if (newGfxJobMode != currGfxJobMode)
{
PlayerSettings.SetGraphicsJobModeForPlatform(platform.defaultTarget, newGfxJobMode);
if(newGfxJobMode == GraphicsJobMode.Native)
PlayerSettings.SetGraphicsThreadingModeForPlatform(platform.defaultTarget, GfxThreadingMode.ClientWorkerNativeJobs);
else if (newGfxJobMode == GraphicsJobMode.Legacy)
PlayerSettings.SetGraphicsThreadingModeForPlatform(platform.defaultTarget, GfxThreadingMode.ClientWorkerJobs);
else if (newGfxJobMode == GraphicsJobMode.Split)
PlayerSettings.SetGraphicsThreadingModeForPlatform(platform.defaultTarget, GfxThreadingMode.SplitJobs);
bool restartEditor = CheckApplyGraphicsJobsModeChange();
if (restartEditor)
{
EditorApplication.RequestCloseAndRelaunchWithCurrentArguments();
GUIUtility.ExitGUI();
}
}
}
if (settingsExtension != null)
{
using (new EditorGUI.DisabledScope(EditorApplication.isPlaying))
{
settingsExtension.RenderingSectionGUI();
}
}
if ((settingsExtension != null && settingsExtension.SupportsCustomNormalMapEncoding()) && !isPreset)
{
using (new EditorGUI.DisabledScope(EditorApplication.isPlaying || Lightmapping.isRunning))
{
EditorGUI.BeginChangeCheck();
NormalMapEncoding oldEncoding = PlayerSettings.GetNormalMapEncoding(platform.namedBuildTarget);
NormalMapEncoding[] encodingValues = { NormalMapEncoding.XYZ, NormalMapEncoding.DXT5nm };
NormalMapEncoding newEncoding = BuildEnumPopup(SettingsContent.normalMapEncodingLabel, oldEncoding, encodingValues, SettingsContent.normalMapEncodingNames);
if (EditorGUI.EndChangeCheck() && newEncoding != oldEncoding)
{
PlayerSettings.SetNormalMapEncoding(platform.namedBuildTarget, newEncoding);
serializedObject.ApplyModifiedProperties();
GUIUtility.ExitGUI();
}
}
}
// Show Lightmap Encoding and HDR Cubemap Encoding quality options
if (hdrEncodingSupportedByPlatform && !isPreset)
{
using (new EditorGUI.DisabledScope(EditorApplication.isPlaying || Lightmapping.isRunning))
{
{
EditorGUI.BeginChangeCheck();
LightmapEncodingQuality encodingQuality = PlayerSettings.GetLightmapEncodingQualityForPlatform(platform.defaultTarget);
LightmapEncodingQuality[] lightmapEncodingValues = { LightmapEncodingQuality.Low, LightmapEncodingQuality.Normal, LightmapEncodingQuality.High };
LightmapEncodingQuality newEncodingQuality = BuildEnumPopup(SettingsContent.lightmapEncodingLabel, encodingQuality, lightmapEncodingValues, SettingsContent.lightmapEncodingNames);
if (EditorGUI.EndChangeCheck() && encodingQuality != newEncodingQuality)
{
PlayerSettings.SetLightmapEncodingQualityForPlatform(platform.defaultTarget, newEncodingQuality);
Lightmapping.OnUpdateLightmapEncoding(platform.namedBuildTarget.ToBuildTargetGroup());
serializedObject.ApplyModifiedProperties();
GUIUtility.ExitGUI();
}
}
{
EditorGUI.BeginChangeCheck();
HDRCubemapEncodingQuality encodingQuality = PlayerSettings.GetHDRCubemapEncodingQualityForPlatform(platform.defaultTarget);
HDRCubemapEncodingQuality[] hdrCubemapProbeEncodingValues = { HDRCubemapEncodingQuality.Low, HDRCubemapEncodingQuality.Normal, HDRCubemapEncodingQuality.High };
HDRCubemapEncodingQuality newEncodingQuality = BuildEnumPopup(SettingsContent.hdrCubemapEncodingLabel, encodingQuality, hdrCubemapProbeEncodingValues, SettingsContent.hdrCubemapEncodingNames);
if (EditorGUI.EndChangeCheck() && encodingQuality != newEncodingQuality)
{
PlayerSettings.SetHDRCubemapEncodingQualityForPlatform(platform.defaultTarget, newEncodingQuality);
Lightmapping.OnUpdateHDRCubemapEncoding(platform.namedBuildTarget.ToBuildTargetGroup());
serializedObject.ApplyModifiedProperties();
GUIUtility.ExitGUI();
}
}
}
}
if (!isPreset)
{
// Light map settings
using (new EditorGUI.DisabledScope(EditorApplication.isPlaying || Lightmapping.isRunning))
{
bool streamingEnabled = PlayerSettings.GetLightmapStreamingEnabledForPlatformGroup(platform.namedBuildTarget.ToBuildTargetGroup());
int streamingPriority = PlayerSettings.GetLightmapStreamingPriorityForPlatformGroup(platform.namedBuildTarget.ToBuildTargetGroup());
EditorGUI.BeginChangeCheck();
streamingEnabled = EditorGUILayout.Toggle(SettingsContent.lightmapStreamingEnabled, streamingEnabled);
if (streamingEnabled)
{
EditorGUI.indentLevel++;
streamingPriority = EditorGUILayout.DelayedIntField(SettingsContent.lightmapStreamingPriority, streamingPriority);
streamingPriority = Math.Clamp(streamingPriority, Texture2D.streamingMipmapsPriorityMin, Texture2D.streamingMipmapsPriorityMax);
EditorGUI.indentLevel--;
}
if (EditorGUI.EndChangeCheck())
{
PlayerSettings.SetLightmapStreamingEnabledForPlatformGroup(platform.namedBuildTarget.ToBuildTargetGroup(), streamingEnabled);
PlayerSettings.SetLightmapStreamingPriorityForPlatformGroup(platform.namedBuildTarget.ToBuildTargetGroup(), streamingPriority);
Lightmapping.OnUpdateLightmapStreaming(platform.namedBuildTarget.ToBuildTargetGroup());
serializedObject.ApplyModifiedProperties();
GUIUtility.ExitGUI();
}
}
// Tickbox for Frame Timing Stats.
if (platform.namedBuildTarget.ToBuildTargetGroup() == BuildTargetGroup.Standalone || platform.namedBuildTarget == NamedBuildTarget.WindowsStoreApps || platform.namedBuildTarget == NamedBuildTarget.WebGL || (settingsExtension != null && settingsExtension.SupportsFrameTimingStatistics()))
{
PlayerSettings.enableFrameTimingStats = EditorGUILayout.Toggle(SettingsContent.enableFrameTimingStats, PlayerSettings.enableFrameTimingStats);
if (PlayerSettings.enableFrameTimingStats)
{
EditorGUILayout.HelpBox(SettingsContent.openGLFrameTimingStatsOnGPURecordersOffInfo.text, MessageType.Info);
}
}
// Tickbox for OpenGL-only option to toggle Profiler GPU Recorders.
if (platform.namedBuildTarget == NamedBuildTarget.Standalone || platform.namedBuildTarget == NamedBuildTarget.Android || platform.namedBuildTarget == NamedBuildTarget.EmbeddedLinux || platform.namedBuildTarget == NamedBuildTarget.QNX)
{
PlayerSettings.enableOpenGLProfilerGPURecorders = EditorGUILayout.Toggle(SettingsContent.enableOpenGLProfilerGPURecorders, PlayerSettings.enableOpenGLProfilerGPURecorders);
// Add different notes/warnings depending on the tickbox combinations.
// These concern Frame Timing Stats as well as Profiler GPU Recorders,
// so are listed below both to (hopefully) highlight that they're linked.
if (PlayerSettings.enableOpenGLProfilerGPURecorders)
{
EditorGUILayout.HelpBox(SettingsContent.openGLFrameTimingStatsOffGPURecordersOnInfo.text, MessageType.Info);
}
}
if (hdrDisplaySupported)
{
bool requestRepaint = false;
bool oldAllowHDRDisplaySupport = PlayerSettings.allowHDRDisplaySupport;
PlayerSettings.allowHDRDisplaySupport = EditorGUILayout.Toggle(SettingsContent.allowHDRDisplay, oldAllowHDRDisplaySupport);
if (oldAllowHDRDisplaySupport != PlayerSettings.allowHDRDisplaySupport)
requestRepaint = true;
using (new EditorGUI.DisabledScope(!PlayerSettings.allowHDRDisplaySupport))
{
using (new EditorGUI.IndentLevelScope())
{
bool oldUseHDRDisplay = PlayerSettings.useHDRDisplay;
PlayerSettings.useHDRDisplay = EditorGUILayout.Toggle(SettingsContent.useHDRDisplay, oldUseHDRDisplay);
if (oldUseHDRDisplay != PlayerSettings.useHDRDisplay)
requestRepaint = true;
if (platform.namedBuildTarget.ToBuildTargetGroup() == BuildTargetGroup.Standalone || platform.namedBuildTarget == NamedBuildTarget.WindowsStoreApps || platform.namedBuildTarget == NamedBuildTarget.iOS)
{
using (new EditorGUI.DisabledScope(!PlayerSettings.useHDRDisplay))
{
using (new EditorGUI.IndentLevelScope())
{
EditorGUI.BeginChangeCheck();
HDRDisplayBitDepth oldBitDepth = PlayerSettings.hdrBitDepth;
HDRDisplayBitDepth[] bitDepthValues = { HDRDisplayBitDepth.BitDepth10, HDRDisplayBitDepth.BitDepth16 };
GUIContent hdrBitDepthLabel = EditorGUIUtility.TrTextContent("Swap Chain Bit Depth", "Affects the bit depth of the final swap chain format and color space.");
GUIContent[] hdrBitDepthNames = { EditorGUIUtility.TrTextContent("Bit Depth 10"), EditorGUIUtility.TrTextContent("Bit Depth 16") };
HDRDisplayBitDepth bitDepth = BuildEnumPopup(hdrBitDepthLabel, oldBitDepth, bitDepthValues, hdrBitDepthNames);
if (EditorGUI.EndChangeCheck())
{
PlayerSettings.hdrBitDepth = bitDepth;
if (oldBitDepth != bitDepth)
requestRepaint = true;
}
}
}
}
}
}
if (PlayerSettings.allowHDRDisplaySupport && GraphicsSettings.currentRenderPipeline != null && !SupportedRenderingFeatures.active.supportsHDR)
{
EditorGUILayout.HelpBox(SettingsContent.hdrOutputRequireHDRRenderingWarning.text, MessageType.Info);
}
if (requestRepaint)
EditorApplication.RequestRepaintAllViews();
}
// Virtual Texturing settings
using (new EditorGUI.DisabledScope(EditorApplication.isPlaying || EditorApplication.isCompiling))
{
EditorGUI.BeginChangeCheck();
bool selectedValue = m_VirtualTexturingSupportEnabled.boolValue;
m_VirtualTexturingSupportEnabled.boolValue = EditorGUILayout.Toggle(SettingsContent.virtualTexturingSupportEnabled, m_VirtualTexturingSupportEnabled.boolValue);
if (EditorGUI.EndChangeCheck())
{
if (PlayerSettings.OnVirtualTexturingChanged())
{
PlayerSettings.SetVirtualTexturingSupportEnabled(m_VirtualTexturingSupportEnabled.boolValue);
EditorApplication.RequestCloseAndRelaunchWithCurrentArguments();
GUIUtility.ExitGUI();
}
else
{
m_VirtualTexturingSupportEnabled.boolValue = selectedValue;
}
}
}
if (PlayerSettings.GetVirtualTexturingSupportEnabled())
{
// Test Platform compatibility
bool platformSupportsVT = UnityEngine.Rendering.VirtualTexturingEditor.Building.IsPlatformSupportedForPlayer(platform.defaultTarget);
if (!platformSupportsVT)
{
EditorGUILayout.HelpBox(SettingsContent.virtualTexturingUnsupportedPlatformWarning.text, MessageType.Warning);
}
// Test for all three 'Automatic Graphics API for X' checkboxes and report API/Platform-specific error
if (platform.namedBuildTarget.ToBuildTargetGroup() == BuildTargetGroup.Standalone)
{
var duplicatedBuildTargetCheck = new List<String>();
foreach (var buildTarget in BuildTargetDiscovery.StandaloneBuildTargets)
{
if (BuildTargetDiscovery.TryGetBuildTarget(buildTarget, out IBuildTarget iBuildTarget))
{
if (duplicatedBuildTargetCheck.Contains(iBuildTarget.TargetName)) // Win64 and Win have the same target name and would duplicate the hint box
continue;
duplicatedBuildTargetCheck.Add(iBuildTarget.TargetName);
ShowWarningIfVirtualTexturingUnsupportedByAPI(iBuildTarget, true);
}
}
}
else
{
if (platformSupportsVT && BuildTargetDiscovery.TryGetBuildTarget(platform.defaultTarget, out IBuildTarget iBuildTarget))
ShowWarningIfVirtualTexturingUnsupportedByAPI(iBuildTarget, false);
}
}
}
if (!isPreset)
EditorGUILayout.Space();
Stereo360CaptureGUI(platform.namedBuildTarget.ToBuildTargetGroup());
using (new EditorGUI.DisabledScope(EditorApplication.isPlaying || EditorApplication.isCompiling))
{
var target = platform.namedBuildTarget.ToBuildTargetGroup();
bool debugModeEnabled = PlayerSettings.GetLoadStoreDebugModeEnabledForPlatformGroup(target);
bool debugModeEditorOnly = PlayerSettings.GetLoadStoreDebugModeEditorOnlyForPlatformGroup(target);
EditorGUI.BeginChangeCheck();
debugModeEnabled = EditorGUILayout.Toggle(SettingsContent.loadStoreDebugModeCheckbox, debugModeEnabled);
if (debugModeEnabled)
{
EditorGUI.indentLevel++;
debugModeEditorOnly = EditorGUILayout.Toggle(SettingsContent.loadStoreDebugModeEditorOnlyCheckbox, debugModeEditorOnly);
EditorGUI.indentLevel--;
}
if (EditorGUI.EndChangeCheck())
{
PlayerSettings.SetLoadStoreDebugModeEnabledForPlatformGroup(target, debugModeEnabled);
PlayerSettings.SetLoadStoreDebugModeEditorOnlyForPlatformGroup(target, debugModeEditorOnly);
GUIUtility.ExitGUI();
}
}
EditorGUILayout.Space();
}
private bool VirtualTexturingInvalidGfxAPI(BuildTarget target, bool checkEditor)
{
GraphicsDeviceType[] gfxTypes = PlayerSettings.GetGraphicsAPIs(target);
bool supportedAPI = true;
foreach (GraphicsDeviceType api in gfxTypes)
{
supportedAPI &= UnityEngine.Rendering.VirtualTexturingEditor.Building.IsRenderAPISupported(api, target, checkEditor);
}
return !supportedAPI;
}
private static readonly Dictionary<IBuildTarget, GUIContent> virtualTexturingUnsupportedAPIContents = new();
void ShowWarningIfVirtualTexturingUnsupportedByAPI(IBuildTarget buildTarget, bool checkEditor)
{
GUIContent warningText = null;
if(!VirtualTexturingInvalidGfxAPI((BuildTarget)buildTarget.GetLegacyId, checkEditor))
return;
if (virtualTexturingUnsupportedAPIContents.TryGetValue(buildTarget, out var guiContent))
warningText = guiContent;
else
warningText = virtualTexturingUnsupportedAPIContents[buildTarget] = EditorGUIUtility.TrTextContent($"The target {buildTarget.DisplayName} graphics API does not support Virtual Texturing. To target compatible graphics APIs, uncheck 'Auto Graphics API', and remove OpenGL ES 2/3 and OpenGLCoreOpenGLCore.");
if (warningText != null)
EditorGUILayout.HelpBox(warningText.text, MessageType.Warning);
}
// WebGPU
private static IReadOnlyList<BuildTarget> k_WebGPUSupportedBuildTargets => new List<BuildTarget> {
BuildTarget.WebGL,
// The following is Google's Dawn native implementatation for WebGPU.
BuildTarget.StandaloneWindows,
BuildTarget.StandaloneWindows64,
// Dawn currently isn't supported on OSX or Linux.
};
private bool CheckIfWebGPUInGfxAPIList()
{
foreach (var target in k_WebGPUSupportedBuildTargets)
{
if (PlayerSettings.GetGraphicsAPIs(target).Contains(GraphicsDeviceType.WebGPU))
{
return true;
}
}
return false;
}
private void OtherSectionIdentificationGUI(BuildPlatform platform, ISettingEditorExtension settingsExtension)
{
// Identification
if (settingsExtension != null && settingsExtension.HasIdentificationGUI())
{
GUILayout.Label(SettingsContent.identificationTitle, EditorStyles.boldLabel);
settingsExtension.IdentificationSectionGUI();
EditorGUILayout.Space();
}
else if (platform.namedBuildTarget.ToBuildTargetGroup() == BuildTargetGroup.Standalone)
{
// TODO this should be move to an extension if we have one for MacOS or Standalone target at some point.
GUILayout.Label(SettingsContent.macAppStoreTitle, EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_OverrideDefaultApplicationIdentifier, EditorGUIUtility.TrTextContent("Override Default Bundle Identifier"));
using (var horizontal = new EditorGUILayout.HorizontalScope())
{
using (new EditorGUI.PropertyScope(horizontal.rect, GUIContent.none, m_OverrideDefaultApplicationIdentifier))
{
using (new EditorGUI.IndentLevelScope())
{
ShowApplicationIdentifierUI(BuildTargetGroup.Standalone, "Bundle Identifier", "'CFBundleIdentifier'");
}
}
}
PlayerSettingsEditor.ShowBuildNumberUI(m_BuildNumber, NamedBuildTarget.Standalone, "Build", "'CFBundleVersion'");
EditorGUILayout.PropertyField(m_MacAppStoreCategory, SettingsContent.macAppStoreCategory);
EditorGUILayout.PropertyField(m_UseMacAppStoreValidation, SettingsContent.useMacAppStoreValidation);
EditorGUILayout.Space();
}
}
private void OtherSectionVulkanSettingsGUI(BuildPlatform platform, ISettingEditorExtension settingsExtension)
{
// Standalone targets don't have a settingsExtension but support vulkan
if (settingsExtension != null && !settingsExtension.ShouldShowVulkanSettings())
return;
GUILayout.Label(SettingsContent.vulkanSettingsTitle, EditorStyles.boldLabel);
if (!isPreset)
{
PlayerSettings.vulkanEnableSetSRGBWrite = EditorGUILayout.Toggle(SettingsContent.vulkanEnableSetSRGBWrite, PlayerSettings.vulkanEnableSetSRGBWrite);
EditorGUILayout.PropertyField(m_VulkanNumSwapchainBuffers, SettingsContent.vulkanNumSwapchainBuffers);
PlayerSettings.vulkanNumSwapchainBuffers = (UInt32)m_VulkanNumSwapchainBuffers.intValue;
}
EditorGUILayout.PropertyField(m_VulkanEnableLateAcquireNextImage, SettingsContent.vulkanEnableLateAcquireNextImage);
EditorGUILayout.PropertyField(m_VulkanEnableCommandBufferRecycling, SettingsContent.vulkanEnableCommandBufferRecycling);
if (settingsExtension != null && settingsExtension.ShouldShowVulkanSettings())
settingsExtension.VulkanSectionGUI();
EditorGUILayout.Space();
}
internal void ShowPlatformIconsByKind(PlatformIconFieldGroup iconFieldGroup, bool foldByKind = true, bool foldBySubkind = true)
{
m_IconsEditor.ShowPlatformIconsByKind(iconFieldGroup, foldByKind, foldBySubkind);
}
internal static GUIContent GetApplicationIdentifierError(BuildTargetGroup targetGroup)
{
if (targetGroup == BuildTargetGroup.Android)
return SettingsContent.packageNameError;
return SettingsContent.applicationIdentifierError;
}
internal void ShowApplicationIdentifierUI(BuildTargetGroup targetGroup, string label, string tooltip)
{
var overrideDefaultID = m_OverrideDefaultApplicationIdentifier.boolValue;
var defaultIdentifier = String.Format("com.{0}.{1}", m_CompanyName.stringValue, m_ProductName.stringValue);
var oldIdentifier = "";
var currentIdentifier = PlayerSettings.SanitizeApplicationIdentifier(defaultIdentifier, targetGroup);
var buildTargetGroup = BuildPipeline.GetBuildTargetGroupName(targetGroup);
var warningMessage = SettingsContent.applicationIdentifierWarning.text;
var errorMessage = GetApplicationIdentifierError(targetGroup).text;
string GetSanitizedApplicationIdentifier()
{
var sanitizedIdentifier = PlayerSettings.SanitizeApplicationIdentifier(currentIdentifier, targetGroup);
if (currentIdentifier != oldIdentifier)
{
if (!overrideDefaultID && !PlayerSettings.IsApplicationIdentifierValid(currentIdentifier, targetGroup))
Debug.LogError(errorMessage);
else if (overrideDefaultID && sanitizedIdentifier != currentIdentifier)
Debug.LogWarning(warningMessage);
}
return sanitizedIdentifier;
}
if (!m_ApplicationIdentifier.serializedObject.isEditingMultipleObjects)
{
m_ApplicationIdentifier.TryGetMapEntry(buildTargetGroup, out var entry);
if (entry != null)
oldIdentifier = entry.FindPropertyRelative("second").stringValue;
if (currentIdentifier != oldIdentifier)
{
if (overrideDefaultID)
currentIdentifier = oldIdentifier;
else
m_ApplicationIdentifier.SetMapValue(buildTargetGroup, currentIdentifier);
}
EditorGUILayout.BeginVertical();
EditorGUI.BeginChangeCheck();
using (new EditorGUI.DisabledScope(!overrideDefaultID))
{
currentIdentifier = GetSanitizedApplicationIdentifier();
currentIdentifier = EditorGUILayout.TextField(EditorGUIUtility.TrTextContent(label, tooltip), currentIdentifier);
}
if (EditorGUI.EndChangeCheck())
{
currentIdentifier = GetSanitizedApplicationIdentifier();
m_ApplicationIdentifier.SetMapValue(buildTargetGroup, currentIdentifier);
}
if (currentIdentifier == "com.Company.ProductName" || currentIdentifier == "com.unity3d.player")
EditorGUILayout.HelpBox("Don't forget to set the Application Identifier.", MessageType.Warning);
else if (!PlayerSettings.IsApplicationIdentifierValid(currentIdentifier, targetGroup))
EditorGUILayout.HelpBox(errorMessage, MessageType.Error);
else if (!overrideDefaultID && currentIdentifier != defaultIdentifier)
EditorGUILayout.HelpBox(warningMessage, MessageType.Warning);
EditorGUILayout.EndVertical();
}
}
internal static void ShowBuildNumberUI(SerializedProperty prop, NamedBuildTarget buildTarget, string label, string tooltip)
{
if (!prop.serializedObject.isEditingMultipleObjects)
{
prop.TryGetMapEntry(buildTarget.TargetName, out var entry);
if (entry != null)
{
var buildNumber = entry.FindPropertyRelative("second");
EditorGUILayout.PropertyField(buildNumber, EditorGUIUtility.TrTextContent(label, tooltip));
}
}
}
private bool ShouldRestartEditorToApplySetting()
{
return EditorUtility.DisplayDialog("Unity editor restart required", "The Unity editor must be restarted for this change to take effect. Cancel to revert changes.", "Apply", "Cancel");
}
private ScriptingImplementation GetCurrentBackendForTarget(NamedBuildTarget namedBuildTarget)
{
if (m_ScriptingBackend.TryGetMapEntry(namedBuildTarget.TargetName, out var entry))
return (ScriptingImplementation)entry.FindPropertyRelative("second").intValue;
else
return PlayerSettings.GetDefaultScriptingBackend(namedBuildTarget);
}
private Il2CppCompilerConfiguration GetCurrentIl2CppCompilerConfigurationForTarget(NamedBuildTarget namedBuildTarget)
{
if (m_Il2CppCompilerConfiguration.TryGetMapEntry(namedBuildTarget.TargetName, out var entry))
return (Il2CppCompilerConfiguration)entry.FindPropertyRelative("second").intValue;
else
return Il2CppCompilerConfiguration.Release;
}
private Il2CppCodeGeneration GetCurrentIl2CppCodeGenerationForTarget(NamedBuildTarget namedBuildTarget)
{
if (m_Il2CppCodeGeneration.TryGetMapEntry(namedBuildTarget.TargetName, out var entry))
return (Il2CppCodeGeneration)entry.FindPropertyRelative("second").intValue;
else
return Il2CppCodeGeneration.OptimizeSpeed;
}
private Il2CppStacktraceInformation GetCurrentIl2CppStacktraceInformationOptionForTarget(NamedBuildTarget namedBuildTarget)
{
if (m_Il2CppStacktraceInformation.TryGetMapEntry(namedBuildTarget.TargetName, out var entry))
return (Il2CppStacktraceInformation)entry.FindPropertyRelative("second").intValue;
else
return Il2CppStacktraceInformation.MethodOnly;
}
private ManagedStrippingLevel GetCurrentManagedStrippingLevelForTarget(NamedBuildTarget namedBuildTarget, ScriptingImplementation backend)
{
if (m_ManagedStrippingLevel.TryGetMapEntry(namedBuildTarget.TargetName, out var entry))
return (ManagedStrippingLevel)entry.FindPropertyRelative("second").intValue;
else
{
if (backend == ScriptingImplementation.IL2CPP)
return ManagedStrippingLevel.Minimal;
else
return ManagedStrippingLevel.Disabled;
}
}
private ApiCompatibilityLevel GetApiCompatibilityLevelForTarget(NamedBuildTarget namedBuildTarget)
{
if (m_APICompatibilityLevel.TryGetMapEntry(namedBuildTarget.TargetName, out var entry))
return (ApiCompatibilityLevel)entry.FindPropertyRelative("second").intValue;
else
// See comment in EditorOnlyPlayerSettings regarding defaultApiCompatibilityLevel
return (ApiCompatibilityLevel)m_DefaultAPICompatibilityLevel.intValue;
}
private void SetApiCompatibilityLevelForTarget(string targetGroup, ApiCompatibilityLevel apiCompatibilityLevel)
{
if (m_APICompatibilityLevel.TryGetMapEntry(targetGroup, out _))
m_APICompatibilityLevel.SetMapValue(targetGroup, (int)apiCompatibilityLevel);
else
// See comment in EditorOnlyPlayerSettings regarding defaultApiCompatibilityLevel
m_DefaultAPICompatibilityLevel.intValue = (int)apiCompatibilityLevel;
}
private EditorAssembliesCompatibilityLevel GetEditorAssembliesCompatibilityLevel()
{
return (EditorAssembliesCompatibilityLevel)m_EditorAssembliesCompatibilityLevel.intValue;
}
private void SetEditorAssembliesCompatibilityLevel(EditorAssembliesCompatibilityLevel editorAssembliesCompatibilityLevel)
{
// We won't allow switching back to the "Default" value.
if (editorAssembliesCompatibilityLevel != EditorAssembliesCompatibilityLevel.Default)
m_EditorAssembliesCompatibilityLevel.intValue = (int)editorAssembliesCompatibilityLevel;
}
private void OtherSectionConfigurationGUI(BuildPlatform platform, ISettingEditorExtension settingsExtension)
{
// Configuration
GUILayout.Label(SettingsContent.configurationTitle, EditorStyles.boldLabel);
// scripting runtime settings in play mode are not supported
using (new EditorGUI.DisabledScope(EditorApplication.isPlaying))
{
// Scripting back-end
bool allowCompilerConfigurationSelection = false;
ScriptingImplementation currentBackend = GetCurrentBackendForTarget(platform.namedBuildTarget);
using (new EditorGUI.DisabledScope(m_SerializedObject.isEditingMultipleObjects))
{
using (var horizontal = new EditorGUILayout.HorizontalScope())
{
using (var propertyScope = new EditorGUI.PropertyScope(horizontal.rect, GUIContent.none, m_ScriptingBackend))
{
IScriptingImplementations scripting = ModuleManager.GetScriptingImplementations(platform.namedBuildTarget);
if (scripting == null)
{
allowCompilerConfigurationSelection = true; // All platforms that support only one scripting backend are IL2CPP platforms
BuildDisabledEnumPopup(SettingsContent.scriptingDefault, SettingsContent.scriptingBackend);
}
else
{
var backends = scripting.Enabled();
allowCompilerConfigurationSelection = currentBackend == ScriptingImplementation.IL2CPP && scripting.AllowIL2CPPCompilerConfigurationSelection();
ScriptingImplementation newBackend;
if (backends.Length == 1)
{
newBackend = backends[0];
BuildDisabledEnumPopup(GetNiceScriptingBackendName(backends[0]), SettingsContent.scriptingBackend);
}
else
{
newBackend = BuildEnumPopup(SettingsContent.scriptingBackend, currentBackend, backends, GetNiceScriptingBackendNames(backends));
}
if (newBackend != currentBackend)
{
m_ScriptingBackend.SetMapValue(platform.namedBuildTarget.TargetName, (int)newBackend);
currentBackend = newBackend;
}
}
}
}
}
// Api Compatibility Level
using (new EditorGUI.DisabledScope(m_SerializedObject.isEditingMultipleObjects))
{
using (var horizontal = new EditorGUILayout.HorizontalScope())
{
using (var propertyScope = new EditorGUI.PropertyScope(horizontal.rect, GUIContent.none, m_APICompatibilityLevel))
{
var currentAPICompatibilityLevel = GetApiCompatibilityLevelForTarget(platform.namedBuildTarget);
var availableCompatibilityLevels = new ApiCompatibilityLevel[] { ApiCompatibilityLevel.NET_Unity_4_8, ApiCompatibilityLevel.NET_Standard };
var newAPICompatibilityLevel = BuildEnumPopup(
SettingsContent.apiCompatibilityLevel,
currentAPICompatibilityLevel,
availableCompatibilityLevels,
GetNiceApiCompatibilityLevelNames(availableCompatibilityLevels)
);
if (newAPICompatibilityLevel != currentAPICompatibilityLevel)
{
SetApiCompatibilityLevelForTarget(platform.namedBuildTarget.TargetName, newAPICompatibilityLevel);
if (platform.IsActive())
{
SetReason(RecompileReason.apiCompatibilityLevelModified);
}
}
}
}
}
// Editor Assemblies Compatibility level
using (new EditorGUI.DisabledScope(m_SerializedObject.isEditingMultipleObjects))
{
using (var horizontal = new EditorGUILayout.HorizontalScope())
{
using (var propertyScope = new EditorGUI.PropertyScope(horizontal.rect, GUIContent.none, m_EditorAssembliesCompatibilityLevel))
{
var currentEditorAssembliesCompatibilityLevel = GetEditorAssembliesCompatibilityLevel();
List<EditorAssembliesCompatibilityLevel> availableEditorAssemblyCompatibilityLevels = new List<EditorAssembliesCompatibilityLevel>(3);
if (currentEditorAssembliesCompatibilityLevel == EditorAssembliesCompatibilityLevel.Default)
{
availableEditorAssemblyCompatibilityLevels.Add(EditorAssembliesCompatibilityLevel.Default);
}
availableEditorAssemblyCompatibilityLevels.Add(EditorAssembliesCompatibilityLevel.NET_Unity_4_8);
availableEditorAssemblyCompatibilityLevels.Add(EditorAssembliesCompatibilityLevel.NET_Standard);
var newEditorAssembliesCompatibilityLevel = BuildEnumPopup(
SettingsContent.editorAssembliesCompatibilityLevel,
currentEditorAssembliesCompatibilityLevel,
availableEditorAssemblyCompatibilityLevels.ToArray(),
GetNiceEditorAssembliesCompatibilityLevelNames(availableEditorAssemblyCompatibilityLevels.ToArray())
);
if (newEditorAssembliesCompatibilityLevel != currentEditorAssembliesCompatibilityLevel)
{
SetEditorAssembliesCompatibilityLevel(newEditorAssembliesCompatibilityLevel);
if (platform.IsActive())
{
SetReason(RecompileReason.editorAssembliesCompatibilityLevelModified);
}
}
}
}
}
// Il2cpp Code Generation
using (new EditorGUI.DisabledScope(m_SerializedObject.isEditingMultipleObjects))
{
using (var horizontal = new EditorGUILayout.HorizontalScope())
{
using (var propertyScope = new EditorGUI.PropertyScope(horizontal.rect, GUIContent.none, m_Il2CppCodeGeneration))
{
using (new EditorGUI.DisabledScope(currentBackend != ScriptingImplementation.IL2CPP))
{
var currentCodeGeneration = GetCurrentIl2CppCodeGenerationForTarget(platform.namedBuildTarget);
var codeGenerationValues = new[] { Il2CppCodeGeneration.OptimizeSpeed, Il2CppCodeGeneration.OptimizeSize };
var newCodeGeneration = BuildEnumPopup(SettingsContent.il2cppCodeGeneration, currentCodeGeneration, codeGenerationValues, SettingsContent.il2cppCodeGenerationNames);
if (currentCodeGeneration != newCodeGeneration)
m_Il2CppCodeGeneration.SetMapValue(platform.namedBuildTarget.TargetName, (int)newCodeGeneration);
}
}
}
}
// Il2cpp Compiler Configuration
using (new EditorGUI.DisabledScope(m_SerializedObject.isEditingMultipleObjects))
{
using (var horizontal = new EditorGUILayout.HorizontalScope())
{
using (var propertyScope = new EditorGUI.PropertyScope(horizontal.rect, GUIContent.none, m_Il2CppCompilerConfiguration))
{
using (new EditorGUI.DisabledScope(!allowCompilerConfigurationSelection))
{
Il2CppCompilerConfiguration currentConfiguration = GetCurrentIl2CppCompilerConfigurationForTarget(platform.namedBuildTarget);
var configurations = GetIl2CppCompilerConfigurations();
var configurationNames = GetIl2CppCompilerConfigurationNames();
var newConfiguration = BuildEnumPopup(SettingsContent.il2cppCompilerConfiguration, currentConfiguration, configurations, configurationNames);
if (currentConfiguration != newConfiguration)
m_Il2CppCompilerConfiguration.SetMapValue(platform.namedBuildTarget.TargetName, (int)newConfiguration);
}
}
}
}
// Il2Cpp Stacktrace Configuration
using (new EditorGUI.DisabledScope(currentBackend != ScriptingImplementation.IL2CPP || platform.namedBuildTarget == NamedBuildTarget.WebGL))
{
Il2CppStacktraceInformation config = GetCurrentIl2CppStacktraceInformationOptionForTarget(platform.namedBuildTarget);
var newConfiguration = BuildEnumPopup(SettingsContent.il2cppStacktraceInformation, config,
GetIl2CppStacktraceOptions(), GetIl2CppStacktraceOptionNames());
if (config != newConfiguration)
m_Il2CppStacktraceInformation.SetMapValue(platform.namedBuildTarget.TargetName, (int)newConfiguration);
}
bool gcIncrementalEnabled = BuildPipeline.IsFeatureSupported("ENABLE_SCRIPTING_GC_WBARRIERS", platform.defaultTarget);
using (new EditorGUI.DisabledScope(!gcIncrementalEnabled))
{
var oldValue = m_GCIncremental.boolValue;
EditorGUILayout.PropertyField(m_GCIncremental, SettingsContent.gcIncremental);
if (m_GCIncremental.boolValue != oldValue)
{
// Give the user a chance to change mind and revert changes.
if (ShouldRestartEditorToApplySetting())
{
m_GCIncremental.serializedObject.ApplyModifiedProperties();
EditorApplication.OpenProject(Environment.CurrentDirectory);
}
else
m_GCIncremental.boolValue = oldValue;
}
}
}
var insecureHttp = BuildEnumPopup(m_InsecureHttpOption, SettingsContent.insecureHttpOption, new[] { InsecureHttpOption.NotAllowed, InsecureHttpOption.DevelopmentOnly, InsecureHttpOption.AlwaysAllowed }, SettingsContent.insecureHttpOptions);
if (insecureHttp == InsecureHttpOption.AlwaysAllowed)
EditorGUILayout.HelpBox(SettingsContent.insecureHttpWarning.text, MessageType.Warning);
// Privacy permissions
bool showPrivacyPermissions =
platform.namedBuildTarget == NamedBuildTarget.iOS || platform.namedBuildTarget == NamedBuildTarget.tvOS || platform.namedBuildTarget == NamedBuildTarget.VisionOS;
if (showPrivacyPermissions)
{
EditorGUILayout.PropertyField(m_CameraUsageDescription, SettingsContent.cameraUsageDescription);
EditorGUILayout.PropertyField(m_MicrophoneUsageDescription, SettingsContent.microphoneUsageDescription);
if (platform.namedBuildTarget == NamedBuildTarget.iOS || platform.namedBuildTarget == NamedBuildTarget.tvOS)
EditorGUILayout.PropertyField(m_LocationUsageDescription, SettingsContent.locationUsageDescription);
}
bool showMobileSection =
platform.namedBuildTarget == NamedBuildTarget.iOS ||
platform.namedBuildTarget == NamedBuildTarget.tvOS ||
platform.namedBuildTarget == NamedBuildTarget.Android ||
platform.namedBuildTarget == NamedBuildTarget.WindowsStoreApps;
// mobile-only settings
if (showMobileSection)
{
if (platform.namedBuildTarget == NamedBuildTarget.iOS || platform.namedBuildTarget == NamedBuildTarget.tvOS)
EditorGUILayout.PropertyField(m_useOnDemandResources, SettingsContent.useOnDemandResources);
bool supportsAccelerometerFrequency =
platform.namedBuildTarget == NamedBuildTarget.iOS ||
platform.namedBuildTarget == NamedBuildTarget.tvOS ||
platform.namedBuildTarget == NamedBuildTarget.WindowsStoreApps;
if (supportsAccelerometerFrequency)
EditorGUILayout.PropertyField(m_AccelerometerFrequency, SettingsContent.accelerometerFrequency);
if (platform.namedBuildTarget == NamedBuildTarget.iOS || platform.namedBuildTarget == NamedBuildTarget.tvOS || platform.namedBuildTarget == NamedBuildTarget.Android)
EditorGUILayout.PropertyField(m_MuteOtherAudioSources, SettingsContent.muteOtherAudioSources);
// TVOS TODO: check what should stay or go
if (platform.namedBuildTarget == NamedBuildTarget.iOS || platform.namedBuildTarget == NamedBuildTarget.tvOS)
{
if (platform.namedBuildTarget == NamedBuildTarget.iOS)
{
EditorGUILayout.PropertyField(m_PrepareIOSForRecording, SettingsContent.prepareIOSForRecording);
if (m_MuteOtherAudioSources.boolValue == false && m_PrepareIOSForRecording.boolValue == false)
EditorGUILayout.HelpBox(SettingsContent.iOSExternalAudioInputNotSupported.text, MessageType.Warning);
EditorGUILayout.PropertyField(m_ForceIOSSpeakersWhenRecording, SettingsContent.forceIOSSpeakersWhenRecording);
}
EditorGUILayout.PropertyField(m_UIRequiresPersistentWiFi, SettingsContent.UIRequiresPersistentWiFi);
}
}
if (platform.namedBuildTarget == NamedBuildTarget.iOS || platform.namedBuildTarget == NamedBuildTarget.tvOS || platform.namedBuildTarget == NamedBuildTarget.VisionOS)
EditorGUILayout.PropertyField(m_IOSURLSchemes, SettingsContent.iOSURLSchemes, true);
if (settingsExtension != null)
settingsExtension.ConfigurationSectionGUI();
// Active input handling
if (platform.namedBuildTarget != NamedBuildTarget.Server)
{
using (var vertical = new EditorGUILayout.VerticalScope())
{
var currValue = m_ActiveInputHandler.intValue;
using (var propertyScope = new EditorGUI.PropertyScope(vertical.rect, GUIContent.none, m_ActiveInputHandler))
{
m_ActiveInputHandler.intValue = EditorGUILayout.Popup(SettingsContent.activeInputHandling, m_ActiveInputHandler.intValue, SettingsContent.activeInputHandlingOptions);
}
if (m_ActiveInputHandler.intValue != currValue)
{
// Give the user a chance to change mind and revert changes.
if (ShouldRestartEditorToApplySetting())
{
m_ActiveInputHandler.serializedObject.ApplyModifiedProperties();
EditorApplication.RestartEditorAndRecompileScripts();
}
else
m_ActiveInputHandler.intValue = currValue;
}
}
}
EditorGUILayout.Space();
if (platform.namedBuildTarget == NamedBuildTarget.Standalone)
{
GUILayout.Label(SettingsContent.macConfigurationTitle, EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_CameraUsageDescription, SettingsContent.cameraUsageDescription);
EditorGUILayout.PropertyField(m_MicrophoneUsageDescription, SettingsContent.microphoneUsageDescription);
EditorGUILayout.PropertyField(m_BluetoothUsageDescription, SettingsContent.bluetoothUsageDescription);
EditorGUILayout.PropertyField(m_MacURLSchemes, SettingsContent.macOSURLSchemes, true);
EditorGUILayout.Space();
}
}
private string GetScriptingDefineSymbolsForGroup(NamedBuildTarget buildTarget)
{
string defines = string.Empty;
if (m_ScriptingDefines.TryGetMapEntry(buildTarget.TargetName, out var entry))
{
defines = entry.FindPropertyRelative("second").stringValue;
}
return defines;
}
private void SetScriptingDefineSymbolsForGroup(NamedBuildTarget buildTarget, string[] defines)
{
m_ScriptingDefines.SetMapValue(buildTarget.TargetName, ScriptingDefinesHelper.ConvertScriptingDefineArrayToString(defines));
}
string[] GetAdditionalCompilerArgumentsForGroup(NamedBuildTarget buildTarget)
{
if (m_AdditionalCompilerArguments.TryGetMapEntry(buildTarget.TargetName, out var entry))
{
var serializedArguments = entry.FindPropertyRelative("second");
var arguments = new string[serializedArguments.arraySize];
for (int i = 0; i < serializedArguments.arraySize; ++i)
{
arguments[i] = serializedArguments.GetArrayElementAtIndex(i).stringValue;
}
return arguments;
}
return new string[0];
}
void SetAdditionalCompilerArgumentsForGroup(NamedBuildTarget buildTarget, string[] arguments)
{
m_AdditionalCompilerArguments.SetMapValue(buildTarget.TargetName, arguments);
}
bool GetCaptureStartupLogsForTarget(NamedBuildTarget buildTarget)
{
if (m_CaptureStartupLogs.TryGetMapEntry(buildTarget.TargetName, out var entry))
{
if (entry != null)
return entry.FindPropertyRelative("second").boolValue;
}
return buildTarget == NamedBuildTarget.Server ? true : false;
}
private void OtherSectionScriptCompilationGUI(BuildPlatform platform)
{
// Configuration
GUILayout.Label(SettingsContent.scriptCompilationTitle, EditorStyles.boldLabel);
// User script defines
using (new EditorGUI.DisabledScope(m_SerializedObject.isEditingMultipleObjects))
{
using (var vertical = new EditorGUILayout.VerticalScope())
{
if (serializedScriptingDefines == null || scriptingDefineSymbolsList == null)
{
InitReorderableScriptingDefineSymbolsList(platform.namedBuildTarget);
}
if (lastNamedBuildTarget.TargetName == platform.namedBuildTarget.TargetName)
{
scriptingDefineSymbolsList.DoLayoutList();
}
else
{
// If platform changes, update define symbols
serializedScriptingDefines = GetScriptingDefineSymbolsForGroup(platform.namedBuildTarget);
UpdateScriptingDefineSymbolsLists();
}
lastNamedBuildTarget = platform.namedBuildTarget;
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.FlexibleSpace();
var GUIState = GUI.enabled;
GUI.enabled = serializedScriptingDefines.Count() > 0;
if (GUILayout.Button(SettingsContent.scriptingDefineSymbolsCopyDefines, EditorStyles.miniButton))
{
EditorGUIUtility.systemCopyBuffer = PlayerSettings.GetScriptingDefineSymbols(platform.namedBuildTarget);
}
GUI.enabled = hasScriptingDefinesBeenModified;
if (GUILayout.Button(SettingsContent.scriptingDefineSymbolsApplyRevert, EditorStyles.miniButton))
{
// Make sure to remove focus from reorderable list text field on revert
GUI.FocusControl(null);
UpdateScriptingDefineSymbolsLists();
}
if (GUILayout.Button(SettingsContent.scriptingDefineSymbolsApply, EditorStyles.miniButton))
{
// Make sure to remove focus from reorderable list text field on apply
GUI.FocusControl(null);
SetScriptingDefineSymbolsForGroup(platform.namedBuildTarget, scriptingDefinesList.ToArray());
// Get Scripting Define Symbols without duplicates
serializedScriptingDefines = GetScriptingDefineSymbolsForGroup(platform.namedBuildTarget);
UpdateScriptingDefineSymbolsLists();
if (platform.IsActive())
SetReason(RecompileReason.scriptingDefineSymbolsModified);
}
// Set previous GUIState
GUI.enabled = GUIState;
}
scriptingDefinesControlID = EditorGUIUtility.s_LastControlID;
}
EditorGUILayout.Space();
using (var vertical = new EditorGUILayout.VerticalScope())
{
if (serializedAdditionalCompilerArguments == null || additionalCompilerArgumentsReorderableList == null)
{
InitReorderableAdditionalCompilerArgumentsList(platform.namedBuildTarget);
}
using (new EditorGUI.PropertyScope(vertical.rect, GUIContent.none, m_AdditionalCompilerArguments))
{
additionalCompilerArgumentsReorderableList.DoLayoutList();
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.FlexibleSpace();
using (new EditorGUI.DisabledScope(!hasAdditionalCompilerArgumentsBeenModified))
{
if (GUILayout.Button(SettingsContent.scriptingDefineSymbolsApplyRevert, EditorStyles.miniButton, GUILayout.ExpandWidth(false)))
{
UpdateAdditionalCompilerArgumentsLists();
}
if (GUILayout.Button(SettingsContent.scriptingDefineSymbolsApply, EditorStyles.miniButton, GUILayout.ExpandWidth(false)))
{
SetAdditionalCompilerArgumentsForGroup(platform.namedBuildTarget, additionalCompilerArgumentsList.ToArray());
// Get Additional Compiler Arguments without duplicates
serializedAdditionalCompilerArguments = GetAdditionalCompilerArgumentsForGroup(platform.namedBuildTarget);
UpdateAdditionalCompilerArgumentsLists();
if (platform.IsActive())
{
SetReason(RecompileReason.additionalCompilerArgumentsModified);
}
}
}
}
}
}
}
// Suppress common warnings
EditorGUILayout.PropertyField(m_SuppressCommonWarnings, SettingsContent.suppressCommonWarnings);
if (serializedSuppressCommonWarnings != m_SuppressCommonWarnings.boolValue)
{
serializedSuppressCommonWarnings = m_SuppressCommonWarnings.boolValue;
SetReason(RecompileReason.suppressCommonWarningsModified);
}
// Allow unsafe code
EditorGUILayout.PropertyField(m_AllowUnsafeCode, SettingsContent.allowUnsafeCode);
if (serializedAllowUnsafeCode != m_AllowUnsafeCode.boolValue)
{
serializedAllowUnsafeCode = m_AllowUnsafeCode.boolValue;
SetReason(RecompileReason.allowUnsafeCodeModified);
}
// Use deterministic compliation
EditorGUILayout.PropertyField(m_UseDeterministicCompilation, SettingsContent.useDeterministicCompilation);
if (serializedUseDeterministicCompilation != m_UseDeterministicCompilation.boolValue)
{
serializedUseDeterministicCompilation = m_UseDeterministicCompilation.boolValue;
SetReason(RecompileReason.useDeterministicCompilationModified);
}
}
void DrawTextField(Rect rect, int index)
{
// Handle list selection before the TextField grabs input
Event evt = Event.current;
if (evt.type == EventType.MouseDown && rect.Contains(evt.mousePosition))
{
if (scriptingDefineSymbolsList.index != index)
{
scriptingDefineSymbolsList.index = index;
scriptingDefineSymbolsList.onSelectCallback?.Invoke(scriptingDefineSymbolsList);
}
}
string define = scriptingDefinesList[index];
scriptingDefinesList[index] = EditorGUI.TextField(rect, scriptingDefinesList[index]);
if (!scriptingDefinesList[index].Equals(define))
SetScriptingDefinesListDirty();
}
void DrawTextFieldAdditionalCompilerArguments(Rect rect, int index)
{
// Handle list selection before the TextField grabs input
Event evt = Event.current;
if (evt.type == EventType.MouseDown && rect.Contains(evt.mousePosition))
{
if (additionalCompilerArgumentsReorderableList.index != index)
{
additionalCompilerArgumentsReorderableList.index = index;
additionalCompilerArgumentsReorderableList.onSelectCallback?.Invoke(additionalCompilerArgumentsReorderableList);
}
}
string additionalCompilerArgument = additionalCompilerArgumentsList[index];
additionalCompilerArgumentsList[index] = GUI.TextField(rect, additionalCompilerArgumentsList[index]);
if (!additionalCompilerArgumentsList[index].Equals(additionalCompilerArgument))
SetAdditionalCompilerArgumentListDirty();
}
void AddScriptingDefineCallback(ReorderableList list)
{
scriptingDefinesList.Add("");
SetScriptingDefinesListDirty();
}
void RemoveScriptingDefineCallback(ReorderableList list)
{
scriptingDefinesList.RemoveAt(list.index);
SetScriptingDefinesListDirty();
}
void DrawScriptingDefinesHeaderCallback(Rect rect)
{
using (new EditorGUI.PropertyScope(rect, GUIContent.none, m_ScriptingDefines))
{
GUI.Label(rect, SettingsContent.scriptingDefineSymbols, EditorStyles.label);
}
}
void SetScriptingDefinesListDirty(ReorderableList list = null)
{
hasScriptingDefinesBeenModified = true;
}
void AddAdditionalCompilerArgumentCallback(ReorderableList list)
{
additionalCompilerArgumentsList.Add("");
SetAdditionalCompilerArgumentListDirty();
}
void RemoveAdditionalCompilerArgumentCallback(ReorderableList list)
{
additionalCompilerArgumentsList.RemoveAt(list.index);
SetAdditionalCompilerArgumentListDirty();
}
void SetAdditionalCompilerArgumentListDirty(ReorderableList list = null)
{
hasAdditionalCompilerArgumentsBeenModified = true;
}
private void OtherSectionOptimizationGUI(BuildPlatform platform)
{
// Optimization
GUILayout.Label(SettingsContent.optimizationTitle, EditorStyles.boldLabel);
if (platform.namedBuildTarget == NamedBuildTarget.Server)
EditorGUILayout.PropertyField(m_DedicatedServerOptimizations, SettingsContent.dedicatedServerOptimizations);
EditorGUILayout.PropertyField(m_BakeCollisionMeshes, SettingsContent.bakeCollisionMeshes);
if (isPreset)
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(m_PreloadedAssets, SettingsContent.preloadedAssets, true);
if (isPreset)
EditorGUI.indentLevel--;
bool platformUsesAOT =
platform.namedBuildTarget == NamedBuildTarget.iOS ||
platform.namedBuildTarget == NamedBuildTarget.tvOS ||
platform.namedBuildTarget == NamedBuildTarget.XboxOne ||
platform.namedBuildTarget == NamedBuildTarget.PS4;
if (platformUsesAOT)
EditorGUILayout.PropertyField(m_AotOptions, SettingsContent.aotOptions);
bool platformSupportsStripping = !BuildTargetDiscovery.PlatformGroupHasFlag(platform.namedBuildTarget.ToBuildTargetGroup(), TargetAttributes.StrippingNotSupported);
if (platformSupportsStripping)
{
ScriptingImplementation backend = GetCurrentBackendForTarget(platform.namedBuildTarget);
if (BuildPipeline.IsFeatureSupported("ENABLE_ENGINE_CODE_STRIPPING", platform.defaultTarget) && backend == ScriptingImplementation.IL2CPP)
EditorGUILayout.PropertyField(m_StripEngineCode, SettingsContent.stripEngineCode);
using (var vertical = new EditorGUILayout.VerticalScope())
{
using (var propertyScope = new EditorGUI.PropertyScope(vertical.rect, GUIContent.none, m_ManagedStrippingLevel))
{
var availableStrippingLevels = GetAvailableManagedStrippingLevels(backend);
ManagedStrippingLevel currentManagedStrippingLevel = GetCurrentManagedStrippingLevelForTarget(platform.namedBuildTarget, backend);
ManagedStrippingLevel newManagedStrippingLevel;
newManagedStrippingLevel = BuildEnumPopup(SettingsContent.managedStrippingLevel, currentManagedStrippingLevel, availableStrippingLevels, GetNiceManagedStrippingLevelNames(availableStrippingLevels));
if (newManagedStrippingLevel != currentManagedStrippingLevel)
m_ManagedStrippingLevel.SetMapValue(platform.namedBuildTarget.TargetName, (int)newManagedStrippingLevel);
}
}
}
if (platform.namedBuildTarget == NamedBuildTarget.iOS || platform.namedBuildTarget == NamedBuildTarget.tvOS)
{
EditorGUILayout.PropertyField(m_IPhoneScriptCallOptimization, SettingsContent.iPhoneScriptCallOptimization);
}
if (platform.namedBuildTarget == NamedBuildTarget.Android)
{
EditorGUILayout.PropertyField(m_AndroidProfiler, SettingsContent.enableInternalProfiler);
}
EditorGUILayout.Space();
// Vertex compression flags dropdown
VertexChannelCompressionFlags vertexFlags = (VertexChannelCompressionFlags)m_VertexChannelCompressionMask.intValue;
vertexFlags = (VertexChannelCompressionFlags)EditorGUILayout.EnumFlagsField(SettingsContent.vertexChannelCompressionMask, vertexFlags);
m_VertexChannelCompressionMask.intValue = (int)vertexFlags;
EditorGUILayout.PropertyField(m_StripUnusedMeshComponents, SettingsContent.stripUnusedMeshComponents);
EditorGUILayout.PropertyField(m_MipStripping, SettingsContent.mipStripping);
EditorGUILayout.Space();
}
static ManagedStrippingLevel[] mono_levels = new ManagedStrippingLevel[] { ManagedStrippingLevel.Disabled, ManagedStrippingLevel.Minimal, ManagedStrippingLevel.Low, ManagedStrippingLevel.Medium, ManagedStrippingLevel.High };
static ManagedStrippingLevel[] il2cpp_levels = new ManagedStrippingLevel[] { ManagedStrippingLevel.Minimal, ManagedStrippingLevel.Low, ManagedStrippingLevel.Medium, ManagedStrippingLevel.High };
// stripping levels vary based on scripting backend
private ManagedStrippingLevel[] GetAvailableManagedStrippingLevels(ScriptingImplementation backend)
{
if (backend == ScriptingImplementation.IL2CPP)
{
return il2cpp_levels;
}
else
{
return mono_levels;
}
}
static Il2CppCompilerConfiguration[] m_Il2cppCompilerConfigurations;
static GUIContent[] m_Il2cppCompilerConfigurationNames;
private Il2CppCompilerConfiguration[] GetIl2CppCompilerConfigurations()
{
if (m_Il2cppCompilerConfigurations == null)
{
m_Il2cppCompilerConfigurations = new Il2CppCompilerConfiguration[]
{
Il2CppCompilerConfiguration.Debug,
Il2CppCompilerConfiguration.Release,
Il2CppCompilerConfiguration.Master,
};
}
return m_Il2cppCompilerConfigurations;
}
private GUIContent[] GetIl2CppCompilerConfigurationNames()
{
if (m_Il2cppCompilerConfigurationNames == null)
{
var configurations = GetIl2CppCompilerConfigurations();
m_Il2cppCompilerConfigurationNames = new GUIContent[configurations.Length];
for (int i = 0; i < configurations.Length; i++)
m_Il2cppCompilerConfigurationNames[i] = EditorGUIUtility.TextContent(configurations[i].ToString());
}
return m_Il2cppCompilerConfigurationNames;
}
static Il2CppStacktraceInformation[] m_Il2cppStacktraceOptions;
static GUIContent[] m_Il2cppStacktraceOptionNames;
private Il2CppStacktraceInformation[] GetIl2CppStacktraceOptions()
{
if (m_Il2cppStacktraceOptions == null)
m_Il2cppStacktraceOptions = (Il2CppStacktraceInformation[])Enum.GetValues(typeof(Il2CppStacktraceInformation));
return m_Il2cppStacktraceOptions;
}
private GUIContent[] GetIl2CppStacktraceOptionNames()
{
if (m_Il2cppStacktraceOptionNames == null)
{
m_Il2cppStacktraceOptionNames = new GUIContent[]
{
EditorGUIUtility.TextContent("Method Name"),
EditorGUIUtility.TextContent("Method Name, File Name, and Line Number"),
};
}
return m_Il2cppStacktraceOptionNames;
}
public static bool IsLatestApiCompatibility(ApiCompatibilityLevel level)
{
return (level == ApiCompatibilityLevel.NET_4_6 || level == ApiCompatibilityLevel.NET_Standard_2_0);
}
private void OtherSectionLoggingGUI()
{
GUILayout.Label(SettingsContent.loggingTitle, EditorStyles.boldLabel);
using (var vertical = new EditorGUILayout.VerticalScope())
{
using (var propertyScope = new EditorGUI.PropertyScope(vertical.rect, GUIContent.none, m_StackTraceTypes))
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Label("Log Type");
foreach (StackTraceLogType stackTraceLogType in Enum.GetValues(typeof(StackTraceLogType)))
GUILayout.Label(stackTraceLogType.ToString(), GUILayout.Width(70));
}
foreach (LogType logType in Enum.GetValues(typeof(LogType)))
{
var logProperty = m_StackTraceTypes.GetArrayElementAtIndex((int)logType);
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Label(logType.ToString(), GUILayout.MinWidth(60));
foreach (StackTraceLogType stackTraceLogType in Enum.GetValues(typeof(StackTraceLogType)))
{
StackTraceLogType inStackTraceLogType = (StackTraceLogType)logProperty.intValue;
EditorGUI.BeginChangeCheck();
bool val = EditorGUILayout.ToggleLeft(" ", inStackTraceLogType == stackTraceLogType, GUILayout.Width(65));
if (EditorGUI.EndChangeCheck() && val)
{
logProperty.intValue = (int)stackTraceLogType;
if (!isPreset)
PlayerSettings.SetGlobalStackTraceLogType(logType, stackTraceLogType);
}
}
}
}
}
}
EditorGUILayout.Space();
}
private void Stereo360CaptureGUI(BuildTargetGroup targetGroup)
{
EditorGUILayout.PropertyField(m_Enable360StereoCapture, SettingsContent.stereo360CaptureCheckbox);
}
private void OtherSectionLegacyGUI(BuildPlatform platform)
{
GUILayout.Label(SettingsContent.legacyTitle, EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_LegacyClampBlendShapeWeights, SettingsContent.legacyClampBlendShapeWeights);
EditorGUILayout.Space();
}
private void OtherSectionCaptureLogsGUI(NamedBuildTarget namedBuildTarget)
{
GUILayout.Label(SettingsContent.captureLogsTitle, EditorStyles.boldLabel);
bool val = GetCaptureStartupLogsForTarget(namedBuildTarget);
bool newVal = EditorGUILayout.Toggle(SettingsContent.captureStartupLogs, val);
if (val != newVal)
m_CaptureStartupLogs.SetMapValue(namedBuildTarget.TargetName, newVal);
EditorGUILayout.Space();
}
private static Dictionary<ApiCompatibilityLevel, GUIContent> m_NiceApiCompatibilityLevelNames;
private static Dictionary<EditorAssembliesCompatibilityLevel, GUIContent> m_NiceEditorAssembliesCompatibilityLevelNames;
private static Dictionary<ManagedStrippingLevel, GUIContent> m_NiceManagedStrippingLevelNames;
private static GUIContent[] GetGUIContentsForValues<T>(Dictionary<T, GUIContent> contents, T[] values)
{
var names = new GUIContent[values.Length];
for (int i = 0; i < values.Length; i++)
{
if (contents.ContainsKey(values[i]))
names[i] = contents[values[i]];
else
throw new NotImplementedException(string.Format("Missing name for {0}", values[i]));
}
return names;
}
static GUIContent[] GetNiceScriptingBackendNames(ScriptingImplementation[] scriptingBackends)
{
return scriptingBackends.Select(s => GetNiceScriptingBackendName(s)).ToArray();
}
static GUIContent GetNiceScriptingBackendName(ScriptingImplementation scriptingBackend)
{
switch (scriptingBackend)
{
case ScriptingImplementation.Mono2x:
return SettingsContent.scriptingMono2x;
case ScriptingImplementation.IL2CPP:
return SettingsContent.scriptingIL2CPP;
#pragma warning disable 618
case ScriptingImplementation.CoreCLR:
return SettingsContent.scriptingCoreCLR;
default:
throw new ArgumentException($"Scripting backend value {scriptingBackend} is not supported.", nameof(scriptingBackend));
}
}
private static GUIContent[] GetNiceApiCompatibilityLevelNames(ApiCompatibilityLevel[] apiCompatibilityLevels)
{
if (m_NiceApiCompatibilityLevelNames == null)
{
m_NiceApiCompatibilityLevelNames = new Dictionary<ApiCompatibilityLevel, GUIContent>
{
{ ApiCompatibilityLevel.NET_2_0, SettingsContent.apiCompatibilityLevel_NET_2_0 },
{ ApiCompatibilityLevel.NET_2_0_Subset, SettingsContent.apiCompatibilityLevel_NET_2_0_Subset },
{ ApiCompatibilityLevel.NET_Unity_4_8, SettingsContent.apiCompatibilityLevel_NET_FW_Unity },
{ ApiCompatibilityLevel.NET_Standard, SettingsContent.apiCompatibilityLevel_NET_Standard },
};
}
return GetGUIContentsForValues(m_NiceApiCompatibilityLevelNames, apiCompatibilityLevels);
}
private static GUIContent[] GetNiceEditorAssembliesCompatibilityLevelNames(EditorAssembliesCompatibilityLevel[] editorAssembliesCompatibilityLevels)
{
if (m_NiceEditorAssembliesCompatibilityLevelNames == null)
{
m_NiceEditorAssembliesCompatibilityLevelNames = new Dictionary<EditorAssembliesCompatibilityLevel, GUIContent>
{
{ EditorAssembliesCompatibilityLevel.Default, SettingsContent.editorAssembliesCompatibilityLevel_Default },
{ EditorAssembliesCompatibilityLevel.NET_Unity_4_8, SettingsContent.editorAssembliesCompatibilityLevel_NET_Framework },
{ EditorAssembliesCompatibilityLevel.NET_Standard, SettingsContent.editorAssembliesCompatibilityLevel_NET_Standard },
};
}
return GetGUIContentsForValues(m_NiceEditorAssembliesCompatibilityLevelNames, editorAssembliesCompatibilityLevels);
}
private static GUIContent[] GetNiceManagedStrippingLevelNames(ManagedStrippingLevel[] managedStrippingLevels)
{
if (m_NiceManagedStrippingLevelNames == null)
{
m_NiceManagedStrippingLevelNames = new Dictionary<ManagedStrippingLevel, GUIContent>
{
{ ManagedStrippingLevel.Disabled, SettingsContent.strippingDisabled },
{ ManagedStrippingLevel.Minimal, SettingsContent.strippingMinimal },
{ ManagedStrippingLevel.Low, SettingsContent.strippingLow },
{ ManagedStrippingLevel.Medium, SettingsContent.strippingMedium },
{ ManagedStrippingLevel.High, SettingsContent.strippingHigh },
};
}
return GetGUIContentsForValues(m_NiceManagedStrippingLevelNames, managedStrippingLevels);
}
public void BrowseablePathProperty(string propertyLabel, SerializedProperty property, string browsePanelTitle, string extension, string dir)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel(EditorGUIUtility.TextContent(propertyLabel));
GUIContent browseBtnLabel = EditorGUIUtility.TrTextContent("...");
Vector2 sizeOfLabel = GUI.skin.GetStyle("Button").CalcSize(browseBtnLabel);
if (GUILayout.Button(browseBtnLabel, EditorStyles.miniButton, GUILayout.MaxWidth(sizeOfLabel.x)))
{
GUI.FocusControl("");
string title = EditorGUIUtility.TempContent(browsePanelTitle).text;
string currDirectory = string.IsNullOrEmpty(dir) ? Directory.GetCurrentDirectory().Replace('\\', '/') + "/" : dir.Replace('\\', '/') + "/";
string newStringValue = "";
if (string.IsNullOrEmpty(extension))
newStringValue = EditorUtility.OpenFolderPanel(title, currDirectory, "");
else
newStringValue = EditorUtility.OpenFilePanel(title, currDirectory, extension);
if (newStringValue.StartsWith(currDirectory))
newStringValue = newStringValue.Substring(currDirectory.Length);
if (!string.IsNullOrEmpty(newStringValue))
{
property.stringValue = newStringValue;
serializedObject.ApplyModifiedProperties();
}
}
GUIContent gc = null;
bool emptyString = string.IsNullOrEmpty(property.stringValue);
using (new EditorGUI.DisabledScope(emptyString))
{
if (emptyString)
{
gc = EditorGUIUtility.TrTextContent("Not selected.");
}
else
{
gc = EditorGUIUtility.TempContent(property.stringValue);
}
EditorGUI.BeginChangeCheck();
GUILayoutOption[] options = { GUILayout.Width(32), GUILayout.ExpandWidth(true) };
string modifiedString = EditorGUILayout.TextArea(gc.text, options);
if (EditorGUI.EndChangeCheck())
{
if (string.IsNullOrEmpty(modifiedString))
{
property.stringValue = "";
serializedObject.ApplyModifiedProperties();
GUI.FocusControl("");
}
}
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
}
internal static bool BuildPathBoxButton(SerializedProperty prop, string uiString, string directory)
{
return BuildPathBoxButton(prop, uiString, directory, null);
}
internal static bool BuildPathBoxButton(SerializedProperty prop, string uiString, string directory, Action onSelect)
{
float h = EditorGUI.kSingleLineHeight;
float kLabelFloatMinW = EditorGUI.kLabelW + EditorGUIUtility.fieldWidth + EditorGUI.kSpacing;
float kLabelFloatMaxW = EditorGUI.kLabelW + EditorGUIUtility.fieldWidth + EditorGUI.kSpacing;
Rect r = GUILayoutUtility.GetRect(kLabelFloatMinW, kLabelFloatMaxW, h, h, EditorStyles.layerMaskField, null);
float labelWidth = EditorGUIUtility.labelWidth;
Rect buttonRect = new Rect(r.x + EditorGUI.indent, r.y, labelWidth - EditorGUI.indent, r.height);
Rect fieldRect = new Rect(r.x + labelWidth, r.y, r.width - labelWidth, r.height);
string display = (prop.stringValue.Length == 0) ? "Not selected." : prop.stringValue;
EditorGUI.TextArea(fieldRect, display, EditorStyles.label);
bool changed = false;
if (GUI.Button(buttonRect, EditorGUIUtility.TextContent(uiString)))
{
string prevVal = prop.stringValue;
string path = EditorUtility.OpenFolderPanel(EditorGUIUtility.TextContent(uiString).text, directory, "");
string relPath = FileUtil.GetProjectRelativePath(path);
prop.stringValue = (relPath != string.Empty) ? relPath : path;
changed = (prop.stringValue != prevVal);
if (onSelect != null)
onSelect();
prop.serializedObject.ApplyModifiedProperties();
}
return changed;
}
internal static bool BuildFileBoxButton(SerializedProperty prop, string uiString, string directory, string ext)
{
return BuildFileBoxButton(prop, uiString, directory, ext, null);
}
internal static bool BuildFileBoxButton(SerializedProperty prop, string uiString, string directory,
string ext, Action onSelect)
{
bool changed = false;
using (var vertical = new EditorGUILayout.VerticalScope())
using (new EditorGUI.PropertyScope(vertical.rect, GUIContent.none, prop))
{
float h = EditorGUI.kSingleLineHeight;
float kLabelFloatMinW = EditorGUI.kLabelW + EditorGUIUtility.fieldWidth + EditorGUI.kSpacing;
float kLabelFloatMaxW = EditorGUI.kLabelW + EditorGUIUtility.fieldWidth + EditorGUI.kSpacing;
Rect r = GUILayoutUtility.GetRect(kLabelFloatMinW, kLabelFloatMaxW, h, h, EditorStyles.layerMaskField, null);
float labelWidth = EditorGUIUtility.labelWidth;
Rect buttonRect = new Rect(r.x + EditorGUI.indent, r.y, labelWidth - EditorGUI.indent, r.height);
Rect fieldRect = new Rect(r.x + labelWidth, r.y, r.width - labelWidth, r.height);
string display = (prop.stringValue.Length == 0) ? "Not selected." : prop.stringValue;
EditorGUI.TextArea(fieldRect, display, EditorStyles.label);
if (GUI.Button(buttonRect, EditorGUIUtility.TextContent(uiString)))
{
string prevVal = prop.stringValue;
string path = EditorUtility.OpenFilePanel(EditorGUIUtility.TextContent(uiString).text, directory, ext);
string relPath = FileUtil.GetProjectRelativePath(path);
prop.stringValue = (relPath != string.Empty) ? relPath : path;
changed = (prop.stringValue != prevVal);
if (onSelect != null)
onSelect();
prop.serializedObject.ApplyModifiedProperties();
}
}
return changed;
}
public void PublishSectionGUI(BuildPlatform platform, ISettingEditorExtension settingsExtension, int sectionIndex = 5)
{
if (platform.namedBuildTarget != NamedBuildTarget.WindowsStoreApps &&
!(settingsExtension != null && settingsExtension.HasPublishSection()))
return;
if (BeginSettingsBox(sectionIndex, SettingsContent.publishingSettingsTitle))
{
float h = EditorGUI.kSingleLineHeight;
float kLabelFloatMinW = EditorGUI.kLabelW + EditorGUIUtility.fieldWidth + EditorGUI.kSpacing;
float kLabelFloatMaxW = EditorGUI.kLabelW + EditorGUIUtility.fieldWidth + EditorGUI.kSpacing;
if (settingsExtension != null)
{
settingsExtension.PublishSectionGUI(h, kLabelFloatMinW, kLabelFloatMaxW);
}
}
EndSettingsBox();
}
protected override bool ShouldHideOpenButton()
{
return true;
}
[SettingsProvider]
internal static SettingsProvider CreateProjectSettingsProvider()
{
var provider = AssetSettingsProvider.CreateProviderFromAssetPath(
"Project/Player", "ProjectSettings/ProjectSettings.asset",
SettingsProvider.GetSearchKeywordsFromGUIContentProperties<SettingsContent>());
provider.activateHandler = (searchContext, rootElement) =>
{
var playerSettingsProvider = provider.settingsEditor as PlayerSettingsEditor;
if (playerSettingsProvider != null)
{
playerSettingsProvider.SetValueChangeListeners(provider.Repaint);
playerSettingsProvider.splashScreenEditor.SetValueChangeListeners(provider.Repaint);
}
};
return provider;
}
void InitReorderableScriptingDefineSymbolsList(NamedBuildTarget namedBuildTarget)
{
// Get Scripting Define Symbols data
string defines = GetScriptingDefineSymbolsForGroup(namedBuildTarget);
scriptingDefinesList = new List<string>(ScriptingDefinesHelper.ConvertScriptingDefineStringToArray(serializedScriptingDefines));
// Initialize Reorderable List
scriptingDefineSymbolsList = new ReorderableList(scriptingDefinesList, typeof(string), true, true, true, true);
scriptingDefineSymbolsList.drawElementCallback = (rect, index, isActive, isFocused) => DrawTextField(rect, index);
scriptingDefineSymbolsList.drawHeaderCallback = (rect) => DrawScriptingDefinesHeaderCallback(rect);
scriptingDefineSymbolsList.onAddCallback = AddScriptingDefineCallback;
scriptingDefineSymbolsList.onRemoveCallback = RemoveScriptingDefineCallback;
scriptingDefineSymbolsList.onChangedCallback = SetScriptingDefinesListDirty;
}
void UpdateScriptingDefineSymbolsLists()
{
scriptingDefinesList = new List<string>(ScriptingDefinesHelper.ConvertScriptingDefineStringToArray(serializedScriptingDefines));
scriptingDefineSymbolsList.list = scriptingDefinesList;
scriptingDefineSymbolsList.DoLayoutList();
hasScriptingDefinesBeenModified = false;
}
void InitReorderableAdditionalCompilerArgumentsList(NamedBuildTarget namedBuildTarget)
{
additionalCompilerArgumentsList = new List<string>(serializedAdditionalCompilerArguments);
additionalCompilerArgumentsReorderableList = new ReorderableList(additionalCompilerArgumentsList, typeof(string), true, true, true, true);
additionalCompilerArgumentsReorderableList.drawElementCallback = (rect, index, isActive, isFocused) => DrawTextFieldAdditionalCompilerArguments(rect, index);
additionalCompilerArgumentsReorderableList.drawHeaderCallback = (rect) => GUI.Label(rect, SettingsContent.additionalCompilerArguments, EditorStyles.label);
additionalCompilerArgumentsReorderableList.onAddCallback = AddAdditionalCompilerArgumentCallback;
additionalCompilerArgumentsReorderableList.onRemoveCallback = RemoveAdditionalCompilerArgumentCallback;
additionalCompilerArgumentsReorderableList.onChangedCallback = SetAdditionalCompilerArgumentListDirty;
}
void UpdateAdditionalCompilerArgumentsLists()
{
additionalCompilerArgumentsList = new List<string>(serializedAdditionalCompilerArguments);
additionalCompilerArgumentsReorderableList.list = additionalCompilerArgumentsList;
additionalCompilerArgumentsReorderableList.DoLayoutList();
hasAdditionalCompilerArgumentsBeenModified = false;
}
private struct PlayerSettingsBox
{
public MethodInfo mi;
public GUIContent title;
public int order;
public string TargetName;
public PlayerSettingsBox(MethodInfo mi, string targetName, string title, int order)
{
this.mi = mi;
this.title = EditorGUIUtility.TrTextContent(title);
this.order = order;
this.TargetName = targetName;
}
};
private List<PlayerSettingsBox> m_boxes;
private PlayerSettingsSectionAttribute GetSectionAttribute(MethodInfo mi)
{
foreach (var attr in mi.GetCustomAttributes())
{
if (attr is PlayerSettingsSectionAttribute)
return (PlayerSettingsSectionAttribute)attr;
}
return null;
}
private bool IsValidSectionSetting(MethodInfo mi)
{
if (!mi.IsStatic)
{
Debug.LogError($"Method {mi.Name} with attribute PlayerSettingsSection must be static.");
return false;
}
if (mi.IsGenericMethod || mi.IsGenericMethodDefinition)
{
Debug.LogError($"Method {mi.Name} with attribute PlayerSettingsSection cannot be generic.");
return false;
}
if (mi.GetParameters().Length != 0)
{
Debug.LogError($"Method {mi.Name} with attribute PlayerSettingsSection does not have the correct signature, expected: static void {mi.Name}()");
return false;
}
return true;
}
private void FindPlayerSettingsAttributeSections()
{
m_boxes = new List<PlayerSettingsBox>();
foreach (var method in TypeCache.GetMethodsWithAttribute<PlayerSettingsSectionAttribute>())
{
if (IsValidSectionSetting(method))
{
PlayerSettingsSectionAttribute attr = GetSectionAttribute(method);
m_boxes.Add(new PlayerSettingsBox(method, attr.TargetName, attr.Title, attr.Order));
}
}
m_boxes.Sort((a, b) => a.order.CompareTo(b.order));
}
}
}
| UnityCsReference/Editor/Mono/Inspector/PlayerSettingsEditor/PlayerSettingsEditor.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/PlayerSettingsEditor/PlayerSettingsEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 96114
} | 325 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
using UnityEngine.Rendering;
using Object = UnityEngine.Object;
namespace UnityEditor
{
/// <summary>
/// Provides a display for a <see cref="EditorGUI.ObjectField"/> and prompts the user to confirm the change.
/// </summary>
public sealed partial class EditorGUI
{
static class RenderPipelineAssetSelectorStyles
{
public static readonly GUIContent renderPipeLabel = EditorGUIUtility.TrTextContent("Scriptable Render Pipeline");
public static string renderPipeChangedWarning => LocalizationDatabase.GetLocalizedString("Changing this render pipeline asset may take a significant amount of time.");
public static string renderPipeChangedTitleBox => LocalizationDatabase.GetLocalizedString("Changing Render Pipeline");
public static string renderPipeChangedConfirmation => LocalizationDatabase.GetLocalizedString("Continue");
public static string cancelLabel => LocalizationDatabase.GetLocalizedString("Cancel");
}
static void PromptConfirmation(SerializedObject serializedObject, SerializedProperty serializedProperty, Object selectedRenderPipelineAsset)
{
if (selectedRenderPipelineAsset == serializedProperty.objectReferenceValue)
return;
if (EditorUtility.DisplayDialog(RenderPipelineAssetSelectorStyles.renderPipeChangedTitleBox, RenderPipelineAssetSelectorStyles.renderPipeChangedWarning, RenderPipelineAssetSelectorStyles.renderPipeChangedConfirmation, RenderPipelineAssetSelectorStyles.cancelLabel))
{
serializedProperty.objectReferenceValue = selectedRenderPipelineAsset;
serializedObject.ApplyModifiedProperties();
}
}
/// <summary>
/// Draws the object field and, if the user attempts to change the value, asks the user for confirmation.
/// </summary>
/// <param name="content">The label.</param>
/// <param name="serializedObject">The <see cref="SerializedObject"/> that holds the <see cref="SerializedProperty"/> with the new render pipeline asset.</param>
/// <param name="serializedProperty">The <see cref="SerializedProperty"/> to modify with the new render pipeline asset.</param>
internal static void RenderPipelineAssetField(GUIContent content, SerializedObject serializedObject, SerializedProperty serializedProperty)
{
using (new EditorGUILayout.HorizontalScope())
{
EditorGUILayout.PrefixLabel(content);
RenderPipelineAssetField(serializedObject, serializedProperty);
}
}
private static bool s_ObjectSelectorClosed = false;
private static Object s_LastPickedObject = null;
/// <summary>
/// Draws the object field and, if the user attempts to change the value, asks the user for confirmation.
/// </summary>
/// <param name="serializedObject">The <see cref="SerializedObject"/> that holds the <see cref="SerializedProperty"/> with the new render pipeline asset.</param>
/// <param name="serializedProperty">The <see cref="SerializedProperty"/> to modify with the new render pipeline asset.</param>
internal static void RenderPipelineAssetField(SerializedObject serializedObject, SerializedProperty serializedProperty)
{
Rect renderLoopRect = EditorGUILayout.GetControlRect(true, EditorGUI.GetPropertyHeight(serializedProperty));
EditorGUI.BeginProperty(renderLoopRect, RenderPipelineAssetSelectorStyles.renderPipeLabel, serializedProperty);
int id = GUIUtility.GetControlID(s_ObjectFieldHash, FocusType.Keyboard, renderLoopRect);
var selectedRenderPipelineAsset = DoObjectField(
position: IndentedRect(renderLoopRect),
dropRect: IndentedRect(renderLoopRect),
id: id,
obj: serializedProperty.objectReferenceValue,
objBeingEdited: null,
objType: typeof(RenderPipelineAsset),
additionalType: null,
property: null,
validator: null,
allowSceneObjects: false,
style: EditorStyles.objectField,
onObjectSelectorClosed: obj =>
{
if (ObjectSelector.SelectionCanceled()) return;
s_ObjectSelectorClosed = true;
s_LastPickedObject = obj;
});
if (s_ObjectSelectorClosed)
{
s_ObjectSelectorClosed = false;
PromptConfirmation(serializedObject, serializedProperty, s_LastPickedObject);
}
else if (!ObjectSelector.isVisible) // Drag and drop
{
PromptConfirmation(serializedObject, serializedProperty, selectedRenderPipelineAsset);
}
EditorGUI.EndProperty();
}
}
}
| UnityCsReference/Editor/Mono/Inspector/RenderPipelineAssetSelector.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/RenderPipelineAssetSelector.cs",
"repo_id": "UnityCsReference",
"token_count": 1958
} | 326 |
// 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 System.Linq;
namespace UnityEditor
{
[CustomEditor(typeof(ShaderVariantCollection))]
internal class ShaderVariantCollectionInspector : Editor
{
private class Styles
{
public static readonly GUIContent iconAdd = EditorGUIUtility.TrIconContent("Toolbar Plus", "Add variant");
public static readonly GUIContent iconRemove = EditorGUIUtility.TrIconContent("Toolbar Minus", "Remove entry");
public static readonly GUIStyle invisibleButton = "InvisibleButton";
}
SerializedProperty m_Shaders;
public virtual void OnEnable()
{
m_Shaders = serializedObject.FindProperty("m_Shaders");
}
static Rect GetAddRemoveButtonRect(Rect r)
{
var buttonSize = Styles.invisibleButton.CalcSize(Styles.iconRemove);
return new Rect(r.xMax - buttonSize.x, r.y + (int)(r.height / 2 - buttonSize.y / 2), buttonSize.x, buttonSize.y);
}
// Show window to select shader variants
void DisplayAddVariantsWindow(Shader shader, ShaderVariantCollection collection)
{
var data = new AddShaderVariantWindow.PopupData();
data.shader = shader;
data.collection = collection;
AddShaderVariantWindow.ShowAddVariantWindow(data);
GUIUtility.ExitGUI();
}
void DrawShaderEntry(int shaderIndex)
{
var entryProp = m_Shaders.GetArrayElementAtIndex(shaderIndex);
Shader shader = (Shader)entryProp.FindPropertyRelative("first").objectReferenceValue;
// Shader name and button to remove it
var variantsProp = entryProp.FindPropertyRelative("second.variants");
using (new GUILayout.HorizontalScope())
{
Rect rowRect = GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.boldLabel);
Rect minusRect = GetAddRemoveButtonRect(rowRect);
rowRect.xMax = minusRect.x;
GUI.Label(rowRect, shader == null ? "<MISSING SHADER>" : shader.name, EditorStyles.boldLabel);
if (GUI.Button(minusRect, Styles.iconRemove, Styles.invisibleButton))
{
m_Shaders.DeleteArrayElementAtIndex(shaderIndex);
return;
}
}
// Variants for this shader
for (var i = 0; i < variantsProp.arraySize; ++i)
{
var prop = variantsProp.GetArrayElementAtIndex(i);
var keywords = prop.FindPropertyRelative("keywords").stringValue;
if (string.IsNullOrEmpty(keywords))
keywords = "<no keywords>";
var passType = (UnityEngine.Rendering.PassType)prop.FindPropertyRelative("passType").intValue;
Rect rowRect = GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.miniLabel);
Rect minusRect = GetAddRemoveButtonRect(rowRect);
// Variant entry with button to remove it
rowRect.xMax = minusRect.x;
GUI.Label(rowRect, passType + " " + keywords, EditorStyles.miniLabel);
if (GUI.Button(minusRect, Styles.iconRemove, Styles.invisibleButton))
{
variantsProp.DeleteArrayElementAtIndex(i);
}
}
// Add variant button
Rect addRowRect = GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.miniLabel);
Rect plusRect = GetAddRemoveButtonRect(addRowRect);
if (shader != null && GUI.Button(plusRect, Styles.iconAdd, Styles.invisibleButton))
{
DisplayAddVariantsWindow(shader, target as ShaderVariantCollection);
}
}
public override void OnInspectorGUI()
{
serializedObject.Update();
for (var i = 0; i < m_Shaders.arraySize; ++i)
{
DrawShaderEntry(i);
}
// Button to add a new shader to collection
if (GUILayout.Button("Add shader"))
{
// Show object selector
ObjectSelector.get.Show(null, typeof(Shader), null, false);
ObjectSelector.get.objectSelectorID = "ShaderVariantSelector".GetHashCode();
GUIUtility.ExitGUI();
}
if (Event.current.type == EventType.ExecuteCommand)
{
// New shader picked in object selector; add it to the collection
if (Event.current.commandName == ObjectSelector.ObjectSelectorClosedCommand && ObjectSelector.get.objectSelectorID == "ShaderVariantSelector".GetHashCode())
{
var newShader = ObjectSelector.GetCurrentObject() as Shader;
if (newShader != null)
{
ShaderUtil.AddNewShaderToCollection(newShader, target as ShaderVariantCollection);
}
Event.current.Use();
GUIUtility.ExitGUI();
}
}
serializedObject.ApplyModifiedProperties();
}
}
// Utility window for selecting shader variants to add.
// Some shaders (Standard, SpeedTree etc.) have massive amounts of variants
// (e.g. about 30000), and approaches like "display a popup menu with all of them"
// don't work.
internal class AddShaderVariantWindow : EditorWindow
{
internal class PopupData
{
public Shader shader;
public ShaderVariantCollection collection;
}
class Styles
{
public static readonly GUIStyle sMenuItem = "MenuItem";
public static readonly GUIStyle sSeparator = "sv_iconselector_sep";
}
const float kMargin = 2;
const float kSpaceHeight = 6;
const float kSeparatorHeight = 3;
private const float kMinWindowWidth = 400;
static readonly float kMiscUIHeight =
5 * EditorGUI.kSingleLineHeight +
kSeparatorHeight * 2 +
kSpaceHeight * 5 +
kMargin * 2;
private static readonly float kMinWindowHeight = 9 * EditorGUI.kSingleLineHeight + kMiscUIHeight;
PopupData m_Data;
List<string> m_SelectedKeywords;
List<string> m_AvailableKeywords;
List<int> m_SelectedVariants; // Indices of variants currently selected for adding
int[] m_FilteredVariantTypes;
string[][] m_FilteredVariantKeywords;
int m_MaxVisibleVariants;
int m_NumFilteredVariants;
public AddShaderVariantWindow()
{
position = new Rect(100, 100, kMinWindowWidth * 1.5f, kMinWindowHeight * 1.5f);
minSize = new Vector2(kMinWindowWidth, kMinWindowHeight);
wantsMouseMove = true;
}
private void Initialize(PopupData data)
{
m_Data = data;
m_SelectedKeywords = new List<string>();
m_AvailableKeywords = new List<string>();
m_SelectedVariants = new List<int>();
ApplyKeywordFilter();
}
public static void ShowAddVariantWindow(PopupData data)
{
var w = EditorWindow.GetWindow<AddShaderVariantWindow>(true, "Add shader " + data.shader.name + " variants to collection");
w.Initialize(data);
w.m_Parent.window.m_DontSaveToLayout = true;
}
void ApplyKeywordFilter()
{
m_MaxVisibleVariants = (int)(CalcVerticalSpaceForVariants() / EditorGUI.kSingleLineHeight);
string[] keywordLists, remainingKeywords;
m_FilteredVariantTypes = new int[m_MaxVisibleVariants];
ShaderUtil.GetShaderVariantEntriesFiltered(m_Data.shader,
m_MaxVisibleVariants + 1, // query one more to know if we're truncating
m_SelectedKeywords.ToArray(),
m_Data.collection,
out m_FilteredVariantTypes,
out keywordLists,
out remainingKeywords);
m_NumFilteredVariants = m_FilteredVariantTypes.Length;
m_FilteredVariantKeywords = new string[m_NumFilteredVariants][];
for (var i = 0; i < m_NumFilteredVariants; ++i)
{
m_FilteredVariantKeywords[i] = keywordLists[i].Split(' ');
}
m_AvailableKeywords.Clear();
m_AvailableKeywords.InsertRange(0, remainingKeywords);
m_AvailableKeywords.Sort();
}
public void OnGUI()
{
// Objects became deleted while our window was showing? Close.
if (m_Data == null || m_Data.shader == null || m_Data.collection == null)
{
Close();
return;
}
// We do not use the layout event
if (Event.current.type == EventType.Layout)
return;
Rect rect = new Rect(0, 0, position.width, position.height);
Draw(rect);
// Repaint on mouse move so we get hover highlights in menu item rows
if (Event.current.type == EventType.MouseMove)
Repaint();
}
private bool KeywordButton(Rect buttonRect, string k, Vector2 areaSize)
{
// If we can't fit all buttons (shader has *a lot* of keywords) and would start clipping,
// do display the partially clipped ones with some transparency.
var oldColor = GUI.color;
if (buttonRect.yMax > areaSize.y)
GUI.color = new Color(1, 1, 1, 0.4f);
var result = GUI.Button(buttonRect, EditorGUIUtility.TempContent(k), EditorStyles.miniButton);
GUI.color = oldColor;
return result;
}
float CalcVerticalSpaceForKeywords()
{
return Mathf.Floor((position.height - kMiscUIHeight) / 4);
}
float CalcVerticalSpaceForVariants()
{
return (position.height - kMiscUIHeight) / 2;
}
void DrawKeywordsList(ref Rect rect, List<string> keywords, bool clickingAddsToSelected)
{
rect.height = CalcVerticalSpaceForKeywords();
var displayKeywords = keywords.Select(k => k.ToLowerInvariant()).ToList();
GUI.BeginGroup(rect);
Rect indentRect = new Rect(4, 0, rect.width, rect.height);
var layoutRects = EditorGUIUtility.GetFlowLayoutedRects(indentRect, EditorStyles.miniButton, 2, 2, displayKeywords);
for (var i = 0; i < displayKeywords.Count; ++i)
{
if (KeywordButton(layoutRects[i], displayKeywords[i], rect.size))
{
if (clickingAddsToSelected)
{
if (!m_SelectedKeywords.Contains(keywords[i]))
{
m_SelectedKeywords.Add(keywords[i]);
m_SelectedKeywords.Sort();
m_AvailableKeywords.Remove(keywords[i]);
}
}
else
{
m_AvailableKeywords.Add(keywords[i]);
m_SelectedKeywords.Remove(keywords[i]);
}
ApplyKeywordFilter();
GUIUtility.ExitGUI();
}
}
GUI.EndGroup();
rect.y += rect.height;
}
void DrawSectionHeader(ref Rect rect, string titleString, bool separator)
{
// space
rect.y += kSpaceHeight;
// separator
if (separator)
{
rect.height = kSeparatorHeight;
GUI.Label(rect, GUIContent.none, Styles.sSeparator);
rect.y += rect.height;
}
// label
rect.height = EditorGUI.kSingleLineHeight;
GUI.Label(rect, titleString);
rect.y += rect.height;
}
private void Draw(Rect windowRect)
{
var rect = new Rect(kMargin, kMargin, windowRect.width - kMargin * 2, EditorGUI.kSingleLineHeight);
DrawSectionHeader(ref rect, "Pick shader keywords to narrow down variant list:", false);
DrawKeywordsList(ref rect, m_AvailableKeywords, true);
DrawSectionHeader(ref rect, "Selected keywords:", true);
DrawKeywordsList(ref rect, m_SelectedKeywords, false);
DrawSectionHeader(ref rect, "Shader variants with these keywords (click to select):", true);
if (m_NumFilteredVariants > 0)
{
int maxFilteredLength = (int)(CalcVerticalSpaceForVariants() / EditorGUI.kSingleLineHeight);
if (maxFilteredLength > m_MaxVisibleVariants) // Query data again if we have bigger window than at last query
ApplyKeywordFilter();
// Display first N variants (don't want to display thousands of them if filter is not narrow)
for (var i = 0; i < Mathf.Min(m_NumFilteredVariants, maxFilteredLength); ++i)
{
var passType = (UnityEngine.Rendering.PassType)m_FilteredVariantTypes[i];
var wasSelected = m_SelectedVariants.Contains(i);
var keywordString = string.IsNullOrEmpty(m_FilteredVariantKeywords[i][0]) ? "<no keywords>" : string.Join(" ", m_FilteredVariantKeywords[i]);
var displayString = passType + " " + keywordString.ToLowerInvariant();
var isSelected = GUI.Toggle(rect, wasSelected, displayString, Styles.sMenuItem);
rect.y += rect.height;
if (isSelected && !wasSelected)
m_SelectedVariants.Add(i);
else if (!isSelected && wasSelected)
m_SelectedVariants.Remove(i);
}
// show how many variants we skipped due to filter not being narrow enough
if (m_NumFilteredVariants > maxFilteredLength)
{
GUI.Label(rect, "List of variants was cropped. Pick further keywords to narrow the selection.", EditorStyles.miniLabel);
rect.y += rect.height;
}
}
else
{
GUI.Label(rect, "No variants with these keywords");
rect.y += rect.height;
}
// Button to add them at the bottom of popup
rect.y = windowRect.height - kMargin - kSpaceHeight - EditorGUI.kSingleLineHeight;
rect.height = EditorGUI.kSingleLineHeight;
// Disable button if no variants selected
using (new EditorGUI.DisabledScope(m_SelectedVariants.Count == 0))
{
if (GUI.Button(rect, string.Format("Add {0} selected variants", m_SelectedVariants.Count)))
{
// Add the selected variants
Undo.RecordObject(m_Data.collection, "Add variant");
for (var i = 0; i < m_SelectedVariants.Count; ++i)
{
var index = m_SelectedVariants[i];
var variant = new ShaderVariantCollection.ShaderVariant(m_Data.shader, (UnityEngine.Rendering.PassType)m_FilteredVariantTypes[index], m_FilteredVariantKeywords[index]);
m_Data.collection.Add(variant);
}
// Close our popup
Close();
GUIUtility.ExitGUI();
}
}
}
}
}
| UnityCsReference/Editor/Mono/Inspector/ShaderVariantCollectionInspector.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/ShaderVariantCollectionInspector.cs",
"repo_id": "UnityCsReference",
"token_count": 7729
} | 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 UnityEditor.Presets;
using UnityEditor.Rendering;
using UnityEditor.UIElements;
using UnityEditor.UIElements.ProjectSettings;
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.UIElements;
using Button = UnityEngine.UIElements.Button;
using Debug = System.Diagnostics.Debug;
namespace UnityEditor
{
[CustomEditor(typeof(TagManager))]
internal class TagManagerInspector : ProjectSettingsBaseEditor
{
const string k_ProjectPath = "Project/Tags and Layers";
const string k_AssetPath = "ProjectSettings/TagManager.asset";
const string k_BodyTemplate = "UXML/ProjectSettings/TagManagerInspector-Body.uxml";
const string k_ProjectSettingsStyleSheet = "StyleSheets/ProjectSettings/ProjectSettingsCommon.uss";
internal override string targetTitle => "Tags & Layers";
bool isEditable => AssetDatabase.IsOpenForEdit(k_AssetPath, StatusQueryOptions.UseCachedIfPossible);
static InitialExpansionState s_InitialExpansionState = InitialExpansionState.None;
internal enum InitialExpansionState
{
None = 0,
Tags = 1,
Layers = 2,
SortingLayers = 3,
RenderingLayers = 4
}
internal class Styles
{
public static GUIContent tags = EditorGUIUtility.TrTextContent("Tags");
public static GUIContent sortingLayers = EditorGUIUtility.TrTextContent("Sorting Layers");
public static GUIContent layers = EditorGUIUtility.TrTextContent("Layers");
public static GUIContent renderingLayers = EditorGUIUtility.TrTextContent("Rendering Layers");
public static float elementHeight = EditorGUIUtility.singleLineHeight + 2;
public const float headerListHeight = 3;
public const string tagListElement = "tags-and-layer-list__element";
public const string helperBox = "tags-and-layer-list__helper-box";
}
public TagManager tagManager => target as TagManager;
internal static void ShowWithInitialExpansion(InitialExpansionState initialExpansionState)
{
s_InitialExpansionState = initialExpansionState;
Selection.activeObject = EditorApplication.tagManager;
}
#region Sorting Layers
bool CanEditSortLayerEntry(int index)
{
if (index < 0 || index >= tagManager.GetSortingLayerCount())
return false;
return !tagManager.IsSortingLayerDefault(index);
}
#endregion
public override VisualElement CreateInspectorGUI()
{
var visualTreeAsset = EditorGUIUtility.Load(k_BodyTemplate) as VisualTreeAsset;
var content = visualTreeAsset.Instantiate();
var tagsProperty = serializedObject.FindProperty("tags");
var sortingLayersProperty = serializedObject.FindProperty("m_SortingLayers");
var layersProperty = serializedObject.FindProperty("layers");
var renderingLayersProperty = serializedObject.FindProperty("m_RenderingLayers");
Debug.Assert(layersProperty.arraySize == 32);
Debug.Assert(renderingLayersProperty.arraySize == 32);
var tagsList = SetupTags(content, tagsProperty);
var sortingLayers = SetupSortingLayers(content, sortingLayersProperty);
var layers = SetupLayers(content, layersProperty);
var renderingLayers = SetupRenderingLayers(content, renderingLayersProperty);
if (s_InitialExpansionState != InitialExpansionState.None)
{
tagsProperty.isExpanded = false;
sortingLayersProperty.isExpanded = false;
layersProperty.isExpanded = false;
renderingLayersProperty.isExpanded = false;
switch (s_InitialExpansionState)
{
case InitialExpansionState.Tags:
tagsProperty.isExpanded = true;
tagsList.Q<Foldout>().value = true;
break;
case InitialExpansionState.SortingLayers:
sortingLayersProperty.isExpanded = true;
sortingLayers.Q<Foldout>().value = true;
break;
case InitialExpansionState.Layers:
layersProperty.isExpanded = true;
layers.Q<Foldout>().value = true;
break;
case InitialExpansionState.RenderingLayers:
renderingLayersProperty.isExpanded = true;
renderingLayers.Q<Foldout>().value = true;
break;
}
s_InitialExpansionState = InitialExpansionState.None;
}
content.Bind(serializedObject);
return content;
}
VisualElement SetupTags(VisualElement content, SerializedProperty tagsProperty)
{
var tagsList = content.Q<ListView>("Tags");
tagsList.fixedItemHeight = Styles.elementHeight;
tagsList.headerTitle = Styles.tags.text;
tagsList.makeItem = () =>
{
var tagListElement = new VisualElement { classList = { Styles.tagListElement } };
tagListElement.Add(new Label()
{
name = "Title",
classList = { "tag-list__element__title" }
});
tagListElement.Add(new Label
{
name = "Value"
});
return tagListElement;
};
tagsList.bindItem = (ve, index) =>
{
ve.Q<Label>("Title").text = $"Tag {index}";
ve.Q<Label>("Value").text = index < tagsProperty.arraySize
? tagsProperty.GetArrayElementAtIndex(index).stringValue
: "Unknown";
};
tagsList.onAdd += (listView) =>
{
var addButton = listView.Q<Button>("unity-list-view__add-button");
PopupWindow.Show(addButton.worldBound, new EnterTagNamePopup(tagsProperty, s =>
{
tagManager.AddTag(s);
serializedObject.ApplyModifiedProperties();
}));
};
tagsList.onRemove += (listView) =>
{
if (tagsProperty.arraySize == 0)
return;
var indexForRemoval = listView.selectedIndex;
if (indexForRemoval == -1)
indexForRemoval = tagsProperty.arraySize - 1;
var tag = tagsProperty.GetArrayElementAtIndex(indexForRemoval).stringValue;
if (string.IsNullOrEmpty(tag))
return;
var isPreset = Preset.IsEditorTargetAPreset(target);
if (!isPreset)
{
var go = GameObject.FindWithTag(tag);
if (go != null)
{
EditorUtility.DisplayDialog("Error", "Can't remove this tag because it is being used by " + go.name, "OK");
return;
}
}
tagManager.RemoveTag(tag);
serializedObject.ApplyModifiedProperties();
};
//TextFields in Array are not bind correctly so we need to refresh them manually
content.TrackPropertyValue(tagsProperty, sp => tagsList.RefreshItems());
return tagsList;
}
VisualElement SetupSortingLayers(VisualElement content, SerializedProperty sortingLayersProperty)
{
var sortingLayers = content.Q<ListView>("SortingLayers");
sortingLayers.fixedItemHeight = Styles.elementHeight;
sortingLayers.headerTitle = Styles.sortingLayers.text;
sortingLayers.makeItem = () => new TextField
{
classList = { Styles.tagListElement }
};
void SortingLayersChanged(ChangeEvent<string> evt)
{
if (evt.target is not TextField textField)
return;
evt.StopPropagation();
var index = (int)textField.userData;
tagManager.SetSortingLayerName(index, evt.newValue);
serializedObject.ApplyModifiedProperties();
}
sortingLayers.bindItem = (ve, index) =>
{
var textField = ve as TextField;
textField.label = $"Layer {index}";
textField.SetValueWithoutNotify(tagManager.GetSortingLayerName(index));
var isEnable = isEditable && CanEditSortLayerEntry(index);
textField.SetEnabled(isEnable);
textField.userData = index;
textField.RegisterValueChangedCallback(SortingLayersChanged);
};
sortingLayers.unbindItem = (ve, index) =>
{
var textField = ve as TextField;
textField.UnregisterValueChangedCallback(SortingLayersChanged);
};
sortingLayers.itemIndexChanged += (prev, next) =>
{
serializedObject.ApplyModifiedProperties();
tagManager.UpdateSortingLayersOrder();
};
sortingLayers.onAdd += (listView) =>
{
serializedObject.ApplyModifiedProperties();
tagManager.AddSortingLayer();
serializedObject.Update();
listView.selectedIndex = tagManager.GetSortingLayerCount() - 1; // select just added one
if (SortingLayer.onLayerAdded != null)
SortingLayer.onLayerAdded(SortingLayer.layers[listView.selectedIndex]);
};
sortingLayers.onRemove += (listView) =>
{
if (tagManager.GetSortingLayerCount() == 0 || !CanEditSortLayerEntry(listView.selectedIndex))
return;
if (SortingLayer.onLayerRemoved != null)
SortingLayer.onLayerRemoved(SortingLayer.layers[listView.selectedIndex]);
listView.viewController.RemoveItem(listView.selectedIndex);
serializedObject.ApplyModifiedProperties();
serializedObject.Update();
tagManager.UpdateSortingLayersOrder();
};
//TextFields in Array are not bind correctly so we need to refresh them manually
content.TrackPropertyValue(sortingLayersProperty, sp => sortingLayers.RefreshItems());
return sortingLayers;
}
VisualElement SetupLayers(VisualElement content, SerializedProperty layersProperty)
{
var layers = content.Q<ListView>("Layers");
layers.fixedItemHeight = Styles.elementHeight;
layers.headerTitle = Styles.layers.text;
layers.makeItem = () => new TextField
{
classList = { Styles.tagListElement }
};
void LayersChanged(ChangeEvent<string> evt)
{
if (evt.target is not TextField textField)
return;
evt.StopPropagation();
var index = (int)textField.userData;
layersProperty.GetArrayElementAtIndex(index).stringValue = evt.newValue;
serializedObject.ApplyModifiedProperties();
}
layers.bindItem = (ve, index) =>
{
// Layers up to 8 used to be reserved for Builtin Layers
// As layers with indices 3, 6 and 7 were empty,
// it was decided to change them to User Layers
// However, we cannot shift layers around so we need to explicitly handle
// the gap where layer index == 3 in the layer stack
var isUserLayer = index is > 5 or 3;
var editable = isEditable && isUserLayer;
var textField = ve as TextField;
var layerName = layersProperty.GetArrayElementAtIndex(index).stringValue;
textField.label = isUserLayer ? $" User Layer {index}" : $" Builtin Layer {index}";
textField.SetValueWithoutNotify(layerName);
textField.SetEnabled(editable);
textField.userData = index;
textField.RegisterValueChangedCallback(LayersChanged);
};
layers.unbindItem = (ve, index) =>
{
var textField = ve as TextField;
textField.UnregisterValueChangedCallback(LayersChanged);
};
//TextFields in Array are not bind correctly so we need to refresh them manually
content.TrackPropertyValue(layersProperty, sp => layers.RefreshItems());
return layers;
}
void UpdateAllowanceAndMessages(BaseListView listView)
{
var renderingLayerCount = tagManager.GetRenderingLayerCount();
var currentMaxRenderingLayerIndex = RenderPipelineEditorUtility.GetActiveMaxRenderingLayers();
listView.allowAdd = renderingLayerCount < currentMaxRenderingLayerIndex;
listView.allowRemove = !tagManager.IsIndexReservedForDefaultRenderingLayer(renderingLayerCount - 1);
var viewport = listView.Q<VisualElement>("unity-content-viewport");
viewport.Query<HelpBox>().Where(h => h.name == "MaximumSupportedRenderingLayers").ForEach(h => viewport.Remove(h));
var maxRenderingLayers = RenderPipelineEditorUtility.GetMaxRenderingLayersFromSettings();
AddInfoBoxesForMaximumValueRestriction(viewport, maxRenderingLayers);
AddWarningMessageForUnsupportedLayers(viewport, maxRenderingLayers);
}
void AddInfoBoxesForMaximumValueRestriction(VisualElement viewport, List<(int, string)> maxRenderingLayers)
{
for (var i = 0; i < maxRenderingLayers.Count; i++)
{
if (maxRenderingLayers[i].Item1 >= 32)
continue;
var message = $"Maximum supported rendering layers on {maxRenderingLayers[i].Item2} is {maxRenderingLayers[i].Item1}.";
AddHelperBoxToViewport(viewport, maxRenderingLayers, message, HelpBoxMessageType.Info);
}
}
void AddWarningMessageForUnsupportedLayers(VisualElement viewport, List<(int, string)> maxRenderingLayers)
{
for (var i = 0; i < maxRenderingLayers.Count; i++)
{
if (tagManager.GetRenderingLayerCount() <= maxRenderingLayers[i].Item1)
continue;
var message = $"One of the used Render Pipelines doesn't supports all defined Rendering Layers. Additional layers added due to other Render Pipelines will be ignored.";
AddHelperBoxToViewport(viewport, maxRenderingLayers, message, HelpBoxMessageType.Warning);
break;
}
}
static void AddHelperBoxToViewport(VisualElement viewport, List<(int, string)> maxRenderingLayers, string message, HelpBoxMessageType type)
{
var supportedLabel = new HelpBox(message, type)
{
name = "MaximumSupportedRenderingLayers",
classList = { Styles.helperBox }
};
viewport.Insert(0, supportedLabel);
}
VisualElement SetupRenderingLayers(VisualElement content, SerializedProperty renderingLayersProperty)
{
var renderingLayers = content.Q<ListView>("RenderingLayers");
renderingLayers.fixedItemHeight = Styles.elementHeight;
renderingLayers.headerTitle = Styles.renderingLayers.text;
renderingLayers.makeItem = () => new TextField
{
classList = { Styles.tagListElement }
};
void RenderingLayersChanged(ChangeEvent<string> evt)
{
if (evt.target is not TextField textField)
return;
evt.StopPropagation();
var index = (int)textField.userData;
renderingLayersProperty.GetArrayElementAtIndex(index).stringValue = evt.newValue;
serializedObject.ApplyModifiedProperties();
}
renderingLayers.bindItem = (ve, index) =>
{
var renderingLayerCount = tagManager.GetRenderingLayerCount();
if (index >= renderingLayerCount)
return;
var textField = ve as TextField;
textField.label = $"Layer {index}";
textField.SetValueWithoutNotify(tagManager.RenderingLayerToString(index));
var isEnabled = isEditable && !tagManager.IsIndexReservedForDefaultRenderingLayer(index);
textField.SetEnabled(isEnabled);
textField.userData = index;
textField.RegisterValueChangedCallback(RenderingLayersChanged);
};
renderingLayers.unbindItem = (ve, index) =>
{
var textField = ve as TextField;
textField.UnregisterValueChangedCallback(RenderingLayersChanged);
};
renderingLayers.onAdd += (listView) =>
{
var newIndex = tagManager.GetRenderingLayerCount();
tagManager.TryAddRenderingLayerName($"Layer {newIndex}");
serializedObject.ApplyModifiedProperties();
listView.selectedIndex = newIndex; // select just added one
UpdateAllowanceAndMessages(listView);
};
renderingLayers.selectionChanged += (item) =>
{
var index = renderingLayers.selectedIndex;
var lastIndex = tagManager.GetRenderingLayerCount() - 1;
renderingLayers.allowRemove = !tagManager.IsIndexReservedForDefaultRenderingLayer(index) && lastIndex == index;
};
renderingLayers.onRemove += (listView) =>
{
var lastIndex = tagManager.GetRenderingLayerCount() - 1;
if (tagManager.IsIndexReservedForDefaultRenderingLayer(lastIndex))
return;
listView.viewController.RemoveItem(lastIndex);
serializedObject.ApplyModifiedProperties();
listView.selectedIndex = lastIndex - 1; // select just added one
UpdateAllowanceAndMessages(listView);
};
UpdateAllowanceAndMessages(renderingLayers);
//TextFields in Array are not bind correctly so we need to refresh them manually
content.TrackPropertyValue(renderingLayersProperty, sp => renderingLayers.RefreshItems());
return renderingLayers;
}
[SettingsProvider]
static SettingsProvider CreateProjectSettingsProvider()
{
var provider = AssetSettingsProvider.CreateProviderFromAssetPath(k_ProjectPath, k_AssetPath, SettingsProvider.GetSearchKeywordsFromGUIContentProperties<Styles>());
provider.activateHandler = (text, root) =>
{
var serializedObject = provider.settingsEditor.serializedObject;
var titleBar = new ProjectSettingsTitleBar("Tags and Layers");
titleBar.Initialize(serializedObject);
var styleSheet = EditorGUIUtility.Load(k_ProjectSettingsStyleSheet) as StyleSheet;
root.styleSheets.Add(styleSheet);
root.Add(titleBar);
root.Add(provider.settingsEditor.CreateInspectorGUI());
};
return provider;
}
class EnterTagNamePopup : PopupWindowContent
{
public delegate void EnterDelegate(string str);
readonly EnterDelegate m_EnterCallback;
string m_NewTagName = "New tag";
bool m_NeedsFocus = true;
public EnterTagNamePopup(SerializedProperty tags, EnterDelegate callback)
{
m_EnterCallback = callback;
var existingTagNames = new List<string>();
for (var i = 0; i < tags.arraySize; i++)
{
var tagName = tags.GetArrayElementAtIndex(i).stringValue;
if (!string.IsNullOrEmpty(tagName))
existingTagNames.Add(tagName);
}
m_NewTagName = ObjectNames.GetUniqueName(existingTagNames.ToArray(), m_NewTagName);
}
public override Vector2 GetWindowSize() =>
new(400, EditorGUI.kSingleLineHeight * 2 + EditorGUI.kControlVerticalSpacing + 14);
public override void OnGUI(Rect windowRect)
{
GUILayout.Space(5);
var evt = Event.current;
var hitEnter = evt.type == EventType.KeyDown && evt.keyCode is KeyCode.Return or KeyCode.KeypadEnter;
GUI.SetNextControlName("TagName");
m_NewTagName = EditorGUILayout.TextField("New Tag Name", m_NewTagName);
if (m_NeedsFocus)
{
m_NeedsFocus = false;
EditorGUI.FocusTextInControl("TagName");
}
GUI.enabled = m_NewTagName.Length != 0;
var savePressed = GUILayout.Button("Save");
if (string.IsNullOrWhiteSpace(m_NewTagName) || (!savePressed && !hitEnter))
return;
m_EnterCallback(m_NewTagName);
editorWindow.Close();
}
}
}
}
| UnityCsReference/Editor/Mono/Inspector/TagManagerInspector.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/TagManagerInspector.cs",
"repo_id": "UnityCsReference",
"token_count": 10245
} | 328 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using UnityEditor.VersionControl;
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor
{
[CustomEditor(typeof(VersionControlSettings))]
internal class VersionControlSettingsProvider : ProjectSettingsBaseEditor
{
class Styles
{
public static GUIContent mode = new GUIContent("Mode");
public static GUIContent logLevel = new GUIContent("Log Level");
public static GUIContent automaticAdd = new GUIContent("Automatic Add",
"Automatically add newly created assets to version control.");
public static GUIContent smartMerge = new GUIContent("Smart merge");
public static GUIContent trackPackagesOutsideProject = new GUIContent("Version Packages Outside Project", "Tracks changes to packages that reside on disk outside of the project's root folder.");
public static GUIContent vcsConnect = new GUIContent("Connect");
public static GUIContent vcsReconnect = new GUIContent("Reconnect");
public static GUIContent workOffline = new GUIContent("Work Offline",
"Enable asset modifications even when not connected to a version control server. Requires manual integration into VCS system afterwards.");
public static GUIContent allowAsyncUpdate = new GUIContent("Async Status",
"Enable asynchronous file status queries (useful with slow server connections).");
public static GUIContent showFailedCheckouts = new GUIContent("Show Failed Checkouts",
"Show dialogs for failed 'Check Out' operations.");
public static GUIContent overwriteFailedCheckoutAssets =
new GUIContent("Overwrite Failed Checkout Assets",
"When on, assets that can not be checked out will get saved anyway.");
public static GUIContent overlayIcons = new GUIContent("Overlay Icons",
"Should version control status icons be shown.");
public static GUIContent projectOverlayIcons = new GUIContent("Project Window",
"Should version control status icons be shown in the Project window.");
public static GUIContent hierarchyOverlayIcons = new GUIContent("Hierarchy Window",
"Should version control status icons be shown in the Hierarchy window.");
public static GUIContent otherOverlayIcons = new GUIContent("Other Windows",
"Should version control status icons be shown in other windows.");
// these are required to have correct search keywords
public static GUIContent password = new GUIContent("Password");
public static GUIContent username = new GUIContent("Username");
public static GUIContent server = new GUIContent("Server");
}
const int kVCFieldRecentCount = 10;
const string kVCFieldRecentPrefix = "vcs_ConfigField";
Dictionary<string, string[]> m_VCConfigFieldsRecentValues = new Dictionary<string, string[]>();
bool m_NeedToSaveValuesOnConnect;
private string[] logLevelPopupList =
{
"Verbose", "Info", "Notice", "Fatal"
};
private string[] semanticMergePopupList =
{
"Off", "Premerge", "Ask"
};
private EditorSettingsInspector.PopupElement[] vcDefaultPopupList =
{
new EditorSettingsInspector.PopupElement(ExternalVersionControl.Disabled),
new EditorSettingsInspector.PopupElement(ExternalVersionControl.Generic),
};
private EditorSettingsInspector.PopupElement[] vcPopupList = null;
void DrawOverlayDescriptions()
{
Texture2D atlas = Provider.overlayAtlas;
if (atlas == null)
return;
GUILayout.BeginHorizontal();
GUILayout.BeginVertical();
DrawOverlayDescription(Asset.States.Local);
DrawOverlayDescription(Asset.States.OutOfSync);
DrawOverlayDescription(Asset.States.CheckedOutLocal);
DrawOverlayDescription(Asset.States.CheckedOutRemote);
GUILayout.EndVertical();
GUILayout.BeginVertical();
DrawOverlayDescription(Asset.States.DeletedLocal);
DrawOverlayDescription(Asset.States.DeletedRemote);
DrawOverlayDescription(Asset.States.AddedLocal);
DrawOverlayDescription(Asset.States.AddedRemote);
GUILayout.EndVertical();
GUILayout.BeginVertical();
DrawOverlayDescription(Asset.States.Conflicted);
DrawOverlayDescription(Asset.States.LockedLocal);
DrawOverlayDescription(Asset.States.LockedRemote);
DrawOverlayDescription(Asset.States.Updating);
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
void DrawOverlayDescription(Asset.States state)
{
Rect atlasUV = Provider.GetAtlasRectForState((int)state);
if (atlasUV.width == 0f)
return; // no overlay
Texture2D atlas = Provider.overlayAtlas;
if (atlas == null)
return;
GUILayout.Label(" " + Asset.StateToString(state), EditorStyles.miniLabel);
Rect r = GUILayoutUtility.GetLastRect();
r.width = r.height;
GUI.DrawTextureWithTexCoords(r, atlas, atlasUV);
}
private void CreatePopupMenuVersionControl(string title, EditorSettingsInspector.PopupElement[] elements, string selectedValue,
GenericMenu.MenuFunction2 func)
{
var selectedIndex = Array.FindIndex(elements, e => e.id == selectedValue);
if (selectedIndex == -1)
selectedIndex = Array.FindIndex(elements, e => e.id == ExternalVersionControl.Generic);
var content = new GUIContent(elements[selectedIndex].content);
EditorSettingsInspector.CreatePopupMenu(null, new GUIContent(title), content, elements, selectedIndex, func);
}
private void SetVersionControlSystem(object data)
{
int popupIndex = (int)data;
if (popupIndex < 0 || popupIndex >= vcPopupList.Length)
return;
EditorSettingsInspector.PopupElement el = vcPopupList[popupIndex];
string oldVC = VersionControlSettings.mode;
VersionControlSettings.mode = el.id;
Provider.UpdateSettings();
AssetDatabase.Refresh();
if (oldVC != el.id)
{
if (el.content.text == ExternalVersionControl.Disabled ||
el.content.text == ExternalVersionControl.Generic
)
{
// Close the normal version control window
WindowPending.CloseAllWindows();
}
}
}
private bool VersionControlSystemHasGUI()
{
ExternalVersionControl system = VersionControlSettings.mode;
return
system != ExternalVersionControl.Disabled &&
system != ExternalVersionControl.AutoDetect &&
system != ExternalVersionControl.Generic;
}
string[] GetVCConfigFieldRecentValues(string fieldName)
{
if (m_VCConfigFieldsRecentValues.ContainsKey(fieldName))
return m_VCConfigFieldsRecentValues[fieldName];
var res = new List<string>();
for (var i = 0; i < kVCFieldRecentCount; ++i)
{
var prefName = $"{kVCFieldRecentPrefix}{fieldName}{i}";
var prefValue = EditorPrefs.GetString(prefName);
if (!string.IsNullOrEmpty(prefValue))
res.Add(prefValue);
}
var arr = res.ToArray();
m_VCConfigFieldsRecentValues[fieldName] = arr;
return arr;
}
void UpdateVCConfigFieldRecentValues(ConfigField[] fields)
{
if (fields == null)
return;
foreach (var field in fields)
{
if (field.isPassword)
continue;
var val = EditorUserSettings.GetConfigValue(field.name);
if (string.IsNullOrEmpty(val))
continue;
UpdateVCConfigFieldRecentValue(field.name, val);
}
}
void UpdateVCConfigFieldRecentValue(string fieldName, string value)
{
if (string.IsNullOrEmpty(value))
return;
var arr = GetVCConfigFieldRecentValues(fieldName);
var newVal = new[] {value};
// put newly used value in front
arr = newVal.Concat(arr.Except(newVal)).Take(kVCFieldRecentCount).ToArray();
m_VCConfigFieldsRecentValues[fieldName] = arr;
for (var i = 0; i < arr.Length; ++i)
{
var prefName = $"{kVCFieldRecentPrefix}{fieldName}{i}";
EditorPrefs.SetString(prefName, arr[i]);
}
}
public void OnEnable()
{
IEnumerable<Plugin> availvc = Plugin.availablePlugins;
var popupArray = new List<EditorSettingsInspector.PopupElement>(vcDefaultPopupList);
var descriptors = VersionControlManager.versionControlDescriptors;
popupArray.AddRange(descriptors.OrderBy(d => d.displayName).Select(d => new EditorSettingsInspector.PopupElement(d.name, d.displayName)));
availvc = availvc.Where(p => !descriptors.Any(d => string.Equals(d.name, p.name, StringComparison.Ordinal)));
foreach (var plugin in availvc)
{
popupArray.Add(new EditorSettingsInspector.PopupElement(plugin.name));
}
vcPopupList = popupArray.ToArray();
}
public override void OnInspectorGUI()
{
serializedObject.Update();
GUILayout.Space(10);
GUILayout.BeginVertical(EditorStyles.inspectorDefaultMargins);
using (new EditorGUI.DisabledScope(true))
{
GUI.enabled = true;
ExternalVersionControl selvc = VersionControlSettings.mode;
CreatePopupMenuVersionControl(Styles.mode.text, vcPopupList, selvc, SetVersionControlSystem);
GUI.enabled = true;
}
GUI.enabled = true;
ConfigField[] configFields = null;
var versionControlSystemHasGUI = VersionControlSystemHasGUI();
var vco = versionControlSystemHasGUI ? VersionControlManager.activeVersionControlObject : null;
if (vco != null)
{
vco.GetExtension<ISettingsInspectorExtension>()?.OnInspectorGUI();
}
else if (versionControlSystemHasGUI)
{
bool hasRequiredFields = false;
if (VersionControlSettings.mode == ExternalVersionControl.Generic ||
VersionControlSettings.mode == ExternalVersionControl.Disabled)
{
// no specific UI for these VCS types
}
else
{
configFields = Provider.GetActiveConfigFields();
hasRequiredFields = true;
foreach (ConfigField field in configFields)
{
string newVal;
string oldVal = EditorUserSettings.GetConfigValue(field.name);
if (field.isPassword)
{
newVal = EditorGUILayout.PasswordField(GUIContent.Temp(field.label, field.description),
oldVal);
if (newVal != oldVal)
EditorUserSettings.SetPrivateConfigValue(field.name, newVal);
}
else
{
var recentValues = GetVCConfigFieldRecentValues(field.name);
newVal = EditorGUILayout.TextFieldDropDown(GUIContent.Temp(field.label, field.description),
oldVal, recentValues);
if (newVal != oldVal)
EditorUserSettings.SetConfigValue(field.name, newVal);
}
if (field.isRequired && string.IsNullOrEmpty(newVal))
hasRequiredFields = false;
}
}
// Log level popup
string logLevel = EditorUserSettings.GetConfigValue("vcSharedLogLevel");
int idx = System.Array.FindIndex(logLevelPopupList, (item) => item.ToLower() == logLevel);
if (idx == -1)
{
logLevel = "notice";
idx = System.Array.FindIndex(logLevelPopupList, (item) => item.ToLower() == logLevel);
if (idx == -1)
{
idx = 0;
}
logLevel = logLevelPopupList[idx];
EditorUserSettings.SetConfigValue("vcSharedLogLevel", logLevel);
}
int newIdx = EditorGUILayout.Popup(Styles.logLevel, idx, logLevelPopupList);
if (newIdx != idx)
{
EditorUserSettings.SetConfigValue("vcSharedLogLevel", logLevelPopupList[newIdx].ToLower());
}
if (Provider.onlineState == OnlineState.Offline)
{
var text = "Not Connected. " + (Provider.offlineReason ?? "");
EditorGUILayout.HelpBox(text, MessageType.Error);
}
else if (Provider.onlineState == OnlineState.Updating)
{
var text = "Connecting...";
EditorGUILayout.HelpBox(text, MessageType.Info);
}
else if (EditorUserSettings.WorkOffline)
{
var text =
"Working Offline. Manually integrate your changes using a version control client, and uncheck 'Work Offline' setting below to get back to regular state.";
EditorGUILayout.HelpBox(text, MessageType.Warning);
}
else if (Provider.onlineState == OnlineState.Online)
{
var text = "Connected";
EditorGUILayout.HelpBox(text, MessageType.Info);
}
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUI.enabled = hasRequiredFields && Provider.onlineState != OnlineState.Updating;
if (GUILayout.Button(
Provider.onlineState != OnlineState.Offline ? Styles.vcsReconnect : Styles.vcsConnect,
EditorStyles.miniButton))
{
m_NeedToSaveValuesOnConnect = true;
Provider.UpdateSettings();
}
GUILayout.EndHorizontal();
if (m_NeedToSaveValuesOnConnect && Provider.onlineState == OnlineState.Online)
{
// save connection field settings if we got online with them successfully
m_NeedToSaveValuesOnConnect = false;
UpdateVCConfigFieldRecentValues(configFields);
}
if (Provider.requiresNetwork)
{
bool workOfflineNew =
EditorGUILayout.Toggle(Styles.workOffline,
EditorUserSettings.WorkOffline); // Enabled has a slightly different behaviour
if (workOfflineNew != EditorUserSettings.WorkOffline)
{
// On toggling on show a warning
if (workOfflineNew && !EditorUtility.DisplayDialog("Confirm working offline",
"Working offline and making changes to your assets means that you will have to manually integrate changes back into version control using your standard version control client before you stop working offline in Unity. Make sure you know what you are doing.",
"Work offline", "Cancel"))
{
workOfflineNew = false; // User cancelled working offline
}
EditorUserSettings.WorkOffline = workOfflineNew;
EditorApplication.RequestRepaintAllViews();
}
}
EditorUserSettings.AutomaticAdd =
EditorGUILayout.Toggle(Styles.automaticAdd, EditorUserSettings.AutomaticAdd);
if (Provider.requiresNetwork)
EditorUserSettings.allowAsyncStatusUpdate = EditorGUILayout.Toggle(Styles.allowAsyncUpdate,
EditorUserSettings.allowAsyncStatusUpdate);
if (Provider.hasCheckoutSupport)
{
EditorUserSettings.showFailedCheckout = EditorGUILayout.Toggle(Styles.showFailedCheckouts,
EditorUserSettings.showFailedCheckout);
EditorUserSettings.overwriteFailedCheckoutAssets = EditorGUILayout.Toggle(
Styles.overwriteFailedCheckoutAssets, EditorUserSettings.overwriteFailedCheckoutAssets);
}
EditorUserSettings.semanticMergeMode = (SemanticMergeMode)EditorGUILayout.Popup(Styles.smartMerge,
(int)EditorUserSettings.semanticMergeMode, semanticMergePopupList);
VersionControlSettings.trackPackagesOutsideProject =
EditorGUILayout.Toggle(Styles.trackPackagesOutsideProject, VersionControlSettings.trackPackagesOutsideProject);
GUILayout.Space(10);
GUILayout.Label(Styles.overlayIcons);
EditorGUI.indentLevel++;
var newProjectOverlayIcons = EditorGUILayout.Toggle(Styles.projectOverlayIcons, EditorUserSettings.overlayIcons);
if (newProjectOverlayIcons != EditorUserSettings.overlayIcons)
{
EditorUserSettings.overlayIcons = newProjectOverlayIcons;
EditorApplication.RequestRepaintAllViews();
}
var newHierarchyOverlayIcons = EditorGUILayout.Toggle(Styles.hierarchyOverlayIcons, EditorUserSettings.hierarchyOverlayIcons);
if (newHierarchyOverlayIcons != EditorUserSettings.hierarchyOverlayIcons)
{
EditorUserSettings.hierarchyOverlayIcons = newHierarchyOverlayIcons;
EditorApplication.RequestRepaintAllViews();
}
var newOtherOverlayIcons = EditorGUILayout.Toggle(Styles.otherOverlayIcons, EditorUserSettings.otherOverlayIcons);
if (newOtherOverlayIcons != EditorUserSettings.otherOverlayIcons)
{
EditorUserSettings.otherOverlayIcons = newOtherOverlayIcons;
EditorApplication.RequestRepaintAllViews();
}
EditorGUI.indentLevel--;
GUILayout.Space(10);
GUI.enabled = true;
if (newProjectOverlayIcons || newHierarchyOverlayIcons || newOtherOverlayIcons)
DrawOverlayDescriptions();
}
GUILayout.EndVertical();
}
[SettingsProvider]
internal static SettingsProvider CreateProjectSettingsProvider()
{
var provider = AssetSettingsProvider.CreateProviderFromAssetPath(
"Project/Version Control", "ProjectSettings/VersionControlSettings.asset",
SettingsProvider.GetSearchKeywordsFromGUIContentProperties<Styles>());
return provider;
}
}
}
| UnityCsReference/Editor/Mono/Inspector/VersionControlSettingsInspector.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/VersionControlSettingsInspector.cs",
"repo_id": "UnityCsReference",
"token_count": 9588
} | 329 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEditor;
using UnityEngine;
namespace UnityEditorInternal
{
/// <summary>
/// Helper factory for <see cref="UnityEditor.MonoScript"/> instances.
/// </summary>
public static class MonoScripts
{
public static MonoScript CreateMonoScript(string scriptContents, string className, string nameSpace, string assemblyName, bool isEditorScript)
{
var script = new MonoScript();
if (!string.IsNullOrEmpty(scriptContents))
{
Debug.LogWarning($"MonoScript {className} was initialized with a non-empty script. This has never worked and should not be attempted. The script contents will be ignored");
}
script.Init(className, nameSpace, assemblyName, isEditorScript);
return script;
}
}
}
| UnityCsReference/Editor/Mono/Internal/MonoScripts.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Internal/MonoScripts.cs",
"repo_id": "UnityCsReference",
"token_count": 349
} | 330 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Bindings;
namespace UnityEditor
{
[NativeHeader("Editor/Mono/MeshUtility.bindings.h")]
[NativeHeader("Runtime/Graphics/Mesh/MeshOptimizer.h")]
[NativeHeader("Runtime/Graphics/Texture.h")]
[StaticAccessor("MeshUtility", StaticAccessorType.DoubleColon)]
public class MeshUtility
{
[FreeFunction] extern private static void OptimizeIndexBuffers([NotNull] Mesh mesh);
[FreeFunction] extern private static void OptimizeReorderVertexBuffer([NotNull] Mesh mesh);
public static void Optimize(Mesh mesh)
{
OptimizeIndexBuffers(mesh);
OptimizeReorderVertexBuffer(mesh);
}
extern public static void SetMeshCompression([NotNull] Mesh mesh, ModelImporterMeshCompression compression);
extern public static ModelImporterMeshCompression GetMeshCompression([NotNull] Mesh mesh);
[NativeName("SetPerTriangleUV2")]
static extern bool SetPerTriangleUV2NoCheck(Mesh src, Vector2[] triUV);
public static bool SetPerTriangleUV2(Mesh src, Vector2[] triUV)
{
if (src == null)
throw new ArgumentNullException("src");
if (triUV == null)
throw new ArgumentNullException("triUV");
int triCount = InternalMeshUtil.CalcTriangleCount(src), uvCount = triUV.Length;
if (uvCount != 3 * triCount)
{
Debug.LogError("mesh contains " + triCount + " triangles but " + uvCount + " uvs are provided");
return false;
}
return SetPerTriangleUV2NoCheck(src, triUV);
}
extern internal static Vector2[] ComputeTextureBoundingHull(Texture texture, int vertexCount);
public static Mesh.MeshDataArray AcquireReadOnlyMeshData(Mesh mesh)
{
return new Mesh.MeshDataArray(mesh, false);
}
public static Mesh.MeshDataArray AcquireReadOnlyMeshData(Mesh[] meshes)
{
if (meshes == null)
throw new ArgumentNullException(nameof(meshes), "Mesh array is null");
return new Mesh.MeshDataArray(meshes, meshes.Length, false);
}
public static Mesh.MeshDataArray AcquireReadOnlyMeshData(List<Mesh> meshes)
{
if (meshes == null)
throw new ArgumentNullException(nameof(meshes), "Mesh list is null");
return new Mesh.MeshDataArray(NoAllocHelpers.ExtractArrayFromList(meshes), meshes.Count, false);
}
}
}
| UnityCsReference/Editor/Mono/MeshUtility.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/MeshUtility.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 1106
} | 331 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine;
using UnityEngine.Bindings;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Generic;
using UnityEditor.Animations;
namespace UnityEditor
{
// Representation of Script assets.
[NativeClass(null)]
[NativeType("Editor/Mono/MonoScript.bindings.h")]
[ExcludeFromPreset]
public class MonoScript : TextAsset
{
// Returns the System.Type object of the class implemented by this script
public extern System.Type GetClass();
// Returns the MonoScript object containing specified MonoBehaviour
public static MonoScript FromMonoBehaviour(MonoBehaviour behaviour)
{
return FromScriptedObject(behaviour);
}
// Returns the MonoScript object containing specified ScriptableObject
public static MonoScript FromScriptableObject(ScriptableObject scriptableObject)
{
return FromScriptedObject(scriptableObject);
}
// Returns the MonoScript object used by the given scripted object
[FreeFunction]
internal static extern MonoScript FromScriptedObject(UnityEngine.Object obj);
internal extern bool GetScriptTypeWasJustCreatedFromComponentMenu();
internal extern void SetScriptTypeWasJustCreatedFromComponentMenu();
// *undocumented*
// Pass CreateOptions.None to TextAsset constructor so it does not create a native TextAsset object.
// We create MonoScript native object instead.
public MonoScript() : base(TextAsset.CreateOptions.None, (string)null)
{
Init_Internal(this);
}
[FreeFunction("MonoScript_Init_Internal")]
private static extern void Init_Internal([Writable] MonoScript script);
[FreeFunction("MonoScript_Init", HasExplicitThis = true)]
internal extern void Init(string className, string nameSpace, string assemblyName, bool isEditorScript);
// *undocumented*
[NativeName("GetAssemblyName")]
internal extern string GetAssemblyName();
// *undocumented*
[NativeName("GetNameSpace")]
internal extern string GetNamespace();
[NativeName("GetPropertiesHashString")]
internal extern string GetPropertiesHashString(bool developmentBuild);
}
}
| UnityCsReference/Editor/Mono/MonoScript.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/MonoScript.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 854
} | 332 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.Overlays
{
// No interference from OverlayCanvas. This overlay completely controls when it is visible or hidden.
interface IControlVisibility
{
}
// Overlay is only displayed in the active scene view, when visible is true.
public interface ITransientOverlay
{
bool visible { get; }
}
// Used by SRP https://github.com/Unity-Technologies/Graphics/commit/9e7999d30a1a5189ab9d30e5341a2e48962db453
// Remove once VFX overlays are using ITransientOverlay
abstract class TransientSceneViewOverlay : IMGUIOverlay, ITransientOverlay
{
public abstract bool visible { get; }
internal virtual bool ShouldDisplay() => visible;
}
public abstract class IMGUIOverlay : Overlay
{
internal IMGUIContainer imguiContainer { get; private set; }
public sealed override VisualElement CreatePanelContent()
{
rootVisualElement.pickingMode = PickingMode.Position;
imguiContainer = new IMGUIContainer();
imguiContainer.onGUIHandler = OnPanelGUIHandler;
OnContentRebuild();
return imguiContainer;
}
internal virtual void OnContentRebuild() { }
void OnPanelGUIHandler()
{
if (!displayed)
return;
m_DisableContentModification = Event.current.type == EventType.Layout;
OnGUI();
m_DisableContentModification = false;
if (Event.current.isMouse)
Event.current.Use();
}
public abstract void OnGUI();
}
}
| UnityCsReference/Editor/Mono/Overlays/IMGUIOverlay.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Overlays/IMGUIOverlay.cs",
"repo_id": "UnityCsReference",
"token_count": 704
} | 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.ComponentModel;
using System.Linq;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.Overlays
{
// This is an ugly hack to get popup windows to close when clicking on a button while the popup is already open.
// The problem is that popup windows close when losing focus, which clicking the trigger button does. So the button
// is clicked, the window loses focus and closes, then the mouse up on button requests a new window.
[EditorBrowsable(EditorBrowsableState.Never)]
abstract class PopupWindowBase : EditorWindow
{
static double s_LastClosedTime;
static Rect s_LastActivatorRect;
static bool ShouldShowWindow(Rect activatorRect)
{
const double kJustClickedTime = 0.2;
bool justClosed = (EditorApplication.timeSinceStartup - s_LastClosedTime) < kJustClickedTime;
if (!justClosed || activatorRect != s_LastActivatorRect)
{
s_LastActivatorRect = activatorRect;
return true;
}
return false;
}
public static T Show<T>(VisualElement trigger, Vector2 size) where T : EditorWindow
{
return Show<T>(GUIUtility.GUIToScreenRect(trigger.worldBound), size);
}
public static T Show<T>(Rect activatorRect, Vector2 size) where T : EditorWindow
{
var windows = Resources.FindObjectsOfTypeAll<T>();
if (windows.Any())
{
foreach (var window in windows)
window.Close();
return default;
}
if (ShouldShowWindow(activatorRect))
{
var popup = CreateInstance<T>();
popup.hideFlags = HideFlags.DontSave;
popup.ShowAsDropDown(activatorRect, size);
return popup;
}
return default;
}
void OnEnableINTERNAL()
{
AssemblyReloadEvents.beforeAssemblyReload += Close;
}
void OnDisableINTERNAL()
{
s_LastClosedTime = EditorApplication.timeSinceStartup;
AssemblyReloadEvents.beforeAssemblyReload -= Close;
}
}
abstract class OverlayPopupWindow : PopupWindowBase
{
const float k_BorderWidth = 1;
protected virtual void OnEnable()
{
Color borderColor = EditorGUIUtility.isProSkin ? new Color(0.44f, 0.44f, 0.44f, 1f) : new Color(0.51f, 0.51f, 0.51f);
rootVisualElement.style.borderLeftWidth = k_BorderWidth;
rootVisualElement.style.borderTopWidth = k_BorderWidth;
rootVisualElement.style.borderRightWidth = k_BorderWidth;
rootVisualElement.style.borderBottomWidth = k_BorderWidth;
rootVisualElement.style.borderLeftColor = borderColor;
rootVisualElement.style.borderTopColor = borderColor;
rootVisualElement.style.borderRightColor = borderColor;
rootVisualElement.style.borderBottomColor = borderColor;
}
}
}
| UnityCsReference/Editor/Mono/Overlays/OverlayPopupWindow.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Overlays/OverlayPopupWindow.cs",
"repo_id": "UnityCsReference",
"token_count": 1377
} | 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.Text;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Profiling;
using UnityEngine.Experimental.Rendering;
using UnityEditor;
namespace UnityEditorInternal.FrameDebuggerInternal
{
internal struct ShaderPropertyCollection
{
internal string m_TypeName;
internal string m_Header;
internal string m_HeaderFormat;
internal string m_Format;
internal ShaderPropertyDisplayInfo[] m_Data;
internal void GetCopyText(ref StringBuilder sb)
{
sb.AppendLine(FrameDebuggerStyles.EventDetails.s_DashesString);
sb.AppendLine(m_TypeName);
sb.AppendLine(FrameDebuggerStyles.EventDetails.s_DashesString);
if (m_Data.Length == 0)
{
sb.AppendLine("<Empty>");
sb.AppendLine();
return;
}
sb.AppendLine(m_Header);
for (int i = 0; i < m_Data.Length; i++)
m_Data[i].GetCopyText(ref sb);
sb.AppendLine();
}
internal string copyString
{
get
{
StringBuilder sb = new StringBuilder(4096);
GetCopyText(ref sb);
return sb.ToString();
}
}
internal void Clear()
{
for (int i = 0; i < m_Data.Length; i++)
m_Data[i].Clear();
m_Data = null;
}
}
internal struct ShaderPropertyDisplayInfo
{
internal bool m_IsArray;
internal bool m_IsFoldoutOpen;
internal string m_FoldoutString;
internal string m_PropertyString;
internal Texture m_Texture;
internal GUIStyle m_ArrayGUIStyle;
internal RenderTexture m_TextureCopy;
internal string copyString
{
get
{
StringBuilder sb = new StringBuilder(4096);
GetCopyText(ref sb);
return sb.ToString();
}
}
internal void Clear()
{
// We only need to destroy the copy texture as the other one is
// directly from source so it could be an asset in the project, etc.
if (m_TextureCopy != null)
{
FrameDebuggerHelper.DestroyTexture(ref m_TextureCopy);
m_TextureCopy = null;
}
}
internal void GetCopyText(ref StringBuilder sb)
{
if (!m_IsArray)
sb.AppendLine(m_PropertyString);
else
{
sb.AppendLine(m_FoldoutString);
sb.AppendLine(m_PropertyString);
}
}
}
internal enum ShaderPropertyType
{
Keyword = 0,
Texture = 1,
Int = 2,
Float = 3,
Vector = 4,
Matrix = 5,
Buffer = 6,
CBuffer = 7,
}
// Cached data built from FrameDebuggerEventData.
// Only need to rebuild them when event data actually changes.
internal class CachedEventDisplayData
{
internal int m_Index;
internal int m_RTDisplayIndex;
internal int m_RenderTargetWidth;
internal int m_RenderTargetHeight;
internal int m_RenderTargetShowableRTCount;
internal uint m_Hash;
internal bool m_IsValid;
internal bool m_IsClearEvent;
internal bool m_IsResolveEvent;
internal bool m_IsComputeEvent;
internal bool m_IsRayTracingEvent;
internal bool m_IsConfigureFoveatedEvent;
internal bool m_ShouldDisplayRealAndOriginalShaders;
internal bool m_RenderTargetIsBackBuffer;
internal bool m_RenderTargetIsDepthOnlyRT;
internal bool m_RenderTargetHasShowableDepth;
internal bool m_RenderTargetHasStencilBits;
internal float m_DetailsGUIWidth;
internal float m_DetailsGUIHeight;
internal string m_Title;
internal string m_RealShaderName;
internal string m_OriginalShaderName;
internal string m_RayTracingShaderName;
internal string m_RayTracingGenerationShaderName;
internal Mesh[] m_Meshes;
internal GUIContent[] m_MeshNames;
internal RenderTexture m_RenderTargetRenderTexture;
internal FrameEventType m_Type;
internal GraphicsFormat m_RenderTargetFormat;
internal UnityEngine.Object m_RealShader;
internal UnityEngine.Object m_OriginalShader;
internal string copyString
{
get
{
string detailsString = detailsCopyString;
m_StringBuilder.Clear();
m_StringBuilder.AppendLine(FrameDebuggerStyles.EventDetails.s_EqualsString);
m_StringBuilder.AppendLine(m_Title);
m_StringBuilder.AppendLine(FrameDebuggerStyles.EventDetails.s_EqualsString);
m_StringBuilder.AppendLine();
m_StringBuilder.AppendLine(detailsString);
for (int i = 0; i < m_ShaderProperties.Length; i++)
m_ShaderProperties[i].GetCopyText(ref m_StringBuilder);
return m_StringBuilder.ToString();
}
}
internal string detailsCopyString
{
get
{
StringBuilder sb = new StringBuilder(4096);
sb.AppendLine(FrameDebuggerStyles.EventDetails.s_DashesString);
sb.AppendLine("Details");
sb.AppendLine(FrameDebuggerStyles.EventDetails.s_DashesString);
sb.AppendLine(details);
if (m_ShouldDisplayRealAndOriginalShaders)
{
sb.AppendFormat(k_TwoColumnFormat, FrameDebuggerStyles.EventDetails.s_RealShaderText, m_RealShaderName);
sb.AppendLine();
sb.AppendFormat(k_TwoColumnFormat, FrameDebuggerStyles.EventDetails.s_OriginalShaderText, m_OriginalShaderName);
sb.AppendLine();
}
return sb.ToString();
}
}
private string m_Details;
internal string details
{
get
{
if (string.IsNullOrEmpty(m_Details))
m_Details = m_DetailsStringBuilder.ToString();
return m_Details;
}
}
private string m_MeshNamesString;
internal string meshNames
{
get
{
if (string.IsNullOrEmpty(m_MeshNamesString))
m_MeshNamesString = m_MeshStringBuilder.ToString();
return m_MeshNamesString;
}
}
internal ShaderPropertyCollection[] m_ShaderProperties;
internal ShaderPropertyCollection m_Keywords => m_ShaderProperties[(int)ShaderPropertyType.Keyword];
internal ShaderPropertyCollection m_Textures => m_ShaderProperties[(int)ShaderPropertyType.Texture];
internal ShaderPropertyCollection m_Ints => m_ShaderProperties[(int)ShaderPropertyType.Int];
internal ShaderPropertyCollection m_Floats => m_ShaderProperties[(int)ShaderPropertyType.Float];
internal ShaderPropertyCollection m_Vectors => m_ShaderProperties[(int)ShaderPropertyType.Vector];
internal ShaderPropertyCollection m_Matrices => m_ShaderProperties[(int)ShaderPropertyType.Matrix];
internal ShaderPropertyCollection m_Buffers => m_ShaderProperties[(int)ShaderPropertyType.Buffer];
internal ShaderPropertyCollection m_CBuffers => m_ShaderProperties[(int)ShaderPropertyType.CBuffer];
// Private
private int m_MaxNameLength;
private int m_MaxStageLength;
private int m_MaxTexSizeLength;
private int m_MaxSampleTypeLength;
private int m_MaxColorFormatLength;
private int m_MaxDepthFormatLength;
private int dataTypeEnumLength => Enum.GetNames(typeof(ShaderPropertyType)).Length;
private StringBuilder m_StringBuilder = new StringBuilder(32768);
private StringBuilder m_DetailsStringBuilder = new StringBuilder(4096);
private StringBuilder m_MeshStringBuilder = new StringBuilder(64);
// Constants
private const int k_MinNameLength = 38;
private const int k_MinStageLength = 5; // "Stage".Length
private const int k_MinTexSizeLength = 11; // "65536x65536".Length
private const int k_MinSampleTypeLength = 12; // "Sampler Type".Length
private const int k_MinColorFormatLength = 12; // "Color Format".Length
private const int k_MinDepthFormatLength = 19; // "DepthStencil Format".Length
private const int k_ColumnSpace = 2;
private const int k_MaxDecimalNumbers = 7;
private const int k_MaxNaturalNumber = 10 + k_MaxDecimalNumbers + 1 + 1; // + decimal point + sign
private const string k_TwoColumnFormat = "{0, -22}{1, -35}";
private const string k_FourColumnFormat = "{0, -22}{1, -35}{2, -22}{3, -10}";
private static string s_IntPrecision = k_MaxNaturalNumber + ":F0";
private static string s_FloatPrecision = k_MaxNaturalNumber + ":F" + k_MaxDecimalNumbers;
private const string k_NotAvailableString = FrameDebuggerStyles.EventDetails.k_NotAvailable;
// Structs
private struct ShaderPropertySortingInfo : IComparable<ShaderPropertySortingInfo>
{
internal string m_Name;
internal int m_ArrayIndex;
public int CompareTo(ShaderPropertySortingInfo other)
{
return string.Compare(m_Name, other.m_Name);
}
}
internal void Initialize(FrameDebuggerEvent curEvent, FrameDebuggerEventData curEventData)
{
Clear();
BuildCurEventDataStrings(curEvent, curEventData);
BuildShaderPropertyData(curEventData);
if (curEventData.m_RenderTargetRenderTexture != null)
{
m_RenderTargetRenderTexture = curEventData.m_RenderTargetRenderTexture;
RenderTextureDescriptor desc = curEventData.m_RenderTargetRenderTexture.descriptor;
if (desc.width > 0 && desc.height > 0)
{
m_RenderTargetWidth = desc.width;
m_RenderTargetHeight = desc.height;
}
else
{
m_RenderTargetWidth = curEventData.m_RenderTargetWidth;
m_RenderTargetHeight = curEventData.m_RenderTargetHeight;
}
m_IsValid = true;
}
else
{
m_RenderTargetWidth = curEventData.m_RenderTargetWidth;
m_RenderTargetHeight = curEventData.m_RenderTargetHeight;
m_IsValid = m_IsComputeEvent || m_IsRayTracingEvent;
}
}
private void BuildShaderPropertyData(FrameDebuggerEventData curEventData)
{
ShaderInfo shaderInfo = curEventData.m_ShaderInfo;
m_ShaderProperties= new ShaderPropertyCollection[dataTypeEnumLength];
m_ShaderProperties[(int)ShaderPropertyType.Keyword] = GetShaderData(ShaderPropertyType.Keyword, "Keywords", ref shaderInfo, shaderInfo.m_Keywords.Length);
m_ShaderProperties[(int)ShaderPropertyType.Float] = GetShaderData(ShaderPropertyType.Float, "Floats", ref shaderInfo, shaderInfo.m_Floats.Length);
m_ShaderProperties[(int)ShaderPropertyType.Int] = GetShaderData(ShaderPropertyType.Int, "Ints", ref shaderInfo, shaderInfo.m_Ints.Length);
m_ShaderProperties[(int)ShaderPropertyType.Vector] = GetShaderData(ShaderPropertyType.Vector, "Vectors", ref shaderInfo, shaderInfo.m_Vectors.Length);
m_ShaderProperties[(int)ShaderPropertyType.Matrix] = GetShaderData(ShaderPropertyType.Matrix, "Matrices", ref shaderInfo, shaderInfo.m_Matrices.Length);
m_ShaderProperties[(int)ShaderPropertyType.Texture] = GetShaderData(ShaderPropertyType.Texture, "Textures", ref shaderInfo, shaderInfo.m_Textures.Length);
m_ShaderProperties[(int)ShaderPropertyType.Buffer] = GetShaderData(ShaderPropertyType.Buffer, "Buffers", ref shaderInfo, shaderInfo.m_Buffers.Length);
m_ShaderProperties[(int)ShaderPropertyType.CBuffer] = GetShaderData(ShaderPropertyType.CBuffer, "Constant Buffers", ref shaderInfo, shaderInfo.m_CBuffers.Length);
}
private ShaderPropertyCollection GetShaderData(ShaderPropertyType propType, string typeName, ref ShaderInfo shaderInfo, int arrayLength)
{
ShaderPropertyCollection displayInfo = new ShaderPropertyCollection();
displayInfo.m_TypeName = typeName;
GetFormatAndHeader(propType, ref shaderInfo, ref displayInfo);
// Clear and Resolve events often have properties from the previous events
// tied to them. We therefore force it to skip them.
// TODO: Fix this properly in C++ land.
if (m_IsClearEvent || m_IsResolveEvent)
arrayLength = 0;
// Check the data and create structs for valid ones...
List<ShaderPropertySortingInfo> myList = new List<ShaderPropertySortingInfo>();
for (int index = 0; index < arrayLength; index++)
if (CreateShaderPropertyDisplayInfo(propType, index, ref shaderInfo, out ShaderPropertySortingInfo propDisplayInfo))
myList.Add(propDisplayInfo);
// Sort it...
myList.Sort();
// Fill the ordered structs with data...
ShaderPropertyDisplayInfo[] myArr = new ShaderPropertyDisplayInfo[myList.Count];
for (int index = 0; index < myList.Count; index++)
GetShaderPropertyData(propType, myList[index].m_ArrayIndex, myList[index].m_Name, ref displayInfo, ref shaderInfo, ref myArr[index]);
// Assign the array and return
displayInfo.m_Data = myArr;
return displayInfo;
}
private void GetFormatAndHeader(ShaderPropertyType dataType, ref ShaderInfo shaderInfo, ref ShaderPropertyCollection displayData)
{
// To keep the lines dynamic that scales with the various properties, we
// count the characters for various fields so we can adjust the text formatting
CountCharacters(dataType, shaderInfo);
// Every property starts with the name + scope
displayData.m_Format = "{0, " + -m_MaxNameLength + "}{1, " + -m_MaxStageLength + "}";
displayData.m_HeaderFormat = string.Empty;
switch (dataType)
{
case ShaderPropertyType.Keyword:
displayData.m_Format += "{2, -12}{3, -9}";
displayData.m_Header = String.Format(displayData.m_Format, "Name", "Stage", "Scope", "Dynamic");
break;
case ShaderPropertyType.Float:
displayData.m_Format += "{2, " + s_FloatPrecision + "}";
displayData.m_Header = String.Format(displayData.m_Format, "Name", "Stage", "Value");
break;
case ShaderPropertyType.Int:
displayData.m_Format += "{2, " + s_IntPrecision + "}";
displayData.m_Header = String.Format(displayData.m_Format, "Name", "Stage", "Value");
break;
case ShaderPropertyType.Vector:
displayData.m_Format += "{2, " + s_FloatPrecision + "}{3, " + s_FloatPrecision + "}{4, " + s_FloatPrecision + "}{5, " + s_FloatPrecision + "}";
displayData.m_Header = String.Format(displayData.m_Format, "Name", "Stage", "Value(R)", "Value(G)", "Value(B)", "Value(A)");
break;
case ShaderPropertyType.Matrix:
displayData.m_HeaderFormat = "{0, " + -m_MaxNameLength + "}{1, " + -m_MaxStageLength + "}{2, " + s_FloatPrecision + "}{3, " + s_FloatPrecision + "}{4, " + s_FloatPrecision + "}{5, " + s_FloatPrecision + "}";
displayData.m_Format = "{0, " + -m_MaxNameLength + "}{1, " + -m_MaxStageLength + "}{2, " + s_FloatPrecision + "}{3, " + s_FloatPrecision + "}{4, " + s_FloatPrecision + "}{5, " + s_FloatPrecision + "}\n"
+ "{6, " + -m_MaxNameLength + "}{7, " + -m_MaxStageLength + "}{8, " + s_FloatPrecision + "}{9, " + s_FloatPrecision + "}{10, " + s_FloatPrecision + "}{11, " + s_FloatPrecision + "}\n"
+ "{12, " + -m_MaxNameLength + "}{13, " + -m_MaxStageLength + "}{14, " + s_FloatPrecision + "}{15, " + s_FloatPrecision + "}{16, " + s_FloatPrecision + "}{17, " + s_FloatPrecision + "}\n"
+ "{18, " + -m_MaxNameLength + "}{19, " + -m_MaxStageLength + "}{20, " + s_FloatPrecision + "}{21, " + s_FloatPrecision + "}{22, " + s_FloatPrecision + "}{23, " + s_FloatPrecision + "}";
displayData.m_Header = String.Format(displayData.m_HeaderFormat, "Name", "Stage", "Column 0", "Column 1", "Column 2", "Column 3");
break;
case ShaderPropertyType.Texture:
displayData.m_Format += "{2, " + -m_MaxTexSizeLength + "}{3, " + -m_MaxSampleTypeLength + "}{4, " + -m_MaxColorFormatLength + "}{5, " + -m_MaxDepthFormatLength + "}{6}";
displayData.m_HeaderFormat = displayData.m_Format;
displayData.m_Header = String.Format(displayData.m_HeaderFormat, "Name", "Stage", "Size", "Sampler Type", "Color Format", "DepthStencil Format", "Texture");
break;
case ShaderPropertyType.Buffer:
displayData.m_Format = "{0, " + -m_MaxNameLength + "}";
displayData.m_Header = String.Format(displayData.m_Format, "Name");
break;
case ShaderPropertyType.CBuffer:
displayData.m_Format = "{0, " + -m_MaxNameLength + "}";
displayData.m_Header = String.Format(displayData.m_Format, "Name");
break;
default:
return;
}
}
private bool CreateShaderPropertyDisplayInfo(ShaderPropertyType dataType, int arrayIndex, ref ShaderInfo shaderInfo, out ShaderPropertySortingInfo data)
{
int flags;
string name;
data = new ShaderPropertySortingInfo();
switch (dataType)
{
case ShaderPropertyType.Keyword: flags = shaderInfo.m_Keywords[arrayIndex].m_Flags; name = shaderInfo.m_Keywords[arrayIndex].m_Name; break;
case ShaderPropertyType.Float: flags = shaderInfo.m_Floats[arrayIndex].m_Flags; name = shaderInfo.m_Floats[arrayIndex].m_Name; break;
case ShaderPropertyType.Int: flags = shaderInfo.m_Ints[arrayIndex].m_Flags; name = shaderInfo.m_Ints[arrayIndex].m_Name; break;
case ShaderPropertyType.Vector: flags = shaderInfo.m_Vectors[arrayIndex].m_Flags; name = shaderInfo.m_Vectors[arrayIndex].m_Name; break;
case ShaderPropertyType.Matrix: flags = shaderInfo.m_Matrices[arrayIndex].m_Flags; name = shaderInfo.m_Matrices[arrayIndex].m_Name; break;
case ShaderPropertyType.Texture: flags = shaderInfo.m_Textures[arrayIndex].m_Flags; name = shaderInfo.m_Textures[arrayIndex].m_Name; break;
case ShaderPropertyType.Buffer: flags = 1; name = shaderInfo.m_Buffers[arrayIndex].m_Name; break;
case ShaderPropertyType.CBuffer: flags = 1; name = shaderInfo.m_CBuffers[arrayIndex].m_Name; break;
default: return false;
}
// We get a lot of rubbish data sent in. Needs investigation to why...
if (dataType != ShaderPropertyType.Keyword && dataType != ShaderPropertyType.Texture && dataType != ShaderPropertyType.Buffer && dataType != ShaderPropertyType.CBuffer)
if (FrameDebuggerHelper.GetNumberOfValuesFromFlags(flags) <= 0)
return false;
data.m_Name = name;
data.m_ArrayIndex = arrayIndex;
return true;
}
private string GetArrayIndexString(int nameLength, int numOfValues, int currentIndex)
{
int numOfSpaces = nameLength + (FrameDebuggerHelper.CountDigits(numOfValues) - FrameDebuggerHelper.CountDigits(currentIndex));
return $"{new string(' ', numOfSpaces)}[{currentIndex}]";
}
private bool GetShaderPropertyData(ShaderPropertyType dataType, int arrayIndex, string name, ref ShaderPropertyCollection propertyTypeDisplayData, ref ShaderInfo shaderInfo, ref ShaderPropertyDisplayInfo data)
{
m_StringBuilder.Clear();
data = new ShaderPropertyDisplayInfo();
// Create and return the data...
string stage;
int numOfValues;
switch (dataType)
{
case ShaderPropertyType.Keyword:
Profiler.BeginSample("Keyword");
ShaderKeywordInfo keywordInfo = shaderInfo.m_Keywords[arrayIndex];
data.m_PropertyString = m_StringBuilder.AppendFormat(propertyTypeDisplayData.m_Format,
name,
FrameDebuggerHelper.GetShaderStageString(keywordInfo.m_Flags),
keywordInfo.m_IsGlobal ? "Global" : "Local",
keywordInfo.m_IsDynamic ? "Yes" : "No").ToString();
Profiler.EndSample();
break;
case ShaderPropertyType.Texture:
Profiler.BeginSample("Texture");
ShaderTextureInfo textureInfo = shaderInfo.m_Textures[arrayIndex];
stage = FrameDebuggerHelper.GetShaderStageString(textureInfo.m_Flags);
Texture texture = textureInfo.m_Value;
string samplerType;
string size;
string colorFormat;
string depthStencilFormat;
string textureName = textureInfo.m_TextureName;
if (texture != null)
{
if (texture.dimension == TextureDimension.Tex2DArray)
samplerType = "Tex2D-Array";
else if (texture.dimension == TextureDimension.CubeArray)
samplerType = "Cube-Array";
else
samplerType = $"{texture.dimension}";
size = $"{texture.width}x{texture.height}";
colorFormat = FrameDebuggerHelper.GetColorFormat(ref texture);
depthStencilFormat = FrameDebuggerHelper.GetDepthStencilFormat(ref texture);
// We need to do a blit for when MSAA is enabled or when trying to show depth.
// The ObjectPreview doesn't currently support RenderTextures with only depth...
int volumeDepth = FrameDebuggerHelper.GetVolumeDepth(ref texture);
int msaaVal = FrameDebuggerHelper.GetMSAAValue(ref texture);
bool isDepthTex = FrameDebuggerHelper.IsADepthTexture(ref texture);
if (msaaVal > 1 || isDepthTex)
{
data.m_TextureCopy = new RenderTexture(texture.width, texture.height, 0, RenderTextureFormat.ARGB32);
FrameDebuggerHelper.BlitToRenderTexture(
ref texture,
ref data.m_TextureCopy,
texture.width,
texture.height,
volumeDepth,
Vector4.one,
new Vector4(0f, 1f, 0f, 0f),
false,
false
);
}
else
data.m_Texture = texture;
}
else
{
samplerType = FrameDebuggerStyles.EventDetails.k_NotAvailable;
size = FrameDebuggerStyles.EventDetails.k_NotAvailable;
colorFormat = FrameDebuggerStyles.EventDetails.k_NotAvailable;
depthStencilFormat = FrameDebuggerStyles.EventDetails.k_NotAvailable;
}
data.m_PropertyString = m_StringBuilder.AppendFormat(propertyTypeDisplayData.m_HeaderFormat, name, stage, size, samplerType, colorFormat, depthStencilFormat, textureName).ToString();
Profiler.EndSample();
break;
case ShaderPropertyType.Int:
Profiler.BeginSample("Int");
ShaderIntInfo intInfo = shaderInfo.m_Ints[arrayIndex];
numOfValues = FrameDebuggerHelper.GetNumberOfValuesFromFlags(intInfo.m_Flags);
stage = FrameDebuggerHelper.GetShaderStageString(intInfo.m_Flags);
data.m_IsArray = numOfValues > 1;
data.m_ArrayGUIStyle = CreateArrayGUIStyle(numOfValues);
if (!data.m_IsArray)
data.m_PropertyString = String.Format(propertyTypeDisplayData.m_Format, name, stage, intInfo.m_Value);
else
{
m_StringBuilder.Clear();
data.m_FoldoutString = String.Format(propertyTypeDisplayData.m_Format, $"{name}[{numOfValues}]", stage, string.Empty, string.Empty, string.Empty, string.Empty);
for (int k = arrayIndex; k < arrayIndex + numOfValues; k++)
{
int value = shaderInfo.m_Ints[k].m_Value;
m_StringBuilder.AppendFormat(propertyTypeDisplayData.m_Format,
GetArrayIndexString(name.Length, numOfValues, k - arrayIndex),
string.Empty,
value).AppendLine();
}
// Remove last linebreak
if (m_StringBuilder.Length > 2)
m_StringBuilder.Length--;
data.m_PropertyString = m_StringBuilder.ToString();
}
Profiler.EndSample();
break;
case ShaderPropertyType.Float:
Profiler.BeginSample("Float");
ShaderFloatInfo floatInfo = shaderInfo.m_Floats[arrayIndex];
numOfValues = FrameDebuggerHelper.GetNumberOfValuesFromFlags(floatInfo.m_Flags);
stage = FrameDebuggerHelper.GetShaderStageString(floatInfo.m_Flags);
data.m_IsArray = numOfValues > 1;
data.m_ArrayGUIStyle = CreateArrayGUIStyle(numOfValues);
if (!data.m_IsArray)
data.m_PropertyString = String.Format(propertyTypeDisplayData.m_Format, name, stage, floatInfo.m_Value);
else
{
m_StringBuilder.Clear();
data.m_FoldoutString = m_StringBuilder.AppendFormat(propertyTypeDisplayData.m_Format, $"{name}[{numOfValues}]", stage, string.Empty, string.Empty, string.Empty, string.Empty).ToString();
m_StringBuilder.Clear();
for (int k = arrayIndex; k < arrayIndex + numOfValues; k++)
{
float value = shaderInfo.m_Floats[k].m_Value;
m_StringBuilder.AppendFormat(propertyTypeDisplayData.m_Format,
GetArrayIndexString(name.Length, numOfValues, k - arrayIndex),
string.Empty,
value).AppendLine();
}
// Remove last linebreak
if (numOfValues > 1 && m_StringBuilder.Length > 2)
m_StringBuilder.Length--;
data.m_PropertyString = m_StringBuilder.ToString();
}
Profiler.EndSample();
break;
case ShaderPropertyType.Vector:
Profiler.BeginSample("Vector");
ShaderVectorInfo vectorInfo = shaderInfo.m_Vectors[arrayIndex];
numOfValues = FrameDebuggerHelper.GetNumberOfValuesFromFlags(vectorInfo.m_Flags);
stage = FrameDebuggerHelper.GetShaderStageString(vectorInfo.m_Flags);
data.m_IsArray = numOfValues > 1;
data.m_ArrayGUIStyle = CreateArrayGUIStyle(numOfValues);
if (!data.m_IsArray)
data.m_PropertyString = String.Format(propertyTypeDisplayData.m_Format, name, stage, vectorInfo.m_Value.x, vectorInfo.m_Value.y, vectorInfo.m_Value.z, vectorInfo.m_Value.w);
else
{
m_StringBuilder.Clear();
data.m_FoldoutString = String.Format(propertyTypeDisplayData.m_Format, $"{name}[{numOfValues}]", stage, string.Empty, string.Empty, string.Empty, string.Empty);
for (int k = arrayIndex; k < arrayIndex + numOfValues; k++)
{
Vector4 value = shaderInfo.m_Vectors[k].m_Value;
m_StringBuilder.AppendFormat(propertyTypeDisplayData.m_Format,
GetArrayIndexString(name.Length, numOfValues, k - arrayIndex),
string.Empty,
value.x,
value.y,
value.z,
value.w).AppendLine();
}
// Remove last linebreak
if (numOfValues > 1 && m_StringBuilder.Length > 2)
m_StringBuilder.Length--;
data.m_PropertyString = m_StringBuilder.ToString();
}
Profiler.EndSample();
break;
case ShaderPropertyType.Matrix:
Profiler.BeginSample("Matrix");
ShaderMatrixInfo matrixInfo = shaderInfo.m_Matrices[arrayIndex];
numOfValues = FrameDebuggerHelper.GetNumberOfValuesFromFlags(matrixInfo.m_Flags);
stage = FrameDebuggerHelper.GetShaderStageString(matrixInfo.m_Flags);
data.m_IsArray = numOfValues > 1;
data.m_ArrayGUIStyle = CreateArrayGUIStyle(numOfValues * 4);
if (!data.m_IsArray)
{
Matrix4x4 value = matrixInfo.m_Value;
data.m_PropertyString = m_StringBuilder.AppendFormat(propertyTypeDisplayData.m_Format,
name, stage, value.m00, value.m01, value.m02, value.m03,
string.Empty, string.Empty, value.m10, value.m11, value.m12, value.m13,
string.Empty, string.Empty, value.m20, value.m21, value.m22, value.m23,
string.Empty, string.Empty, value.m30, value.m31, value.m32, value.m33).ToString();
}
else
{
m_StringBuilder.Clear();
data.m_FoldoutString = m_StringBuilder.AppendFormat(propertyTypeDisplayData.m_HeaderFormat, $"{name}[{numOfValues}]", stage, string.Empty, string.Empty, string.Empty, string.Empty).ToString();
m_StringBuilder.Clear();
for (int k = arrayIndex; k < arrayIndex + numOfValues; k++)
{
Matrix4x4 value = shaderInfo.m_Matrices[k].m_Value;
m_StringBuilder.AppendFormat(propertyTypeDisplayData.m_Format,
GetArrayIndexString(name.Length, numOfValues, k - arrayIndex),
string.Empty, value.m00, value.m01, value.m02, value.m03,
string.Empty, string.Empty, value.m10, value.m11, value.m12, value.m13,
string.Empty, string.Empty, value.m20, value.m21, value.m22, value.m23,
string.Empty, string.Empty, value.m30, value.m31, value.m32, value.m33).AppendLine();
}
// Remove last linebreak
if (numOfValues > 1 && m_StringBuilder.Length > 2)
m_StringBuilder.Length--;
data.m_PropertyString = m_StringBuilder.ToString();
}
Profiler.EndSample();
break;
case ShaderPropertyType.Buffer:
Profiler.BeginSample("Buffer");
ShaderBufferInfo bufferInfo = shaderInfo.m_Buffers[arrayIndex];
data.m_PropertyString = String.Format(propertyTypeDisplayData.m_Format, name);
Profiler.EndSample();
break;
case ShaderPropertyType.CBuffer:
Profiler.BeginSample("Constant Buffer");
ShaderConstantBufferInfo constantBufferInfo = shaderInfo.m_CBuffers[arrayIndex];
data.m_PropertyString = String.Format(propertyTypeDisplayData.m_Format, name);
Profiler.EndSample();
break;
default:
return false;
}
return true;
}
private GUIStyle CreateArrayGUIStyle(int numOfValues)
{
// GUIStyle.CalcSizeWithConstraints() is super expensive so to avoid that we set a fixed
// height and width so that function can early out. The width doesn't matter due as the
// Vertical layout above makes sure it doesn't go too far but needs to be set for the early out.
GUIStyle style = new GUIStyle(FrameDebuggerStyles.EventDetails.s_MonoLabelNoWrapStyle);
style.fixedWidth = 1000f;
style.fixedHeight = 16 * numOfValues;
return style;
}
internal void OnDisable()
{
Clear();
}
private void Clear()
{
FrameDebuggerHelper.DestroyTexture(ref m_RenderTargetRenderTexture);
m_StringBuilder.Clear();
m_DetailsStringBuilder.Clear();
m_MeshStringBuilder.Clear();
m_Details = string.Empty;
m_MeshNamesString = string.Empty;
m_RealShaderName = string.Empty;
m_RealShader = null;
m_OriginalShaderName = string.Empty;
m_OriginalShader = null;
m_ShouldDisplayRealAndOriginalShaders = false;
if (m_ShaderProperties != null)
{
for (int i = 0; i < m_ShaderProperties.Length; i++)
{
if (!m_ShaderProperties[i].Equals(default(ShaderPropertyCollection)))
m_ShaderProperties[i].Clear();
}
m_ShaderProperties = null;
}
}
private void BuildCurEventDataStrings(FrameDebuggerEvent curEvent, FrameDebuggerEventData curEventData)
{
// Initialize some key settings
m_Index = FrameDebuggerUtility.limit - 1;
m_Type = curEvent.m_Type;
m_RTDisplayIndex = curEventData.m_RTDisplayIndex;
m_IsClearEvent = FrameDebuggerHelper.IsAClearEvent(m_Type);
m_IsResolveEvent = FrameDebuggerHelper.IsAResolveEvent(m_Type);
m_IsComputeEvent = FrameDebuggerHelper.IsAComputeEvent(m_Type);
m_IsRayTracingEvent = FrameDebuggerHelper.IsARayTracingEvent(m_Type);
m_IsConfigureFoveatedEvent = FrameDebuggerHelper.IsAConfigureFoveatedRenderingEvent(m_Type);
m_RenderTargetIsBackBuffer = curEventData.m_RenderTargetIsBackBuffer;
m_RenderTargetFormat = (GraphicsFormat)curEventData.m_RenderTargetFormat;
m_RenderTargetIsDepthOnlyRT = GraphicsFormatUtility.IsDepthFormat(m_RenderTargetFormat);
m_RenderTargetHasShowableDepth = (curEventData.m_RenderTargetHasDepthTexture != 0);
m_RenderTargetHasStencilBits = (curEventData.m_RenderTargetHasStencilBits != 0);
m_RenderTargetShowableRTCount = curEventData.m_RenderTargetCount;
// Event title
int eventTypeInt = (int)m_Type;
var eventObj = FrameDebuggerUtility.GetFrameEventObject(m_Index);
if (eventObj)
m_Title = $"Event #{m_Index + 1} {FrameDebuggerStyles.s_FrameEventTypeNames[eventTypeInt]} {eventObj.name}";
else
m_Title = $"Event #{m_Index + 1} {FrameDebuggerStyles.s_FrameEventTypeNames[eventTypeInt]}";
// Collect data into a string builder based on the event type...
if (m_IsComputeEvent)
BuildComputeEventDataStrings(curEvent, curEventData);
else if (m_IsRayTracingEvent)
BuildRayTracingEventDataStrings(curEvent, curEventData);
else if (m_IsClearEvent)
BuildClearEventDataStrings(curEvent, curEventData);
else
BuildDrawCallEventDataStrings(curEvent, curEventData);
// Create a string out of the string builder
m_Details = m_DetailsStringBuilder.ToString();
// Calculate the width and height so the scrollbar functions correctly for the details
GUIContent content = new GUIContent(m_Details);
Vector2 guiContentSize = FrameDebuggerStyles.EventDetails.s_MonoLabelStyle.CalcSize(content);
m_DetailsGUIWidth = guiContentSize.x + 12; // Add small margin to the width
m_DetailsGUIHeight = guiContentSize.y;
}
private void BuildRayTracingEventDataStrings(FrameDebuggerEvent curEvent, FrameDebuggerEventData curEventData)
{
bool hasAccelerationName = curEventData.m_RayTracingShaderAccelerationStructureName.Length > 0;
string rayTracingMaxRecursionDepth = $"{curEventData.m_RayTracingShaderMaxRecursionDepth}";
string rayTracingDispatchSize = $"{curEventData.m_RayTracingShaderWidth} x {curEventData.m_RayTracingShaderHeight} x {curEventData.m_RayTracingShaderDepth}";
string rayTracingAccelerationStructure = hasAccelerationName ? $"{curEventData.m_RayTracingShaderAccelerationStructureName} ({curEventData.m_RayTracingShaderAccelerationStructureSize} KB)" : k_NotAvailableString;
string rayTracingMissShaderCount = $"{curEventData.m_RayTracingShaderMissShaderCount}";
string rayTracingCallableShaderCount = $"{curEventData.m_RayTracingShaderCallableShaderCount}";
string rayTracingPassName = $"{curEventData.m_RayTracingShaderPassName}";
m_RayTracingShaderName = $"{curEventData.m_RayTracingShaderName}";
m_RayTracingGenerationShaderName = $"{curEventData.m_RayTracingShaderRayGenShaderName}";
m_DetailsStringBuilder.AppendFormat(k_TwoColumnFormat, "Max. Recursion Depth", rayTracingMaxRecursionDepth).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_TwoColumnFormat, "Dispatch Size", rayTracingDispatchSize).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_TwoColumnFormat, "Indirect Call", curEventData.m_RayTracingIndirectDispatch ? "Yes" : "No").AppendLine();
m_DetailsStringBuilder.AppendFormat(k_TwoColumnFormat, "Accel. Structure", rayTracingAccelerationStructure).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_TwoColumnFormat, "Miss Shader Count", rayTracingMissShaderCount).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_TwoColumnFormat, "Callable Shader Count", rayTracingCallableShaderCount).AppendLine();
m_DetailsStringBuilder.AppendLine();
m_DetailsStringBuilder.AppendFormat(k_TwoColumnFormat, "Pass", rayTracingPassName).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_TwoColumnFormat, "Ray Tracing Shader", m_RayTracingShaderName).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_TwoColumnFormat, "Ray Generation Shader", m_RayTracingGenerationShaderName).AppendLine();
}
private void BuildComputeEventDataStrings(FrameDebuggerEvent curEvent, FrameDebuggerEventData curEventData)
{
bool hasGroups = curEventData.m_ComputeShaderThreadGroupsX != 0 || curEventData.m_ComputeShaderThreadGroupsY != 0 || curEventData.m_ComputeShaderThreadGroupsZ != 0;
string computeThreadGroups = hasGroups ? $"{curEventData.m_ComputeShaderThreadGroupsX}x{curEventData.m_ComputeShaderThreadGroupsY}x{curEventData.m_ComputeShaderThreadGroupsZ}" : "Indirect dispatch";
string computeThreadGroupSize = curEventData.m_ComputeShaderGroupSizeX > 0 ? $"{curEventData.m_ComputeShaderGroupSizeX}x{curEventData.m_ComputeShaderGroupSizeY}x{curEventData.m_ComputeShaderGroupSizeZ}" : k_NotAvailableString;
string computeShaderKernel = curEventData.m_ComputeShaderKernelName;
string computeShaderName = curEventData.m_ComputeShaderName;
m_DetailsStringBuilder.AppendFormat(k_TwoColumnFormat, "Thread Groups", computeThreadGroups).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_TwoColumnFormat, "Thread Group Size", computeThreadGroupSize).AppendLine();
m_DetailsStringBuilder.AppendLine();
m_DetailsStringBuilder.AppendFormat(k_TwoColumnFormat, "Kernel", computeShaderKernel).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_TwoColumnFormat, "Compute Shader", computeShaderName).AppendLine();
}
private void BuildClearEventDataStrings(FrameDebuggerEvent curEvent, FrameDebuggerEventData curEventData)
{
string target = curEventData.m_RenderTargetName;
int typeInt = (int)curEvent.m_Type;
string clearColor = (typeInt & 1) != 0 ? $"({curEventData.m_RenderTargetClearColorR:F2}, {curEventData.m_RenderTargetClearColorG:F2}, {curEventData.m_RenderTargetClearColorB:F2}, {curEventData.m_RenderTargetClearColorA:F2})" : k_NotAvailableString;
string clearDepth = (typeInt & 2) != 0 ? curEventData.m_ClearDepth.ToString("f3") : k_NotAvailableString;
string clearStencil = (typeInt & 4) != 0 ? FrameDebuggerHelper.GetStencilString((int)curEventData.m_ClearStencil) : k_NotAvailableString;
string size = $"{curEventData.m_RenderTargetWidth}x{curEventData.m_RenderTargetHeight}";
string format = $"{m_RenderTargetFormat}";
bool hasColorActions = curEventData.m_RenderTargetLoadAction != -1;
bool hasDepthActions = curEventData.m_RenderTargetDepthLoadAction != -1;
string colorActions = hasColorActions ? $"{(RenderBufferLoadAction)curEventData.m_RenderTargetLoadAction} / {(RenderBufferStoreAction)curEventData.m_RenderTargetStoreAction}" : k_NotAvailableString;
string depthActions = hasDepthActions ? $"{(RenderBufferLoadAction)curEventData.m_RenderTargetDepthLoadAction} / {(RenderBufferStoreAction)curEventData.m_RenderTargetDepthStoreAction}" : k_NotAvailableString;
m_DetailsStringBuilder.Append(FrameDebuggerStyles.EventDetails.s_RenderTargetText).AppendLine();
m_DetailsStringBuilder.Append(target).AppendLine();
m_DetailsStringBuilder.AppendLine();
m_DetailsStringBuilder.AppendFormat(k_TwoColumnFormat, "Size", size).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_TwoColumnFormat, "Format", format).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_TwoColumnFormat, "Color Actions", colorActions).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_TwoColumnFormat, "Depth Actions", depthActions).AppendLine();
m_DetailsStringBuilder.AppendLine();
m_DetailsStringBuilder.AppendFormat(k_TwoColumnFormat, "Clear Color", clearColor).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_TwoColumnFormat, "Clear Depth", clearDepth).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_TwoColumnFormat, "Clear Stencil", clearStencil).AppendLine();
}
private void BuildDrawCallEventDataStrings(FrameDebuggerEvent curEvent, FrameDebuggerEventData curEventData)
{
m_ShouldDisplayRealAndOriginalShaders = true;
//
FrameDebuggerRasterState rasterState = curEventData.m_RasterState;
FrameDebuggerDepthState depthState = curEventData.m_DepthState;
FrameDebuggerBlendState blendState = curEventData.m_BlendState;
// Shader names
m_RealShaderName = curEventData.m_RealShaderName;
m_RealShader = Shader.Find(m_RealShaderName);
m_OriginalShaderName = curEventData.m_OriginalShaderName;
m_OriginalShader = Shader.Find(m_OriginalShaderName);
//
bool isResolveOrConfigureFov = m_IsResolveEvent || m_IsConfigureFoveatedEvent;
bool hasColorActions = curEventData.m_RenderTargetLoadAction != -1;
bool hasDepthActions = curEventData.m_RenderTargetDepthLoadAction != -1;
bool isStencilEnabled = curEventData.m_StencilState.m_StencilEnable;
// Gather the necessary strings...
string target = curEventData.m_RenderTargetName;
string batchbreakCause = FrameDebuggerStyles.EventDetails.s_BatchBreakCauses[curEventData.m_BatchBreakCause];
FrameDebuggerHelper.SpliceText(ref batchbreakCause, 85);
string size = $"{curEventData.m_RenderTargetWidth}x{curEventData.m_RenderTargetHeight}";
string format = $"{m_RenderTargetFormat}";
string colorActions = hasColorActions ? $"{(RenderBufferLoadAction)curEventData.m_RenderTargetLoadAction} / {(RenderBufferStoreAction)curEventData.m_RenderTargetStoreAction}" : k_NotAvailableString;
string depthActions = hasDepthActions ? $"{(RenderBufferLoadAction)curEventData.m_RenderTargetDepthLoadAction} / {(RenderBufferStoreAction)curEventData.m_RenderTargetDepthStoreAction}" : k_NotAvailableString;
string zClip = !isResolveOrConfigureFov ? rasterState.m_DepthClip.ToString() : k_NotAvailableString;
string zTest = !isResolveOrConfigureFov ? depthState.m_DepthFunc.ToString() : k_NotAvailableString;
string zWrite = !isResolveOrConfigureFov ? (depthState.m_DepthWrite == 0 ? "Off" : "On") : k_NotAvailableString;
string cull = !isResolveOrConfigureFov ? rasterState.m_CullMode.ToString() : k_NotAvailableString;
string conservative = !isResolveOrConfigureFov ? rasterState.m_Conservative.ToString() : k_NotAvailableString;
string offset = !isResolveOrConfigureFov ? $"{rasterState.m_SlopeScaledDepthBias}, {rasterState.m_DepthBias}" : k_NotAvailableString;
string memoryless = !isResolveOrConfigureFov ? (curEventData.m_RenderTargetMemoryless != 0 ? "Yes" : "No") : k_NotAvailableString;
string foveatedRendering = FrameDebuggerHelper.GetFoveatedRenderingModeString(curEventData.m_RenderTargetFoveatedRenderingMode);
bool hasGroups = curEventData.m_ComputeShaderThreadGroupsX != 0 || curEventData.m_ComputeShaderThreadGroupsY != 0 || curEventData.m_ComputeShaderThreadGroupsZ != 0;
string computeShaderKernel = m_IsComputeEvent ? curEventData.m_ComputeShaderKernelName : k_NotAvailableString;
string computeThreadGroups = m_IsComputeEvent && hasGroups ? $"{curEventData.m_ComputeShaderThreadGroupsX}x{curEventData.m_ComputeShaderThreadGroupsY}x{curEventData.m_ComputeShaderThreadGroupsZ}" : m_IsComputeEvent ? "Indirect dispatch" : k_NotAvailableString;
string computeThreadGroupSize = m_IsComputeEvent && curEventData.m_ComputeShaderGroupSizeX > 0 ? $"{curEventData.m_ComputeShaderGroupSizeX}x{curEventData.m_ComputeShaderGroupSizeY}x{curEventData.m_ComputeShaderGroupSizeZ}" : k_NotAvailableString;
string passName = $"{(string.IsNullOrEmpty(curEventData.m_PassName) ? k_NotAvailableString : curEventData.m_PassName)} ({curEventData.m_ShaderPassIndex})";
string lightModeName = string.IsNullOrEmpty(curEventData.m_PassLightMode) ? k_NotAvailableString : curEventData.m_PassLightMode;
// Format them all together...
m_DetailsStringBuilder.Append(FrameDebuggerStyles.EventDetails.s_RenderTargetText).AppendLine();
m_DetailsStringBuilder.Append(target).AppendLine();
m_DetailsStringBuilder.AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "Size", size, "ZClip", zClip).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "Format", format, "ZTest", zTest).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "Color Actions", colorActions, "ZWrite", zWrite).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "Depth Actions", depthActions, "Cull", cull).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "Memoryless", memoryless, "Conservative", conservative).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "Foveated Rendering", foveatedRendering, "Offset", offset).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, string.Empty, string.Empty, string.Empty, string.Empty).AppendLine();
if (isResolveOrConfigureFov)
{
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "ColorMask", k_NotAvailableString, "Stencil", string.Empty).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "Blend Color", k_NotAvailableString, "Stencil Ref", k_NotAvailableString).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "Blend Alpha", k_NotAvailableString, "Stencil ReadMask", k_NotAvailableString).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "BlendOp Color", k_NotAvailableString, "Stencil WriteMask", k_NotAvailableString).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "BlendOp Alpha", k_NotAvailableString, "Stencil Comp", k_NotAvailableString).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, string.Empty, string.Empty, "Stencil Pass", k_NotAvailableString).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "DrawInstanced Calls", k_NotAvailableString, "Stencil Fail", k_NotAvailableString).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "Instances", k_NotAvailableString, "Stencil ZFail", k_NotAvailableString).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "Draw Calls", "1", string.Empty, string.Empty).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "Vertices", k_NotAvailableString, string.Empty, string.Empty).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "Indices", k_NotAvailableString, string.Empty, string.Empty).AppendLine();
}
else
{
string colorMask = FrameDebuggerHelper.GetColorMask(blendState.m_WriteMask);
string blendColor = $"{blendState.m_SrcBlend} / {blendState.m_DstBlend}";
string blendAlpha = $"{blendState.m_SrcBlendAlpha} / {blendState.m_DstBlendAlpha}";
string blendOpColor = blendState.m_BlendOp.ToString();
string blendOpAlpha = blendState.m_BlendOpAlpha.ToString();
string stencilRef = isStencilEnabled ? FrameDebuggerHelper.GetStencilString(curEventData.m_StencilRef) : k_NotAvailableString;
string stencilReadMask = isStencilEnabled && curEventData.m_StencilState.m_ReadMask != 255 ? FrameDebuggerHelper.GetStencilString(curEventData.m_StencilState.m_ReadMask) : k_NotAvailableString;
string stencilWriteMask = isStencilEnabled && curEventData.m_StencilState.m_WriteMask != 255 ? FrameDebuggerHelper.GetStencilString(curEventData.m_StencilState.m_WriteMask) : k_NotAvailableString;
string stencilComp = k_NotAvailableString;
string stencilPass = k_NotAvailableString;
string stencilFail = k_NotAvailableString;
string stencilZFail = k_NotAvailableString;
if (isStencilEnabled)
{
CullMode cullMode = curEventData.m_RasterState.m_CullMode;
// Only show *Front states when CullMode is set to Back.
if (cullMode == CullMode.Back)
{
stencilComp = $"{curEventData.m_StencilState.m_StencilFuncFront}";
stencilPass = $"{curEventData.m_StencilState.m_StencilPassOpFront}";
stencilFail = $"{curEventData.m_StencilState.m_StencilFailOpFront}";
stencilZFail = $"{curEventData.m_StencilState.m_StencilZFailOpFront}";
}
// Only show *Back states when CullMode is set to Front.
else if (cullMode == CullMode.Front)
{
stencilComp = $"{curEventData.m_StencilState.m_StencilFuncBack}";
stencilPass = $"{curEventData.m_StencilState.m_StencilPassOpBack}";
stencilFail = $"{curEventData.m_StencilState.m_StencilFailOpBack}";
stencilZFail = $"{curEventData.m_StencilState.m_StencilZFailOpBack}";
}
// Show both *Front and *Back states for two-sided geometry.
else
{
stencilComp = $"{curEventData.m_StencilState.m_StencilFuncFront} / {curEventData.m_StencilState.m_StencilFuncBack}";
stencilPass = $"{curEventData.m_StencilState.m_StencilPassOpFront} / {curEventData.m_StencilState.m_StencilPassOpBack}";
stencilFail = $"{curEventData.m_StencilState.m_StencilFailOpFront} / {curEventData.m_StencilState.m_StencilFailOpBack}";
stencilZFail = $"{curEventData.m_StencilState.m_StencilZFailOpFront} / {curEventData.m_StencilState.m_StencilZFailOpBack}";
}
}
string drawInstancedCalls = curEventData.m_InstanceCount > 1 ? $"{curEventData.m_DrawCallCount}" : k_NotAvailableString;
string drawInstances = curEventData.m_InstanceCount > 1 ? $"{curEventData.m_InstanceCount}" : k_NotAvailableString;
string drawCalls = curEventData.m_InstanceCount > 1 ? k_NotAvailableString : $"{curEventData.m_DrawCallCount}";
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "ColorMask", colorMask, "Stencil", string.Empty).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "Blend Color", blendColor, "Stencil Ref", stencilRef).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "Blend Alpha", blendAlpha, "Stencil ReadMask", stencilReadMask).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "BlendOp Color", blendOpColor, "Stencil WriteMask", stencilWriteMask).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "BlendOp Alpha", blendOpAlpha, "Stencil Comp", stencilComp).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, string.Empty, string.Empty, "Stencil Pass", stencilPass).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "DrawInstanced Calls", drawInstancedCalls, "Stencil Fail", stencilFail).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "Instances", drawInstances, "Stencil ZFail", stencilZFail).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "Draw Calls", drawCalls, string.Empty, string.Empty).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "Vertices", curEventData.m_VertexCount.ToString(), string.Empty, string.Empty).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, "Indices", curEventData.m_IndexCount.ToString(), string.Empty, string.Empty).AppendLine();
}
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, string.Empty, string.Empty, string.Empty, string.Empty).AppendLine();
m_DetailsStringBuilder.AppendFormat(k_FourColumnFormat, FrameDebuggerStyles.EventDetails.s_BatchCauseText, string.Empty, string.Empty, string.Empty).AppendLine();
m_DetailsStringBuilder.Append(batchbreakCause).AppendLine();
m_DetailsStringBuilder.AppendLine();
if (curEventData.m_MeshInstanceIDs != null && curEventData.m_MeshInstanceIDs.Length > 0)
{
HashSet<int> meshIDs = new HashSet<int>();
for (int i = 0; i < curEventData.m_MeshInstanceIDs.Length; i++)
{
int id = curEventData.m_MeshInstanceIDs[i];
Mesh mesh = EditorUtility.InstanceIDToObject(id) as Mesh;
if (mesh != null)
meshIDs.Add(id);
}
List<Mesh> meshes = new List<Mesh>();
foreach (int id in meshIDs)
{
Mesh mesh = EditorUtility.InstanceIDToObject(id) as Mesh;
meshes.Add(mesh);
}
m_Meshes = meshes.ToArray();
m_MeshNames = new GUIContent[meshes.Count];
for (var i = 0; i < m_Meshes.Length; ++i)
{
m_MeshNames[i] = EditorGUIUtility.TrTextContent(m_Meshes[i].name, string.Empty);
if (i == 0)
m_MeshStringBuilder.AppendFormat(k_TwoColumnFormat, "Meshes", m_MeshNames[i].text);
else
m_MeshStringBuilder.AppendFormat(k_TwoColumnFormat, string.Empty, m_MeshNames[i].text);
m_MeshStringBuilder.AppendLine();
}
}
else
{
if (curEventData.m_Mesh == null || curEventData.m_Mesh.name == string.Empty)
{
m_MeshStringBuilder.AppendFormat(k_TwoColumnFormat, "Mesh", k_NotAvailableString);
m_Meshes = null;
m_MeshNames = null;
}
else
{
m_Meshes = new Mesh[] { curEventData.m_Mesh };
m_MeshNames = new GUIContent[1];
m_MeshNames[0] = EditorGUIUtility.TrTextContent(curEventData.m_Mesh.name, string.Empty);
m_MeshStringBuilder.AppendFormat(k_TwoColumnFormat, "Mesh", m_MeshNames[0].text);
}
m_MeshStringBuilder.AppendLine();
}
m_DetailsStringBuilder.Append(m_MeshStringBuilder);
m_DetailsStringBuilder.AppendLine();
m_DetailsStringBuilder.AppendFormat(k_TwoColumnFormat, "LightMode", lightModeName);
m_DetailsStringBuilder.AppendLine();
m_DetailsStringBuilder.AppendFormat(k_TwoColumnFormat, "Pass", passName);
}
private void CountCharacters(ShaderPropertyType dataType, ShaderInfo shaderInfo)
{
m_MaxNameLength = k_MinNameLength;
m_MaxStageLength = k_MinStageLength;
m_MaxTexSizeLength = k_MinTexSizeLength;
m_MaxSampleTypeLength = k_MinSampleTypeLength;
m_MaxColorFormatLength = k_MinColorFormatLength;
m_MaxDepthFormatLength = k_MinDepthFormatLength;
switch (dataType)
{
case ShaderPropertyType.Keyword:
for (int i = 0; i < shaderInfo.m_Keywords.Length; i++)
{
m_MaxNameLength = Mathf.Max(m_MaxNameLength, shaderInfo.m_Keywords[i].m_Name.Length);
m_MaxStageLength = Mathf.Max(m_MaxStageLength, FrameDebuggerHelper.GetShaderStageString(shaderInfo.m_Keywords[i].m_Flags).Length);
}
break;
case ShaderPropertyType.Texture:
for (int i = 0; i < shaderInfo.m_Textures.Length; i++)
{
m_MaxNameLength = Mathf.Max(m_MaxNameLength, shaderInfo.m_Textures[i].m_Name.Length);
m_MaxStageLength = Mathf.Max(m_MaxStageLength, FrameDebuggerHelper.GetShaderStageString(shaderInfo.m_Textures[i].m_Flags).Length);
Texture texture = shaderInfo.m_Textures[i].m_Value;
if (texture != null)
{
m_MaxColorFormatLength = Mathf.Max(m_MaxColorFormatLength, FrameDebuggerHelper.GetColorFormat(ref texture).Length);
m_MaxDepthFormatLength = Mathf.Max(m_MaxDepthFormatLength, FrameDebuggerHelper.GetDepthStencilFormat(ref texture).Length);
m_MaxTexSizeLength = Mathf.Max(m_MaxTexSizeLength, $"{texture.width}x{texture.height}".Length);
m_MaxSampleTypeLength = Mathf.Max(m_MaxSampleTypeLength, $"{texture.dimension}".Length);
}
}
break;
case ShaderPropertyType.Int:
for (int i = 0; i < shaderInfo.m_Ints.Length; i++)
{
int numOfValues = FrameDebuggerHelper.GetNumberOfValuesFromFlags(shaderInfo.m_Ints[i].m_Flags);
int arrayChars = numOfValues > 1 ? FrameDebuggerHelper.CountDigits(numOfValues) + 2 : 0;
m_MaxNameLength = Mathf.Max(m_MaxNameLength, shaderInfo.m_Ints[i].m_Name.Length + arrayChars);
m_MaxStageLength = Mathf.Max(m_MaxStageLength, FrameDebuggerHelper.GetShaderStageString(shaderInfo.m_Ints[i].m_Flags).Length);
}
break;
case ShaderPropertyType.Float:
for (int i = 0; i < shaderInfo.m_Floats.Length; i++)
{
int numOfValues = FrameDebuggerHelper.GetNumberOfValuesFromFlags(shaderInfo.m_Floats[i].m_Flags);
int arrayChars = numOfValues > 1 ? FrameDebuggerHelper.CountDigits(numOfValues) + 2 : 0;
m_MaxNameLength = Mathf.Max(m_MaxNameLength, shaderInfo.m_Floats[i].m_Name.Length + arrayChars);
m_MaxStageLength = Mathf.Max(m_MaxStageLength, FrameDebuggerHelper.GetShaderStageString(shaderInfo.m_Floats[i].m_Flags).Length);
}
break;
case ShaderPropertyType.Vector:
for (int i = 0; i < shaderInfo.m_Vectors.Length; i++)
{
int numOfValues = FrameDebuggerHelper.GetNumberOfValuesFromFlags(shaderInfo.m_Vectors[i].m_Flags);
int arrayChars = numOfValues > 1 ? FrameDebuggerHelper.CountDigits(numOfValues) + 2 : 0;
m_MaxNameLength = Mathf.Max(m_MaxNameLength, shaderInfo.m_Vectors[i].m_Name.Length + arrayChars);
m_MaxStageLength = Mathf.Max(m_MaxStageLength, FrameDebuggerHelper.GetShaderStageString(shaderInfo.m_Vectors[i].m_Flags).Length);
}
break;
case ShaderPropertyType.Matrix:
for (int i = 0; i < shaderInfo.m_Matrices.Length; i++)
{
int numOfValues = FrameDebuggerHelper.GetNumberOfValuesFromFlags(shaderInfo.m_Matrices[i].m_Flags);
int arrayChars = numOfValues > 1 ? FrameDebuggerHelper.CountDigits(numOfValues) + 2 : 0;
m_MaxNameLength = Mathf.Max(m_MaxNameLength, shaderInfo.m_Matrices[i].m_Name.Length + arrayChars);
m_MaxStageLength = Mathf.Max(m_MaxStageLength, FrameDebuggerHelper.GetShaderStageString(shaderInfo.m_Matrices[i].m_Flags).Length);
}
break;
case ShaderPropertyType.Buffer:
for (int i = 0; i < shaderInfo.m_Buffers.Length; i++)
{
m_MaxNameLength = Mathf.Max(m_MaxNameLength, shaderInfo.m_Buffers[i].m_Name.Length);
m_MaxStageLength = Mathf.Max(m_MaxStageLength, FrameDebuggerHelper.GetShaderStageString(shaderInfo.m_Buffers[i].m_Flags).Length);
}
break;
case ShaderPropertyType.CBuffer:
for (int i = 0; i < shaderInfo.m_CBuffers.Length; i++)
{
m_MaxNameLength = Mathf.Max(m_MaxNameLength, shaderInfo.m_CBuffers[i].m_Name.Length);
m_MaxStageLength = Mathf.Max(m_MaxStageLength, FrameDebuggerHelper.GetShaderStageString(shaderInfo.m_CBuffers[i].m_Flags).Length);
}
break;
default:
break;
}
m_MaxNameLength += k_ColumnSpace;
m_MaxStageLength += k_ColumnSpace;
m_MaxTexSizeLength += k_ColumnSpace;
m_MaxSampleTypeLength += k_ColumnSpace;
m_MaxColorFormatLength += k_ColumnSpace;
m_MaxDepthFormatLength += k_ColumnSpace;
}
}
}
| UnityCsReference/Editor/Mono/PerformanceTools/FrameDebuggerEventDisplayData.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/PerformanceTools/FrameDebuggerEventDisplayData.cs",
"repo_id": "UnityCsReference",
"token_count": 32101
} | 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 UnityEngine.Bindings;
using UnityEngine.Playables;
using UnityEngine.Scripting;
namespace UnityEditor.Playables
{
[NativeHeader("Editor/Src/Playables/Playables.bindings.h")]
static public class Utility
{
static public event Action<PlayableGraph> graphCreated;
static public event Action<PlayableGraph> destroyingGraph;
[RequiredByNativeCode]
static private void OnPlayableGraphCreated(PlayableGraph graph)
{
if (graphCreated != null)
graphCreated(graph);
}
[RequiredByNativeCode]
static private void OnDestroyingPlayableGraph(PlayableGraph graph)
{
if (destroyingGraph != null)
destroyingGraph(graph);
}
extern static public PlayableGraph[] GetAllGraphs();
}
}
| UnityCsReference/Editor/Mono/Playables/Playables.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Playables/Playables.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 380
} | 336 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
using UnityEngine.Bindings;
using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.IO;
namespace UnityEditor
{
// Player Settings is where you define various parameters for the final game that you will build in Unity. Some of these values are used in the Resolution Dialog that launches when you open a standalone game.
public sealed partial class PlayerSettings
{
// Nintendo Switch specific player settings
[NativeHeader("Editor/Mono/PlayerSettingsSwitch.bindings.h")]
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()", StaticAccessorType.Dot)]
public sealed partial class Switch
{
public enum ScreenResolutionBehavior
{
Manual = 0,
OperationMode = 1,
PerformanceMode = 2,
Both = 3
}
private enum SupportedNpadStyleBits
{
FullKey = 1,
Handheld = 2,
JoyDual = 4,
JoyLeft = 8,
JoyRight = 16,
}
[Flags]
public enum SupportedNpadStyle
{
FullKey = (1 << SupportedNpadStyleBits.FullKey),
Handheld = (1 << SupportedNpadStyleBits.Handheld),
JoyDual = (1 << SupportedNpadStyleBits.JoyDual),
JoyLeft = (1 << SupportedNpadStyleBits.JoyLeft),
JoyRight = (1 << SupportedNpadStyleBits.JoyRight),
}
// Socket Memory Pool Size
[NativeProperty("switchSocketMemoryPoolSize", TargetType.Field)]
extern public static int socketMemoryPoolSize { get; set; }
// Socket Allocator Pool Size
[NativeProperty("switchSocketAllocatorPoolSize", TargetType.Field)]
extern public static int socketAllocatorPoolSize { get; set; }
// Socket Concurrency Limit
[NativeProperty("switchSocketConcurrencyLimit", TargetType.Field)]
extern public static int socketConcurrencyLimit { get; set; }
// Whether to enable use of the Nintendo Switch CPU Profiler.
[NativeProperty("switchUseCPUProfiler", TargetType.Field)]
extern public static bool useSwitchCPUProfiler { get; set; }
// Whether to enable file system trace on Nintendo Switch CPU Profiler.
[NativeProperty("switchEnableFileSystemTrace", TargetType.Field)]
extern public static bool enableFileSystemTrace { get; set; }
// What LTO setting to use on Switch.
[NativeProperty("switchLTOSetting", TargetType.Field)]
extern public static int switchLTOSetting { get; set; }
[StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)]
extern public static int queueCommandMemory
{
[NativeMethod("GetSwitchQueueCommandMemory")]
get;
[NativeMethod("SetSwitchQueueCommandMemory")]
set;
}
[StaticAccessor("PlayerSettings", StaticAccessorType.DoubleColon)]
extern public static int defaultSwitchQueueCommandMemory { get; }
[StaticAccessor("PlayerSettings", StaticAccessorType.DoubleColon)]
extern public static int minimumSwitchQueueCommandMemory { get; }
[StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)]
extern public static int queueControlMemory
{
[NativeMethod("GetSwitchQueueControlMemory")]
get;
[NativeMethod("SetSwitchQueueControlMemory")]
set;
}
[StaticAccessor("PlayerSettings", StaticAccessorType.DoubleColon)]
extern public static int defaultSwitchQueueControlMemory { get; }
[StaticAccessor("PlayerSettings", StaticAccessorType.DoubleColon)]
extern public static int minimumSwitchQueueControlMemory { get; }
[StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)]
extern public static int queueComputeMemory
{
[NativeMethod("GetSwitchQueueComputeMemory")]
get;
[NativeMethod("SetSwitchQueueComputeMemory")]
set;
}
[StaticAccessor("PlayerSettings", StaticAccessorType.DoubleColon)]
extern public static int defaultSwitchQueueComputeMemory { get; }
// GPU Pool information.
[StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)]
extern public static int NVNShaderPoolsGranularity
{
[NativeMethod("GetSwitchNVNShaderPoolsGranularity")]
get;
[NativeMethod("SetSwitchNVNShaderPoolsGranularity")]
set;
}
[StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)]
extern public static int NVNDefaultPoolsGranularity
{
[NativeMethod("GetSwitchNVNDefaultPoolsGranularity")]
get;
[NativeMethod("SetSwitchNVNDefaultPoolsGranularity")]
set;
}
[StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)]
extern public static int NVNOtherPoolsGranularity
{
[NativeMethod("GetSwitchNVNOtherPoolsGranularity")]
get;
[NativeMethod("SetSwitchNVNOtherPoolsGranularity")]
set;
}
[StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)]
extern public static int GpuScratchPoolGranularity
{
[NativeMethod("GetSwitchGpuScratchPoolGranularity")]
get;
[NativeMethod("SetSwitchGpuScratchPoolGranularity")]
set;
}
[StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)]
extern public static bool AllowGpuScratchShrinking
{
[NativeMethod("GetSwitchAllowGpuScratchShrinking")]
get;
[NativeMethod("SetSwitchAllowGpuScratchShrinking")]
set;
}
[StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)]
extern public static int NVNMaxPublicTextureIDCount
{
[NativeMethod("GetSwitchNVNMaxPublicTextureIDCount")]
get;
[NativeMethod("SetSwitchNVNMaxPublicTextureIDCount")]
set;
}
[StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)]
extern public static int NVNMaxPublicSamplerIDCount
{
[NativeMethod("GetSwitchNVNMaxPublicSamplerIDCount")]
get;
[NativeMethod("SetSwitchNVNMaxPublicSamplerIDCount")]
set;
}
[StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)]
extern public static int NVNGraphicsFirmwareMemory
{
[NativeMethod("GetSwitchNVNGraphicsFirmwareMemory")]
get;
[NativeMethod("SetSwitchNVNGraphicsFirmwareMemory")]
set;
}
[StaticAccessor("PlayerSettings", StaticAccessorType.DoubleColon)]
extern public static int defaultSwitchNVNGraphicsFirmwareMemory { get; }
[StaticAccessor("PlayerSettings", StaticAccessorType.DoubleColon)]
extern public static int minimumSwitchNVNGraphicsFirmwareMemory { get; }
[StaticAccessor("PlayerSettings", StaticAccessorType.DoubleColon)]
extern public static int maximumSwitchNVNGraphicsFirmwareMemory { get; }
[StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)]
extern public static int switchMaxWorkerMultiple
{
[NativeMethod("GetSwitchKMaxWorkerMultiple")]
get;
[NativeMethod("SetSwitchKMaxWorkerMultiple")]
set;
}
// Controls the behavior of Switch's auto-changing screen resolution
[NativeProperty("switchScreenResolutionBehavior", TargetType.Field)]
extern public static ScreenResolutionBehavior screenResolutionBehavior { get; set; }
[NativeProperty("switchNMETAOverride", TargetType.Function)]
extern static private string NMETAOverrideInternal { get; set; }
public static string NMETAOverride
{
get
{
string path = NMETAOverrideInternal;
if (string.IsNullOrEmpty(path))
return "";
return path;
}
set
{
NMETAOverrideInternal = value;
}
}
public static string NMETAOverrideFullPath
{
get
{
string path = NMETAOverrideInternal;
if (string.IsNullOrEmpty(path))
return "";
if (!Path.IsPathRooted(path))
path = Path.GetFullPath(path);
return path;
}
}
public static string[] compilerFlags
{
get
{
return compilerFlagsInternal.Split(new char[] {' '});
}
set
{
compilerFlagsInternal = string.Join(" ", value);
}
}
[NativeProperty("switchCompilerFlags", TargetType.Function)]
extern private static string compilerFlagsInternal { get; set; }
//Additional NSO Dependencies
[NativeProperty("switchNSODependencies", TargetType.Function)]
extern public static string nsoDependencies { get; set; }
[NativeProperty("switchSupportedNpadStyles", TargetType.Field)]
extern public static SupportedNpadStyle supportedNpadStyles { get; set; }
[NativeProperty("switchNativeFsCacheSize", TargetType.Field)]
extern public static int nativeFsCacheSize { get; set; }
[NativeProperty("switchIsHoldTypeHorizontal", TargetType.Field)]
extern public static bool isHoldTypeHorizontal { get; set; }
[NativeProperty("switchSupportedNpadCount", TargetType.Field)]
extern public static int supportedNpadCount { get; set; }
[NativeProperty("switchEnableTouchScreen", TargetType.Field)]
extern public static bool enableTouchScreen { get; set; }
// SocketConfigEnabled
[NativeProperty("switchSocketConfigEnabled", TargetType.Field)]
extern public static bool socketConfigEnabled { get; set; }
// Tcp Initial Send Buffer Size
[NativeProperty("switchTcpInitialSendBufferSize", TargetType.Field)]
extern public static int tcpInitialSendBufferSize { get; set; }
// Tcp Initial Receive Buffer Size
[NativeProperty("switchTcpInitialReceiveBufferSize", TargetType.Field)]
extern public static int tcpInitialReceiveBufferSize { get; set; }
// Tcp Auto Send Buffer Size Max
[NativeProperty("switchTcpAutoSendBufferSizeMax", TargetType.Field)]
extern public static int tcpAutoSendBufferSizeMax { get; set; }
// Tcp Auto Receive Buffer Size Max
[NativeProperty("switchTcpAutoReceiveBufferSizeMax", TargetType.Field)]
extern public static int tcpAutoReceiveBufferSizeMax { get; set; }
// Udp Send Buffer Size
[NativeProperty("switchUdpSendBufferSize", TargetType.Field)]
extern public static int udpSendBufferSize { get; set; }
// Udp Receive Buffer Size
[NativeProperty("switchUdpReceiveBufferSize", TargetType.Field)]
extern public static int udpReceiveBufferSize { get; set; }
// Socket Buffer Efficiency
[NativeProperty("switchSocketBufferEfficiency", TargetType.Field)]
extern public static int socketBufferEfficiency { get; set; }
// Socket Initialize Enabled
[NativeProperty("switchSocketInitializeEnabled", TargetType.Field)]
extern public static bool socketInitializeEnabled { get; set; }
// Network Interface Manager Initialize Enabled
[NativeProperty("switchNetworkInterfaceManagerInitializeEnabled", TargetType.Field)]
extern public static bool networkInterfaceManagerInitializeEnabled { get; set; }
// HTCS for player connection
[NativeProperty("switchDisableHTCSPlayerConnection", TargetType.Field)]
extern public static bool disableHTCSPlayerConnection { get; set; }
// Forces all FMOD threads to use nn::os::LowestThreadPriority
[NativeProperty("switchUseLegacyFmodPriorities", TargetType.Field)]
extern public static bool switchUseLegacyFmodPriorities { get; set; }
// Controls if calls to nn::os::YieldThread are swapped with calls to nn::os::SleepThread({switchMicroSleepForYieldTime}us)
[NativeProperty("switchUseMicroSleepForYield", TargetType.Field)]
extern public static bool switchUseMicroSleepForYield { get; set; }
// Number of micro seconds used by switchUseMicroSleepForYield
[NativeProperty("switchMicroSleepForYieldTime", TargetType.Field)]
extern public static int switchMicroSleepForYieldTime { get; set; }
//Enable the RamDisk support
[NativeProperty("switchEnableRamDiskSupport", TargetType.Field)]
extern public static bool switchEnableRamDiskSupport { get; set; }
//To specify how much space should be allocated for the ram disk
[NativeProperty("switchRamDiskSpaceSize", TargetType.Field)]
extern public static int switchRamDiskSpaceSize { get; set; }
}
}
}
| UnityCsReference/Editor/Mono/PlayerSettingsSwitch.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/PlayerSettingsSwitch.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 6399
} | 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.Collections.Generic;
using UnityEditor.AssetImporters;
using UnityEditor.SceneManagement;
using UnityEditor.UIElements;
using UnityEngine;
namespace UnityEditor
{
[CustomEditor(typeof(PrefabImporter))]
[CanEditMultipleObjects]
internal class PrefabImporterEditor : AssetImporterEditor
{
static class Styles
{
public static GUIContent missingScriptsHelpText = EditorGUIUtility.TrTextContent("Prefab has missing scripts. Open Prefab to fix the issue.");
public static GUIContent missingSerializeReferenceHelpText = EditorGUIUtility.TrTextContent("Prefab has missing SerializeReference Types. Open Prefab to fix the issue. Changing the Prefab directly will cause those types to be lost.");
public static GUIContent multiSelectionMissingScriptsHelpText = EditorGUIUtility.TrTextContent("Some of the selected Prefabs have missing scripts and needs to be fixed before editing them. Click to Open Prefab to fix the issue.");
public static GUIContent savingFailedHelpText = EditorGUIUtility.TrTextContent("Saving has failed. Check the Console window to get more insight into what needs to be fixed on the Prefab Asset.\n\nOpen Prefab to fix the issue.");
public static GUIContent variantOfText = EditorGUIUtility.TrTextContent("Variant Parent");
public static string localizedTitleMultiplePrefabs = L10n.Tr("Prefab Assets");
public static string localizedTitleSinglePrefab = L10n.Tr("Prefab Asset");
public static GUIStyle openButtonStyle = "AC Button";
public static readonly GUIContent hierarchyIcon = EditorGUIUtility.IconContent("UnityEditor.SceneHierarchyWindow");
public const int kHierarchyIconWidth = 44;
}
int m_HasMixedBaseVariants = -1;
double m_NextUpdate;
List<string> m_PrefabsWithMissingScript = new List<string>();
bool m_SavingHasFailed;
bool m_ContainsMissingSerializeReferenceType;
struct TrackedAsset
{
public GameObject asset;
public string guid;
public Hash128 hash;
}
readonly List<Component> m_TempComponentsResults = new List<Component>();
readonly List<TrackedAsset> m_DirtyPrefabAssets = new List<TrackedAsset>();
bool m_HasPendingChanges;
public override bool showImportedObject { get { return !hasMissingScripts; } }
internal override bool CanOpenMultipleObjects() { return false; }
internal override bool ShouldTryToMakeEditableOnOpen() { return false; }
bool isTextFieldCaretShowing
{
get { return EditorGUI.IsEditingTextField() && !EditorGUIUtility.textFieldHasSelection; }
}
internal bool readyToAutoSave
{
get { return !m_SavingHasFailed && !hasMissingScripts && GUIUtility.hotControl == 0 && !isTextFieldCaretShowing && !EditorApplication.isCompiling; }
}
bool hasMissingScripts
{
get { return m_PrefabsWithMissingScript.Count > 0; }
}
public override void OnEnable()
{
base.OnEnable();
ObjectChangeEvents.changesPublished += ObjectChangeEventPublished;
}
public override void OnDisable()
{
if (m_HasPendingChanges)
{
EditorApplication.update -= WaitToApplyChanges;
m_HasPendingChanges = false;
SaveDirtyPrefabAssets(false);
}
ObjectChangeEvents.changesPublished -= ObjectChangeEventPublished;
base.OnDisable();
}
private void ObjectChangeEventPublished(ref ObjectChangeEventStream stream)
{
if (m_HasPendingChanges)
return;
for (int i = 0; i < stream.length; ++i)
{
if (stream.GetEventType(i) == ObjectChangeKind.ChangeGameObjectOrComponentProperties)
{
stream.GetChangeGameObjectOrComponentPropertiesEvent(i, out var changeGameObjectOrComponent);
var asset = EditorUtility.InstanceIDToObject(changeGameObjectOrComponent.instanceId);
if (IsTargetAsset(asset))
{
if (!EditorFocusMonitor.AreBindableElementsSelected() && readyToAutoSave)
{
SaveDirtyPrefabAssets(true);
}
else
{
m_HasPendingChanges = true;
EditorApplication.update += WaitToApplyChanges;
}
return;
}
}
}
}
protected override void Awake()
{
base.Awake();
m_ContainsMissingSerializeReferenceType = false;
foreach (var prefabAssetRoot in assetTargets)
{
if (PrefabUtility.HasInvalidComponent(prefabAssetRoot))
{
m_PrefabsWithMissingScript.Add(AssetDatabase.GetAssetPath(prefabAssetRoot));
}
if (PrefabUtility.IsPartOfPrefabAsset(prefabAssetRoot) && PrefabUtility.HasManagedReferencesWithMissingTypes(prefabAssetRoot))
{
m_ContainsMissingSerializeReferenceType = true;
}
}
m_PrefabsWithMissingScript.Sort();
}
void OnDestroy()
{
// Ensure to save unsaved changes (regardless of hotcontrol etc)
if (!m_SavingHasFailed && !hasMissingScripts)
SaveDirtyPrefabAssets(false);
}
void WaitToApplyChanges()
{
var time = EditorApplication.timeSinceStartup;
if (time > m_NextUpdate)
{
m_NextUpdate = time + 0.2;
if (!EditorFocusMonitor.AreBindableElementsSelected() && readyToAutoSave)
SaveDirtyPrefabAssets(true);
}
}
// Internal for testing framework
internal void SaveDirtyPrefabAssets(bool reloadInspectors)
{
if (assetTargets == null)
return;
if (assetTarget == null)
return;
m_DirtyPrefabAssets.Clear();
foreach (var asset in assetTargets)
{
// The asset could have been deleted when this method is called from OnDestroy().
// E.g delete the selected prefab asset from the Project Browser.
if (asset == null)
continue;
if (!EditorUtility.IsPersistent(asset))
continue;
if (!(asset is GameObject))
continue;
var rootGameObject = (GameObject)asset;
if (IsDirty(rootGameObject))
{
string currentGuid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(rootGameObject));
var changeTracking = new TrackedAsset()
{
asset = rootGameObject,
guid = currentGuid,
hash = AssetDatabase.GetSourceAssetFileHash(currentGuid)
};
m_DirtyPrefabAssets.Add(changeTracking);
}
}
if (m_DirtyPrefabAssets.Count > 0)
{
AssetDatabase.StartAssetEditing();
try
{
foreach (var trackedAsset in m_DirtyPrefabAssets)
{
bool savedSuccesfully;
PrefabUtility.SavePrefabAsset(trackedAsset.asset, out savedSuccesfully);
if (!savedSuccesfully)
{
string title = L10n.Tr("Saving Failed");
string message = L10n.Tr("Check the Console window to get more insight into what needs to be fixed on the Prefab Asset.\n\nYou can open Prefab Mode to fix any issues on child GameObjects");
EditorUtility.DisplayDialog(title, message, L10n.Tr("OK"));
m_SavingHasFailed = true;
break;
}
}
}
finally
{
AssetDatabase.StopAssetEditing();
if (reloadInspectors)
{
foreach (var trackedAsset in m_DirtyPrefabAssets)
{
if (AssetDatabase.GetSourceAssetFileHash(trackedAsset.guid) != trackedAsset.hash)
{
// We only call ForceReloadInspectors (and not ForceRebuildInspectors) to ensure local inspector state
// is not destroyed, such as a foldout state maintained by an editor (case 1255013).
// And we need to reload Prefab asset inspectors in order for the preview to be regenerated since the preview shows
// an instantiated Prefab. E.g disable a MeshRenderer on a Prefab Asset and the mesh should be hidden in the preview.
EditorUtility.ForceReloadInspectors();
break;
}
}
}
// We reset the flag after the changes have been applied in order to avoid a new change being detected from the save operation.
if (m_HasPendingChanges)
{
EditorApplication.update -= WaitToApplyChanges;
m_HasPendingChanges = false;
}
}
}
}
bool IsTargetAsset(Object obj)
{
if (obj is Component component)
obj = component.gameObject;
foreach (var asset in assetTargets)
{
if (obj == asset)
return true;
}
return false;
}
bool IsDirty(GameObject prefabAssetRoot)
{
if (prefabAssetRoot == null)
return false;
if (EditorUtility.IsDirty(prefabAssetRoot))
return true;
// For Prefab Variant Asset we need to also check if the instance handle is dirty
// since this happens when the list of removed component changes
var instanceHandle = PrefabUtility.GetPrefabInstanceHandle(prefabAssetRoot);
if (instanceHandle != null)
if (EditorUtility.IsDirty(instanceHandle))
return true;
prefabAssetRoot.GetComponents(m_TempComponentsResults);
foreach (var component in m_TempComponentsResults)
{
if (EditorUtility.IsDirty(component))
return true;
if (component is Renderer)
{
Renderer r = component as Renderer;
foreach (Material mat in r.sharedMaterials)
{
if (EditorUtility.IsDirty(mat) && AssetDatabase.IsSubAsset(mat))
return AssetDatabase.GetAssetPath(mat) == AssetDatabase.GetAssetPath(prefabAssetRoot);
}
}
}
return false;
}
void CacheHasMixedBaseVariants()
{
if (m_HasMixedBaseVariants >= 0)
return; // already cached
var firstVariantParent = PrefabUtility.GetCorrespondingObjectFromSource(assetTarget);
if (firstVariantParent == null)
return;
m_HasMixedBaseVariants = 0;
foreach (var t in assetTargets)
{
var variantParent = PrefabUtility.GetCorrespondingObjectFromSource(t);
if (variantParent != firstVariantParent)
{
m_HasMixedBaseVariants = 1;
break;
}
}
}
protected override bool needsApplyRevert => false;
internal override string targetTitle
{
get
{
if (assetTargets == null || assetTargets.Length == 1 || !m_AllowMultiObjectAccess)
return assetTarget != null ? assetTarget.name + " (" + Styles.localizedTitleSinglePrefab + ")" : Styles.localizedTitleSinglePrefab;
else
return assetTargets.Length + " " + Styles.localizedTitleMultiplePrefabs;
}
}
void PrefabFamilyButton()
{
if (EditorGUILayout.DropdownButton(GUIContent.none, FocusType.Passive, GUILayout.MaxWidth(Styles.kHierarchyIconWidth)))
{
if (!PrefabFamilyPopup.isOpen)
PopupWindow.Show(GUILayoutUtility.topLevel.GetLast(), new PrefabFamilyPopup((GameObject)assetTarget));
GUIUtility.ExitGUI();
}
var rect = new Rect(GUILayoutUtility.topLevel.GetLast());
rect.x += 6;
EditorGUI.LabelField(rect, Styles.hierarchyIcon);
}
internal override void OnHeaderControlsGUI()
{
GUILayout.FlexibleSpace();
using (new EditorGUI.DisabledScope(targets.Length != 1))
{
PrefabFamilyButton();
}
if (!ShouldHideOpenButton())
{
var assets = assetTargets;
ShowOpenButton(assets, assetTarget != null);
}
var variantParent = PrefabUtility.GetCorrespondingObjectFromSource(assetTarget) as GameObject;
if (variantParent != null)
{
// OnHeaderControlsGUI() is called within a BeginHorizontal() scope so to create a new line
// we end and start a new BeginHorizontal().
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
using (new EditorGUI.DisabledScope(true))
{
CacheHasMixedBaseVariants();
EditorGUI.showMixedValue = m_HasMixedBaseVariants == 1;
var oldLabelWidth = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = 90;
EditorGUILayout.ObjectField(Styles.variantOfText, variantParent, typeof(GameObject), false);
EditorGUIUtility.labelWidth = oldLabelWidth;
EditorGUI.showMixedValue = false;
}
}
}
public override void OnInspectorGUI()
{
if (assetTarget is DefaultAsset)
{
return;
}
if (hasMissingScripts)
{
if (assetTargets.Length > 1)
{
// List all assets that have missing scripts (but only if we have a multi-selection)
GUILayout.Space(5);
EditorGUILayout.HelpBox(Styles.multiSelectionMissingScriptsHelpText.text, MessageType.Warning, true);
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(10);
using (new EditorGUILayout.VerticalScope())
{
foreach (var prefabAssetPath in m_PrefabsWithMissingScript)
{
if (GUILayout.Button(prefabAssetPath, EditorStyles.label))
{
PrefabStageUtility.OpenPrefab(prefabAssetPath);
}
}
}
}
}
else
{
EditorGUILayout.HelpBox(Styles.missingScriptsHelpText.text, MessageType.Warning, true);
}
}
else if (m_SavingHasFailed)
{
EditorGUILayout.HelpBox(Styles.savingFailedHelpText.text, MessageType.Warning, true);
}
else if (m_ContainsMissingSerializeReferenceType)
{
EditorGUILayout.HelpBox(Styles.missingSerializeReferenceHelpText.text, MessageType.Warning, true);
}
}
}
}
| UnityCsReference/Editor/Mono/Prefabs/PrefabImporterEditor.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Prefabs/PrefabImporterEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 8549
} | 338 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEngine;
namespace UnityEditor
{
[AssetFileNameExtension("curves", "curvesNormalized", "particleCurves", "particleCurvesSigned", "particleDoubleCurves", "particleDoubleCurvesSigned")]
[ExcludeFromPreset]
class CurvePresetLibrary : PresetLibrary
{
[SerializeField]
List<CurvePreset> m_Presets = new List<CurvePreset>();
public override int Count()
{
return m_Presets.Count;
}
public override object GetPreset(int index)
{
return m_Presets[index].curve;
}
public override void Add(object presetObject, string presetName)
{
AnimationCurve curve = presetObject as AnimationCurve;
if (curve == null)
{
Debug.LogError("Wrong type used in CurvePresetLibrary");
return;
}
AnimationCurve copy = new AnimationCurve(curve.keys);
copy.preWrapMode = curve.preWrapMode;
copy.postWrapMode = curve.postWrapMode;
m_Presets.Add(new CurvePreset(copy, presetName));
}
public override void Replace(int index, object newPresetObject)
{
AnimationCurve curve = newPresetObject as AnimationCurve;
if (curve == null)
{
Debug.LogError("Wrong type used in CurvePresetLibrary");
return;
}
AnimationCurve copy = new AnimationCurve(curve.keys);
copy.preWrapMode = curve.preWrapMode;
copy.postWrapMode = curve.postWrapMode;
m_Presets[index].curve = copy;
}
public override void Remove(int index)
{
m_Presets.RemoveAt(index);
}
public override void Move(int index, int destIndex, bool insertAfterDestIndex)
{
PresetLibraryHelpers.MoveListItem(m_Presets, index, destIndex, insertAfterDestIndex);
}
public override void Draw(Rect rect, int index)
{
DrawInternal(rect, m_Presets[index].curve);
}
public override void Draw(Rect rect, object presetObject)
{
DrawInternal(rect, presetObject as AnimationCurve);
}
private void DrawInternal(Rect rect, AnimationCurve animCurve)
{
if (animCurve == null)
return;
EditorGUIUtility.DrawCurveSwatch(rect, animCurve, null, new Color(0.8f, 0.8f, 0.8f, 1.0f), EditorGUI.kCurveBGColor);
}
public override string GetName(int index)
{
return m_Presets[index].name;
}
public override void SetName(int index, string presetName)
{
m_Presets[index].name = presetName;
}
[System.Serializable]
class CurvePreset
{
[SerializeField]
string m_Name;
[SerializeField]
AnimationCurve m_Curve;
public CurvePreset(AnimationCurve preset, string presetName)
{
curve = preset;
name = presetName;
}
public CurvePreset(AnimationCurve preset, AnimationCurve preset2, string presetName)
{
curve = preset;
name = presetName;
}
public AnimationCurve curve
{
get { return m_Curve; }
set { m_Curve = value; }
}
public string name
{
get { return m_Name; }
set { m_Name = value; }
}
}
}
}
| UnityCsReference/Editor/Mono/PresetLibraries/CurvePresetLibrary.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/PresetLibraries/CurvePresetLibrary.cs",
"repo_id": "UnityCsReference",
"token_count": 1854
} | 339 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace UnityEditor
{
static class GlobSearchUtilities
{
static readonly Regex k_BasicSymbolsRegex = new Regex(@"(?<range>\\\[..+?\])|(?<dstarfold>\\\*\\\*/)|(?<dstar>\\\*\\\*)|(?<star>\\\*)|(?<single>\\\?)");
static readonly Regex k_ComplexSymbolsRegex = new Regex(@"(?<or>\\\(.+?(?:\\\|.+?)+\\\))");
static Dictionary<string, Func<string, string>> s_GlobToRegexMatch;
static GlobSearchUtilities()
{
s_GlobToRegexMatch = new Dictionary<string, Func<string, string>>();
//Match any number of characters, where characters exist - end in a fold.
s_GlobToRegexMatch.Add("dstarfold", match => "(.+/)?");
//Match any number of characters
s_GlobToRegexMatch.Add("dstar", match => ".*");
//Match any number of non-"/" characters
s_GlobToRegexMatch.Add("star", match => @"[^/]*");
//Match a single non-"/" character
s_GlobToRegexMatch.Add("single", match => @"[^/]");
s_GlobToRegexMatch.Add("range", match => match.Replace(@"\[", "["));
s_GlobToRegexMatch.Add("or", match => match.Replace(@"\(", "(").Replace(@"\|", "|").Replace(@"\)", ")"));
}
static string GlobToRegex(string glob)
{
// Escape any glob character that could be interpreted in the regex
var regex = Regex.Escape(glob);
// Handle basic symbols replacement first
regex = k_BasicSymbolsRegex.Replace(regex, ReplaceGlobGroups);
// Complex patterns are replaced in a second pass because they may contain basic symbols that we want to replace first.
regex = k_ComplexSymbolsRegex.Replace(regex, ReplaceGlobGroups);
// Add ^ and $ to make sure the search is always done on the full path.
// Searches like "Editor" should match the same as "**Editor" and looks only for Editor folders or file in any subfolder
// This is why we are always adding optional folder path at the beginning and option folder ending character in the end.
return $"^(.+/)?{regex}/?$";
}
static string ReplaceGlobGroups(Match match)
{
foreach (var replace in s_GlobToRegexMatch)
{
if (match.Groups[replace.Key].Success)
{
return replace.Value(match.Value);
}
}
return match.Value;
}
static bool IsRegexValid(string regex)
{
try
{
// Regex.Match throws and ArgumentException when the regex is not valid,
// we use this to make sure the generated regex can be used during a search.
Regex.Match("", regex);
}
catch (ArgumentException)
{
return false;
}
return true;
}
internal static IEnumerable<string> GlobToRegex(this SearchFilter filter)
{
return filter.globs.Select(GlobToRegex).Where(IsRegexValid);
}
}
}
| UnityCsReference/Editor/Mono/ProjectBrowser/GlobSearchUtilities.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/ProjectBrowser/GlobSearchUtilities.cs",
"repo_id": "UnityCsReference",
"token_count": 1518
} | 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 UnityEditor.Inspector.GraphicsSettingsInspectors;
using UnityEditor.Rendering.Settings;
using UnityEngine.Rendering;
using UnityEngine.UIElements;
namespace UnityEditor.Rendering
{
// We need a base non generic to fetch with TypeCache. But User should use the
// generic type as the generic is used to retrieve the IRenderPipelineGraphicsSettings
// used.
// This version indicates that it will be applied to any IRenderPipelineGraphicsSettings
public interface IRenderPipelineGraphicsSettingsContextMenu
{
void PopulateContextMenu(IRenderPipelineGraphicsSettings setting, PropertyDrawer drawer, ref GenericMenu menu);
int priority => 0;
}
// This version is specialized for T only
public interface IRenderPipelineGraphicsSettingsContextMenu<T> : IRenderPipelineGraphicsSettingsContextMenu
where T : class, IRenderPipelineGraphicsSettings
{
void PopulateContextMenu(T setting, PropertyDrawer drawer, ref GenericMenu menu);
void IRenderPipelineGraphicsSettingsContextMenu.PopulateContextMenu(IRenderPipelineGraphicsSettings setting, PropertyDrawer drawer, ref GenericMenu menu)
=> PopulateContextMenu(setting as T, drawer, ref menu);
}
struct RenderPipelineGraphicsSettingsContextMenuComparer : IComparer<IRenderPipelineGraphicsSettingsContextMenu>, IComparer<(IRenderPipelineGraphicsSettingsContextMenu, IEnumerable<IRenderPipelineGraphicsSettings>)>
{
//Sorting is done first by priority, but when priority
//are the same, we sort by type name to have a stable result.
public int Compare(IRenderPipelineGraphicsSettingsContextMenu m1, IRenderPipelineGraphicsSettingsContextMenu m2)
{
var compResult = m1.priority.CompareTo(m2.priority);
if (compResult == 0)
compResult = m1.GetType().FullName.CompareTo(m2.GetType().FullName);
return compResult;
}
public int Compare((IRenderPipelineGraphicsSettingsContextMenu, IEnumerable<IRenderPipelineGraphicsSettings>) m1, (IRenderPipelineGraphicsSettingsContextMenu, IEnumerable<IRenderPipelineGraphicsSettings>) m2)
=> Compare(m1.Item1, m2.Item1);
}
static class RenderPipelineGraphicsSettingsContextMenuManager
{
// typeof(IRenderPipelineGraphicsSettings) is used for global menu entries.
static Lazy<Dictionary<Type, List<IRenderPipelineGraphicsSettingsContextMenu>>> s_MenuEntries = new (Initialize);
static Dictionary<Type, List<IRenderPipelineGraphicsSettingsContextMenu>> Initialize()
{
RenderPipelineGraphicsSettingsContextMenuComparer comparer = new();
Dictionary<Type, List<IRenderPipelineGraphicsSettingsContextMenu>> menus = new();
Type GetTargetGraphicsSettingsType(Type menuType)
{
var interfaces = menuType.GetInterfaces();
foreach (var @interface in interfaces)
if (@interface.IsGenericType && @interface.GetGenericTypeDefinition() == typeof(IRenderPipelineGraphicsSettingsContextMenu<>))
return @interface.GetGenericArguments()[0];
return typeof(IRenderPipelineGraphicsSettings);
}
void AddToList(Type menuType)
{
var instance = Activator.CreateInstance(menuType, true) as IRenderPipelineGraphicsSettingsContextMenu;
Type rpgsType = GetTargetGraphicsSettingsType(menuType);
if (!menus.ContainsKey(rpgsType))
menus[rpgsType] = new();
menus[rpgsType].Add(instance);
}
var menuTypes = TypeCache.GetTypesDerivedFrom<IRenderPipelineGraphicsSettingsContextMenu>();
foreach (Type menuType in menuTypes)
{
if (menuType.IsAbstract)
continue;
AddToList(menuType);
}
foreach (var list in menus.Values)
list.Sort(comparer);
return menus;
}
static internal void PopulateContextMenu(IEnumerable<IRenderPipelineGraphicsSettings> graphicsSettings, SerializedProperty property, ref GenericMenu menu)
{
RenderPipelineGraphicsSettingsContextMenuComparer comparer = new();
var drawer = ScriptAttributeUtility.GetHandler(property).propertyDrawer;
var defaultMenuPopulators = s_MenuEntries.Value.GetValueOrDefault(typeof(IRenderPipelineGraphicsSettings));
List<(IRenderPipelineGraphicsSettingsContextMenu populator, IEnumerable<IRenderPipelineGraphicsSettings> data)> menuPopupators = new();
foreach(var defaultMenuPopulator in defaultMenuPopulators)
menuPopupators.Add((defaultMenuPopulator, graphicsSettings));
foreach(var settings in graphicsSettings)
{
if (s_MenuEntries.Value.TryGetValue(settings.GetType(), out var additionalSpecificMenuPopulators))
{
foreach (var item in additionalSpecificMenuPopulators)
menuPopupators.Add((item, new IRenderPipelineGraphicsSettings[] { settings }));
}
}
menuPopupators.Sort(comparer);
foreach (var menuPopulator in menuPopupators)
foreach(var settings in menuPopulator.data)
menuPopulator.populator.PopulateContextMenu(settings, drawer, ref menu);
}
}
struct ResetImplementation : IRenderPipelineGraphicsSettingsContextMenu
{
const string k_Label = "Reset";
// Keeping space in case one want to modify after the Reset
public int priority => int.MaxValue - 1;
List<IRenderPipelineGraphicsSettings> targets;
public void PopulateContextMenu(IRenderPipelineGraphicsSettings setting, PropertyDrawer _, ref GenericMenu menu)
{
if (menu.menuItems.Count > 0)
{
if (menu.menuItems[menu.menuItems.Count - 1].userData is ResetImplementation implementation)
{
implementation.targets.Add(setting);
return;
}
else if (!menu.menuItems[menu.menuItems.Count - 1].separator)
menu.AddSeparator("");
}
if (EditorApplication.isPlaying)
menu.AddDisabledItem(EditorGUIUtility.TrTextContent(k_Label), false);
else
{
targets = new() { setting };
menu.AddItem(EditorGUIUtility.TrTextContent(k_Label), false, (implementation) => Reset((ResetImplementation)implementation), this);
}
}
static void Reset(ResetImplementation implementation)
{
var alreadyOpenedWindow = EditorWindow.GetWindow<ProjectSettingsWindow>();
var renderPipelineType = RenderPipelineEditorUtility.GetPipelineTypeFromPipelineAssetType(GraphicsSettingsInspectorUtility.GetRenderPipelineAssetTypeForSelectedTab(alreadyOpenedWindow.rootVisualElement));
foreach (var target in implementation.targets)
RenderPipelineGraphicsSettingsManager.ResetRenderPipelineGraphicsSettings(target.GetType(), renderPipelineType);
}
}
}
| UnityCsReference/Editor/Mono/RenderPipelineGraphicsSettingsContextMenu.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/RenderPipelineGraphicsSettingsContextMenu.cs",
"repo_id": "UnityCsReference",
"token_count": 2994
} | 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 UnityEditor.IMGUI.Controls;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace UnityEditor.SceneManagement
{
public sealed class MainStage : Stage
{
static StateCache<MainStageHierarchyState> s_StateCache = new StateCache<MainStageHierarchyState>("Library/StateCache/MainStageHierarchy/");
internal static MainStage CreateMainStage()
{
var mainStage = CreateInstance<MainStage>();
mainStage.name = "MainStage";
return mainStage;
}
internal override int sceneCount { get { return SceneManager.sceneCount; } }
internal override Scene GetSceneAt(int index)
{
return SceneManager.GetSceneAt(index);
}
protected internal override bool OnOpenStage()
{
// do nothing as the main stage is always in memory
return true;
}
protected override void OnCloseStage()
{
Debug.LogError("The MainStage should not be destroyed. This is not supported.");
}
protected internal override GUIContent CreateHeaderContent()
{
return new GUIContent(
"Scenes",
EditorGUIUtility.IconContent("SceneAsset Icon").image);
}
internal override BreadcrumbBar.Item CreateBreadcrumbItem()
{
BreadcrumbBar.Item item = base.CreateBreadcrumbItem();
item.separatorstyle = BreadcrumbBar.SeparatorStyle.None;
return item;
}
internal override ulong GetSceneCullingMask()
{
return SceneCullingMasks.MainStageSceneViewObjects;
}
internal override void SyncSceneViewToStage(SceneView sceneView)
{
sceneView.customScene = new Scene();
sceneView.customParentForNewGameObjects = null;
// NOTE: We always set overrideSceneCullingMask to ensure the gizmo handling in the Entities package works (in dots search for 'gizmo hack').
// This ensures normal picking works with the livelink since the SceneCullingMasks.MainStageSceneViewObjects is part of the mask while the gizmo bit is also set.
// When the gizmo hack is removed in dots we can set 'sceneView.overrideSceneCullingMask = 0'.
sceneView.overrideSceneCullingMask = GetSceneCullingMask();
}
internal override void SyncSceneHierarchyToStage(SceneHierarchyWindow sceneHierarchyWindow)
{
var sceneHierarchy = sceneHierarchyWindow.sceneHierarchy;
sceneHierarchy.customScenes = null;
sceneHierarchy.customParentForNewGameObjects = null;
sceneHierarchy.SetCustomDragHandler(null);
}
internal override void PlaceGameObjectInStage(GameObject rootGameObject)
{
if (rootGameObject.transform.parent != null)
throw new ArgumentException("GameObject has a transform parent, only root GameObjects are valid", "rootGameObject");
if (StageUtility.GetStageHandle(rootGameObject) != StageUtility.GetMainStageHandle())
SceneManager.MoveGameObjectToScene(rootGameObject, SceneManager.GetActiveScene());
}
internal override void SaveHierarchyState(SceneHierarchyWindow hierarchyWindow)
{
if (!isValid)
return;
Hash128 key = StageUtility.CreateWindowAndStageIdentifier(hierarchyWindow.windowGUID, this);
var state = s_StateCache.GetState(key);
if (state == null)
state = new MainStageHierarchyState();
state.SaveStateFromHierarchy(hierarchyWindow, this);
s_StateCache.SetState(key, state);
}
MainStageHierarchyState GetStoredHierarchyState(SceneHierarchyWindow hierarchyWindow)
{
Hash128 key = StageUtility.CreateWindowAndStageIdentifier(hierarchyWindow.windowGUID, this);
return s_StateCache.GetState(key);
}
internal override void LoadHierarchyState(SceneHierarchyWindow hierarchy)
{
if (!isValid)
return;
var state = GetStoredHierarchyState(hierarchy);
if (state != null)
state.LoadStateIntoHierarchy(hierarchy, this);
else
OnFirstTimeOpenStageInSceneHierachyWindow(hierarchy);
}
}
}
| UnityCsReference/Editor/Mono/SceneManagement/StageManager/MainStage.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/SceneManagement/StageManager/MainStage.cs",
"repo_id": "UnityCsReference",
"token_count": 1881
} | 342 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
using UnityEngine.Rendering;
using UnityEditor.Rendering;
using System.Linq;
using System;
namespace UnityEditor
{
//Attribute that should be deprecated in 2020.1
//Will be replaced by ScriptableRenderPipelineAttribute
//Kept for package compatibility and user SRP compatibility at the moment
public interface ILightingExplorerExtension
{
LightingExplorerTab[] GetContentTabs();
void OnEnable();
void OnDisable();
}
[EditorWindowTitle(title = "Light Explorer", icon = "Lighting")]
internal class LightingExplorerWindow : EditorWindow
{
LightingExplorerTab[] m_TableTabs;
GUIContent[] m_TabTitles;
int m_SelectedTab = 0;
System.Type m_CurrentSRPType = null;
ILightingExplorerExtension m_CurrentLightingExplorerExtension = null;
static ILightingExplorerExtension s_DefaultLightingExplorerExtension = null;
[MenuItem("Window/Rendering/Light Explorer", priority = 2, secondaryPriority = 1)]
static void CreateLightingExplorerWindow()
{
LightingExplorerWindow window = EditorWindow.GetWindow<LightingExplorerWindow>();
window.minSize = new Vector2(500, 250);
window.Show();
}
void OnEnable()
{
titleContent = GetLocalizedTitleContent();
UpdateTabs();
EditorApplication.searchChanged += Repaint;
Repaint();
}
void OnDisable()
{
OnDisableTabsAndExtension();
EditorApplication.searchChanged -= Repaint;
}
void OnDisableTabsAndExtension()
{
if (m_TableTabs != null)
{
for (int i = 0; i < m_TableTabs.Length; i++)
{
m_TableTabs[i].OnDisable();
}
}
if (m_CurrentLightingExplorerExtension != null)
{
m_CurrentLightingExplorerExtension.OnDisable();
}
}
void OnInspectorUpdate()
{
if (m_TableTabs != null && (int)m_SelectedTab >= 0 && (int)m_SelectedTab < m_TableTabs.Length)
{
m_TableTabs[(int)m_SelectedTab].OnInspectorUpdate();
}
}
void OnSelectionChange()
{
if (m_TableTabs != null)
{
for (int i = 0; i < m_TableTabs.Length; i++)
{
if (i == (m_TableTabs.Length - 1)) // last tab containing materials
{
int[] selectedIds = UnityEngine.Object.FindObjectsByType<MeshRenderer>(UnityEngine.FindObjectsSortMode.InstanceID).Where((MeshRenderer mr) => {
return Selection.instanceIDs.Contains(mr.gameObject.GetInstanceID());
}).SelectMany(meshRenderer => meshRenderer.sharedMaterials).Where((Material m) => {
return m != null && (m.globalIlluminationFlags & MaterialGlobalIlluminationFlags.AnyEmissive) != 0;
}).Select(m => m.GetInstanceID()).Union(Selection.instanceIDs).Distinct().ToArray();
m_TableTabs[i].OnSelectionChange(selectedIds);
}
else
m_TableTabs[i].OnSelectionChange();
}
}
Repaint();
}
void OnHierarchyChange()
{
if (m_TableTabs != null)
{
for (int i = 0; i < m_TableTabs.Length; i++)
{
m_TableTabs[i].OnHierarchyChange();
}
}
}
void OnGUI()
{
UpdateTabs();
EditorGUIUtility.labelWidth = 130;
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (m_TabTitles != null)
m_SelectedTab = GUILayout.Toolbar(m_SelectedTab, m_TabTitles, "LargeButton", GUI.ToolbarButtonSize.FitToContents);
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
if (m_TableTabs != null && (int)m_SelectedTab >= 0 && (int)m_SelectedTab < m_TableTabs.Length)
m_TableTabs[(int)m_SelectedTab].OnGUI();
EditorGUILayout.Space();
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
}
private System.Type GetSRPType()
{
System.Type SRPType = null;
if (GraphicsSettings.currentRenderPipeline != null)
{
SRPType = GraphicsSettings.currentRenderPipeline.GetType();
}
return SRPType;
}
private void UpdateTabs()
{
var SRPType = GetSRPType();
if (m_CurrentLightingExplorerExtension == null || m_CurrentSRPType != SRPType)
{
m_CurrentSRPType = SRPType;
OnDisableTabsAndExtension();
m_CurrentLightingExplorerExtension = GetLightExplorerExtension(SRPType);
m_CurrentLightingExplorerExtension.OnEnable();
m_SelectedTab = EditorSettings.defaultBehaviorMode == EditorBehaviorMode.Mode2D ? /* 2D Lights */ 1 : /* Lights */ 0;
if (m_CurrentLightingExplorerExtension.GetContentTabs() == null || m_CurrentLightingExplorerExtension.GetContentTabs().Length == 0)
{
throw new ArgumentException("There must be atleast 1 content tab defined for the Lighting Explorer.");
}
m_TableTabs = m_CurrentLightingExplorerExtension.GetContentTabs();
m_TabTitles = m_TableTabs != null ? m_TableTabs.Select(item => item.title).ToArray() : null;
}
}
ILightingExplorerExtension GetDefaultLightingExplorerExtension()
{
return s_DefaultLightingExplorerExtension ??= new DefaultLightingExplorerExtension();
}
ILightingExplorerExtension GetLightExplorerExtension(Type currentSRPType)
{
if (currentSRPType == null)
return GetDefaultLightingExplorerExtension();
var extensionType = RenderPipelineEditorUtility.GetDerivedTypesSupportedOnCurrentPipeline<ILightingExplorerExtension>().FirstOrDefault();
if (extensionType == null)
return GetDefaultLightingExplorerExtension();
var extension = (ILightingExplorerExtension) Activator.CreateInstance(extensionType);
return extension;
// no light explorer extension found for current srp, return the default one
}
}
}
| UnityCsReference/Editor/Mono/SceneModeWindows/LightingExplorerWindow.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/SceneModeWindows/LightingExplorerWindow.cs",
"repo_id": "UnityCsReference",
"token_count": 3340
} | 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.AnimatedValues;
using UnityEngine;
namespace UnityEditor
{
static class GridSettings
{
const float k_GridSizeMin = 0f;
const float k_GridSizeMax = 1024f;
const int k_DefaultMultiplier = 0;
public const float defaultGridSize = 1.0f;
static SavedFloat s_GridSizeX = new SavedFloat("GridSizeX", defaultGridSize);
static SavedFloat s_GridSizeY = new SavedFloat("GridSizeY", defaultGridSize);
static SavedFloat s_GridSizeZ = new SavedFloat("GridSizeZ", defaultGridSize);
static SavedInt s_GridMultiplier = new SavedInt("GridMultiplier", k_DefaultMultiplier);
static Vector3 rawSize
{
get { return new Vector3(s_GridSizeX, s_GridSizeY, s_GridSizeZ); }
}
internal static event Action<Vector3> sizeChanged = delegate {};
internal static bool linked => Mathf.Approximately(size.x, size.y) && Mathf.Approximately(size.x, size.z);
public static Vector3 size
{
get { return ApplyMultiplier(rawSize, s_GridMultiplier); }
set
{
if (size == value)
return;
ResetSizeMultiplier();
s_GridSizeX.value = Mathf.Min(k_GridSizeMax, Mathf.Max(k_GridSizeMin, value.x));
s_GridSizeY.value = Mathf.Min(k_GridSizeMax, Mathf.Max(k_GridSizeMin, value.y));
s_GridSizeZ.value = Mathf.Min(k_GridSizeMax, Mathf.Max(k_GridSizeMin, value.z));
sizeChanged(size);
}
}
internal static int sizeMultiplier
{
get { return s_GridMultiplier.value; }
set
{
s_GridMultiplier.value = value;
sizeChanged?.Invoke(size);
}
}
internal static void ResetSizeMultiplier()
{
s_GridMultiplier.value = k_DefaultMultiplier;
}
static Vector3 ApplyMultiplier(Vector3 value, int mul)
{
if (mul > 0)
{
for (int i = 0; i < mul; i++)
value *= 2f;
}
else if (mul < 0)
{
for (int i = 0; i > mul; i--)
value /= 2f;
}
return value;
}
public static void ResetGridSettings()
{
size = new Vector3(defaultGridSize, defaultGridSize, defaultGridSize);
}
}
[System.Serializable]
class SceneViewGrid
{
public const float defaultGridOpacity = .5f;
public const GridRenderAxis defaultRenderAxis = GridRenderAxis.Y;
public const bool defaultShowGrid = true;
internal event Action<bool> gridVisibilityChanged = delegate(bool b) {};
internal event Action<GridRenderAxis> gridRenderAxisChanged = delegate(GridRenderAxis axis) {};
internal enum GridRenderAxis
{
X,
Y,
Z,
All
}
[System.Serializable]
internal class Grid
{
[SerializeField]
AnimBool m_Fade = new AnimBool();
[SerializeField]
Color m_Color;
[SerializeField]
Vector3 m_Pivot;
[SerializeField]
Vector2 m_Size;
internal AnimBool fade
{
get { return m_Fade; }
set { m_Fade = value; }
}
internal Color color
{
get { return m_Color; }
set { m_Color = value; }
}
internal Vector3 pivot
{
get { return m_Pivot; }
set { m_Pivot = value; }
}
internal Vector2 size
{
get { return m_Size; }
set { m_Size = value; }
}
internal DrawGridParameters PrepareGridRender(int gridID, float opacity)
{
DrawGridParameters parameters = default(DrawGridParameters);
parameters.gridID = gridID;
parameters.pivot = pivot;
parameters.color = color;
parameters.color.a = fade.faded * opacity;
parameters.size = size;
return parameters;
}
}
internal static PrefColor kViewGridColor = new PrefColor("Scene/Grid", .5f, .5f, .5f, .4f);
static float k_AngleThresholdForOrthographicGrid = 0.15f;
[SerializeField]
Grid xGrid = new Grid();
[SerializeField]
Grid yGrid = new Grid();
[SerializeField]
Grid zGrid = new Grid();
[SerializeField]
bool m_ShowGrid = defaultShowGrid;
[SerializeField]
GridRenderAxis m_GridAxis = defaultRenderAxis;
[SerializeField]
float m_gridOpacity = defaultGridOpacity;
internal bool showGrid
{
get => m_ShowGrid;
set
{
if (value == m_ShowGrid)
return;
m_ShowGrid = value;
gridVisibilityChanged(m_ShowGrid);
}
}
internal float gridOpacity
{
get => m_gridOpacity;
set => m_gridOpacity = Mathf.Clamp01(value);
}
internal GridRenderAxis gridAxis
{
get => m_GridAxis;
set
{
if (m_GridAxis == value) return;
m_GridAxis = value;
gridRenderAxisChanged(value);
}
}
internal Grid activeGrid
{
get
{
if (gridAxis == GridRenderAxis.X)
return xGrid;
else if (gridAxis == GridRenderAxis.Y)
return yGrid;
else if (gridAxis == GridRenderAxis.Z)
return zGrid;
return yGrid;
}
}
internal void UpdateGridColor()
{
xGrid.color = yGrid.color = zGrid.color = kViewGridColor;
}
internal void OnEnable(SceneView view)
{
UpdateGridColor();
GridSettings.sizeChanged += GridSizeChanged;
// hook up the anims, so repainting can work correctly
xGrid.fade.valueChanged.AddListener(view.Repaint);
yGrid.fade.valueChanged.AddListener(view.Repaint);
zGrid.fade.valueChanged.AddListener(view.Repaint);
}
internal void OnDisable(SceneView view)
{
GridSettings.sizeChanged -= GridSizeChanged;
xGrid.fade.valueChanged.RemoveListener(view.Repaint);
yGrid.fade.valueChanged.RemoveListener(view.Repaint);
zGrid.fade.valueChanged.RemoveListener(view.Repaint);
}
void GridSizeChanged(Vector3 size)
{
SetPivot(GridRenderAxis.X, Snapping.Snap(GetPivot(GridRenderAxis.X), GridSettings.size));
SetPivot(GridRenderAxis.Y, Snapping.Snap(GetPivot(GridRenderAxis.Y), GridSettings.size));
SetPivot(GridRenderAxis.Z, Snapping.Snap(GetPivot(GridRenderAxis.Z), GridSettings.size));
}
internal void SetAllGridsPivot(Vector3 pivot)
{
xGrid.pivot = pivot;
yGrid.pivot = pivot;
zGrid.pivot = pivot;
}
internal void SetPivot(GridRenderAxis axis, Vector3 pivot)
{
if (axis == GridRenderAxis.X)
xGrid.pivot = pivot;
else if (axis == GridRenderAxis.Y)
yGrid.pivot = pivot;
else if (axis == GridRenderAxis.Z)
zGrid.pivot = pivot;
}
internal Vector3 GetPivot(GridRenderAxis axis)
{
if (axis == GridRenderAxis.X)
return xGrid.pivot;
else if (axis == GridRenderAxis.Y)
return yGrid.pivot;
else if (axis == GridRenderAxis.Z)
return zGrid.pivot;
return Vector3.zero;
}
internal void ResetPivot(GridRenderAxis axis)
{
if (axis == GridRenderAxis.X)
xGrid.pivot = Vector3.zero;
else if (axis == GridRenderAxis.Y)
yGrid.pivot = Vector3.zero;
else if (axis == GridRenderAxis.Z)
zGrid.pivot = Vector3.zero;
else if (axis == GridRenderAxis.All)
xGrid.pivot = yGrid.pivot = zGrid.pivot = Vector3.zero;
}
internal void UpdateGridsVisibility(Quaternion rotation, bool orthoMode)
{
bool showX = false, showY = false, showZ = false;
if (showGrid)
{
if (orthoMode)
{
Vector3 fwd = rotation * Vector3.forward;
// Show xy, zy and xz planes only when straight on
if (fwd == Vector3.up || fwd == Vector3.down)
showY = true;
else if (fwd == Vector3.left || fwd == Vector3.right)
showX = true;
else if (fwd == Vector3.forward || fwd == Vector3.back)
showZ = true;
}
// Main path for perspective mode.
// In ortho, fallback on this path if camera is not aligned with X, Y or Z axis.
if (!showX && !showY && !showZ)
{
showX = (gridAxis == GridRenderAxis.X || gridAxis == GridRenderAxis.All);
showY = (gridAxis == GridRenderAxis.Y || gridAxis == GridRenderAxis.All);
showZ = (gridAxis == GridRenderAxis.Z || gridAxis == GridRenderAxis.All);
}
}
xGrid.fade.target = showX;
yGrid.fade.target = showY;
zGrid.fade.target = showZ;
}
internal void SkipFading()
{
xGrid.fade.SkipFading();
yGrid.fade.SkipFading();
zGrid.fade.SkipFading();
}
void ApplySnapConstraintsInPerspectiveMode()
{
switch (gridAxis)
{
case GridRenderAxis.X:
ApplySnapContraintsOnXAxis();
break;
case GridRenderAxis.Y:
ApplySnapContraintsOnYAxis();
break;
case GridRenderAxis.Z:
ApplySnapContraintsOnZAxis();
break;
}
}
void ApplySnapConstraintsInOrthogonalMode()
{
if (xGrid.fade.target)
ApplySnapContraintsOnXAxis();
if (yGrid.fade.target)
ApplySnapContraintsOnYAxis();
if (zGrid.fade.target)
ApplySnapContraintsOnZAxis();
}
void ApplySnapContraintsOnXAxis()
{
Vector3 grid = GridSettings.size;
xGrid.size = new Vector2(grid.y, grid.z);
}
void ApplySnapContraintsOnYAxis()
{
Vector3 grid = GridSettings.size;
yGrid.size = new Vector2(grid.z, grid.x);
}
void ApplySnapContraintsOnZAxis()
{
Vector3 grid = GridSettings.size;
zGrid.size = new Vector2(grid.x, grid.y);
}
internal DrawGridParameters PrepareGridRender(Camera camera, Vector3 pivot, Quaternion rotation,
float size, bool orthoMode)
{
UpdateGridsVisibility(rotation, orthoMode);
if (orthoMode)
{
ApplySnapConstraintsInOrthogonalMode();
return PrepareGridRenderOrthogonalMode(camera, pivot, rotation, size);
}
ApplySnapConstraintsInPerspectiveMode();
return PrepareGridRenderPerspectiveMode(camera, pivot, rotation, size);
}
DrawGridParameters PrepareGridRenderPerspectiveMode(Camera camera, Vector3 pivot, Quaternion rotation,
float size)
{
DrawGridParameters parameters = default(DrawGridParameters);
switch (gridAxis)
{
case GridRenderAxis.X:
parameters = xGrid.PrepareGridRender(0, gridOpacity);
break;
case GridRenderAxis.Y:
parameters = yGrid.PrepareGridRender(1, gridOpacity);
break;
case GridRenderAxis.Z:
parameters = zGrid.PrepareGridRender(2, gridOpacity);
break;
}
return parameters;
}
DrawGridParameters PrepareGridRenderOrthogonalMode(Camera camera, Vector3 pivot, Quaternion rotation,
float size)
{
Vector3 direction = camera.transform.TransformDirection(new Vector3(0, 0, 1));
DrawGridParameters parameters = default(DrawGridParameters);
// Don't show orthographic grid at very shallow angles because it looks bad.
// It's normally already faded out by the managed animated fading values at this angle,
// but if it's orbited rapidly, it can end up at this angle faster than the fading has kicked in.
// For these cases hiding it abruptly looks better.
// The popping isn't noticable because the user is orbiting rapidly to begin with.
if (xGrid.fade.target && Mathf.Abs(direction.x) >= k_AngleThresholdForOrthographicGrid)
parameters = xGrid.PrepareGridRender(0, gridOpacity);
else if (yGrid.fade.target && Mathf.Abs(direction.y) >= k_AngleThresholdForOrthographicGrid)
parameters = yGrid.PrepareGridRender(1, gridOpacity);
else if (zGrid.fade.target && Mathf.Abs(direction.z) >= k_AngleThresholdForOrthographicGrid)
parameters = zGrid.PrepareGridRender(2, gridOpacity);
return parameters;
}
internal void Reset()
{
gridOpacity = defaultGridOpacity;
showGrid = defaultShowGrid;
gridAxis = defaultRenderAxis;
}
}
} // namespace
| UnityCsReference/Editor/Mono/SceneView/SceneViewGrid.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/SceneView/SceneViewGrid.cs",
"repo_id": "UnityCsReference",
"token_count": 7406
} | 344 |
// 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 UnityEditor;
using UnityEditor.Utils;
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Unity.CodeEditor;
namespace UnityEditorInternal
{
public class ScriptEditorUtility
{
// Keep in sync with enum ScriptEditorType in ExternalEditor.h
[Obsolete("This will be removed", false)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public enum ScriptEditor
{
SystemDefault = 0,
MonoDevelop = 1,
VisualStudio = 2,
VisualStudioExpress = 3,
Other = 32
}
public struct Installation
{
public string Name;
public string Path;
}
static readonly List<Func<Installation[]>> k_PathCallbacks = new List<Func<Installation[]>>();
[Obsolete("Use UnityEditor.ScriptEditor.Register()", true)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static void RegisterIde(Func<Installation[]> pathCallBack)
{
k_PathCallbacks.Add(pathCallBack);
}
[Obsolete("This functionality is going to be removed. See IExternalCodeEditor for more information", true)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static ScriptEditor GetScriptEditorFromPath(string path)
{
string lowerCasePath = path.ToLower();
if (lowerCasePath == CodeEditor.SystemDefaultPath)
return ScriptEditor.SystemDefault;
return ScriptEditor.Other;
}
[RequiredByNativeCode]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static string GetExternalScriptEditor()
{
return CodeEditor.CurrentEditorPath;
}
[Obsolete("This method has been moved to CodeEditor.SetExternalScriptEditor", true)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static void SetExternalScriptEditor(string path)
{
CodeEditor.SetExternalScriptEditor(path);
}
[Obsolete("Use UnityEditor.ScriptEditor.GetCurrentEditor()", true)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static ScriptEditor GetScriptEditorFromPreferences()
{
return GetScriptEditorFromPath(CodeEditor.CurrentEditorInstallation);
}
[Obsolete("This method is being internalized, please use UnityEditorInternal.CodeEditorUtility.GetFoundScriptEditorPaths", true)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static Dictionary<string, string> GetFoundScriptEditorPaths(RuntimePlatform platform)
{
return CodeEditor.Editor.GetFoundScriptEditorPaths();
}
private static void AddIfDirectoryExists(string name, string path, Dictionary<string, string> list)
{
if (list.ContainsKey(path))
return;
if (Directory.Exists(path)) list.Add(path, name);
else if (File.Exists(path)) list.Add(path, name);
}
}
}
| UnityCsReference/Editor/Mono/ScriptEditorUtility.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/ScriptEditorUtility.cs",
"repo_id": "UnityCsReference",
"token_count": 1368
} | 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;
namespace UnityEditor.Scripting.Compilers
{
internal class MicrosoftCSharpResponseFileProvider : ResponseFileProvider
{
public override string ResponseFileName { get { return CompilerSpecificResponseFiles.MicrosoftCSharpCompiler; } }
public override string[] ObsoleteResponseFileNames { get { return CompilerSpecificResponseFiles.MicrosoftCSharpCompilerObsolete; } }
}
}
| UnityCsReference/Editor/Mono/Scripting/Compilers/MicrosoftCSharpResponseFileProvider.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Scripting/Compilers/MicrosoftCSharpResponseFileProvider.cs",
"repo_id": "UnityCsReference",
"token_count": 160
} | 346 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using Bee.BeeDriver;
using Bee.BinLog;
using NiceIO;
using ScriptCompilationBuildProgram.Data;
using Unity.Profiling;
using UnityEditor.Build.Player;
using UnityEditor.Compilation;
using UnityEditor.PackageManager;
using UnityEditor.Scripting.Compilers;
using UnityEngine;
using CompilerMessage = UnityEditor.Scripting.Compilers.CompilerMessage;
using CompilerMessageType = UnityEditor.Scripting.Compilers.CompilerMessageType;
namespace UnityEditor.Scripting.ScriptCompilation
{
internal static class BeeScriptCompilation
{
internal static string ExecutableExtension => Application.platform == RuntimePlatform.WindowsEditor ? ".exe" : "";
private static string projectPath = Path.GetDirectoryName(Application.dataPath);
public static ScriptCompilationData ScriptCompilationDataFor(
EditorCompilation editorCompilation,
ScriptAssembly[] assemblies,
bool debug,
string outputDirectory,
BuildTarget buildTarget,
bool buildingForEditor,
bool enableScriptUpdater,
string[] extraScriptingDefines = null)
{
// Need to call AssemblyDataFrom before calling CompilationPipeline.GetScriptAssemblies,
// as that acts on the same ScriptAssemblies, and modifies them with different build settings.
var cachedAssemblies = AssemblyDataFrom(assemblies);
AssemblyData[] codeGenAssemblies;
using (new ProfilerMarker("GetScriptAssembliesForCodeGen").Auto())
{
codeGenAssemblies = buildingForEditor
? null
: AssemblyDataFrom(CodeGenAssemblies(CompilationPipeline.GetScriptAssemblies(editorCompilation, AssembliesType.Editor, extraScriptingDefines)));
}
var movedFromExtractorPath = $"{EditorApplication.applicationContentsPath}/Tools/Compilation/ApiUpdater/ApiUpdater.MovedFromExtractor.dll";
var dotNetSdkRoslynPath = EditorApplication.applicationContentsPath + $"/DotNetSdkRoslyn";
var localization = "en-US";
if (LocalizationDatabase.currentEditorLanguage != SystemLanguage.English && EditorPrefs.GetBool("Editor.kEnableCompilerMessagesLocalization", false))
localization = LocalizationDatabase.GetCulture(LocalizationDatabase.currentEditorLanguage);
var assembliesToScanForTypeDB = new HashSet<string>();
var searchPaths = new HashSet<string>(BuildPlayerDataGenerator.GetStaticSearchPaths(buildTarget));
var options = EditorScriptCompilationOptions.BuildingIncludingTestAssemblies;
if (buildingForEditor)
options |= EditorScriptCompilationOptions.BuildingForEditor;
foreach (var a in editorCompilation.GetAllScriptAssemblies(options, extraScriptingDefines))
{
if (!a.Flags.HasFlag(AssemblyFlags.EditorOnly))
{
var path = a.FullPath.ToNPath();
assembliesToScanForTypeDB.Add(path.ToString());
searchPaths.Add(path.Parent.ToString());
}
}
var precompileAssemblies = editorCompilation.PrecompiledAssemblyProvider.GetPrecompiledAssembliesDictionary(
options,
buildTarget,
extraScriptingDefines);
if (precompileAssemblies != null)
{
foreach (var a in precompileAssemblies)
{
if (!a.Value.Flags.HasFlag(AssemblyFlags.EditorOnly))
{
var path = a.Value.Path.ToNPath();
assembliesToScanForTypeDB.Add(path.ToString());
searchPaths.Add(path.Parent.ToString());
}
}
}
return new ScriptCompilationData()
{
OutputDirectory = outputDirectory,
DotnetRuntimePath = NetCoreProgram.DotNetRuntimePath.ToString(),
DotnetRoslynPath = dotNetSdkRoslynPath,
MovedFromExtractorPath = movedFromExtractorPath,
Assemblies = cachedAssemblies,
CodegenAssemblies = codeGenAssemblies,
Debug = debug,
BuildTarget = buildTarget.ToString(),
Localization = localization,
EnableDiagnostics = editorCompilation.EnableDiagnostics,
BuildPlayerDataOutput = $"Library/BuildPlayerData/{(buildingForEditor ? "Editor" : "Player")}",
ExtractRuntimeInitializeOnLoads = !buildingForEditor,
AssembliesToScanForTypeDB = assembliesToScanForTypeDB.OrderBy(p => p).ToArray(),
SearchPaths = searchPaths.OrderBy(p => p).ToArray(),
EmitInfoForScriptUpdater = enableScriptUpdater
};
}
private static ScriptAssembly[] CodeGenAssemblies(ScriptAssembly[] assemblies) =>
assemblies
.Where(assembly => UnityCodeGenHelpers.IsCodeGen(FileUtil.GetPathWithoutExtension(assembly.Filename)))
.SelectMany(assembly => assembly.AllRecursiveScripAssemblyReferencesIncludingSelf())
.Distinct()
.OrderBy(a => a.Filename)
.ToArray();
private static AssemblyData[] AssemblyDataFrom(ScriptAssembly[] assemblies)
{
Array.Sort(assemblies, (a1, a2) => string.Compare(a1.Filename, a2.Filename, StringComparison.Ordinal));
return assemblies.Select((scriptAssembly, index) =>
{
using (new ProfilerMarker($"AssemblyDataFrom {scriptAssembly.Filename}").Auto())
return AssemblyDataFrom(scriptAssembly, assemblies, index);
}).ToArray();
}
private static AssemblyData AssemblyDataFrom(ScriptAssembly a, ScriptAssembly[] allAssemblies, int index)
{
Array.Sort(a.Files, StringComparer.Ordinal);
var references = a.ScriptAssemblyReferences.Select(r => Array.IndexOf(allAssemblies, r)).ToArray();
Array.Sort(references);
return new AssemblyData
{
Name = new NPath(a.Filename).FileNameWithoutExtension,
SourceFiles = a.Files,
Defines = a.Defines,
PrebuiltReferences = a.References,
References = references,
AllowUnsafeCode = a.CompilerOptions.AllowUnsafeCode,
RuleSet = a.CompilerOptions.RoslynAnalyzerRulesetPath,
LanguageVersion = a.CompilerOptions.LanguageVersion,
Analyzers = a.CompilerOptions.RoslynAnalyzerDllPaths,
AdditionalFiles = a.CompilerOptions.RoslynAdditionalFilePaths,
AnalyzerConfigPath = a.CompilerOptions.AnalyzerConfigPath,
UseDeterministicCompilation = a.CompilerOptions.UseDeterministicCompilation,
SuppressCompilerWarnings = (a.Flags & AssemblyFlags.SuppressCompilerWarnings) != 0,
Asmdef = a.AsmDefPath,
CustomCompilerOptions = a.CompilerOptions.AdditionalCompilerArguments,
BclDirectories = MonoLibraryHelpers.GetSystemReferenceDirectories(a.CompilerOptions.ApiCompatibilityLevel),
DebugIndex = index,
SkipCodeGen = a.SkipCodeGen,
Path = projectPath,
};
}
private static CompilerMessage AsCompilerMessage(BeeDriverResult.Message message)
{
return new CompilerMessage
{
message = message.Text,
type = message.Kind == BeeDriverResult.MessageKind.Error
? CompilerMessageType.Error
: CompilerMessageType.Warning,
};
}
/// <summary>
/// the returned array of compiler messages corresponds to the input array of noderesult. Each node result can result in 0,1 or more compilermessages.
/// We return them as an array of arrays, so on the caller side you're still able to map a compilermessage to the noderesult where it originated from,
/// which we need when invoking per assembly compilation callbacks.
/// </summary>
public static CompilerMessage[][] ParseAllNodeResultsIntoCompilerMessages(BeeDriverResult.Message[] beeDriverMessages, NodeFinishedMessage[] nodeResults, EditorCompilation editorCompilation)
{
// If there's any messages from the bee driver, we add one additional array to the result which contains all of the driver messages converted and augmented like the nodes messages arrays.
bool hasBeeDriverMessages = beeDriverMessages.Length > 0;
var result = new CompilerMessage[nodeResults.Length + (hasBeeDriverMessages ? 1 : 0)][];
int resultIndex = 0;
if (hasBeeDriverMessages)
{
result[resultIndex] = beeDriverMessages.Select(AsCompilerMessage).ToArray();
++resultIndex;
}
for (int i = 0; i != nodeResults.Length; i++)
{
result[resultIndex] = ParseCompilerOutput(nodeResults[i]);
++resultIndex;
}
//To be more kind to performance issues in situations where there are thousands of compiler messages, we're going to assume
//that after the first 10 compiler error messages, we get very little benefit from augmenting the rest with higher quality unity specific messaging.
int totalErrors = 0;
int nextResultToAugment = 0;
while (totalErrors < 10 && nextResultToAugment < result.Length)
{
UnitySpecificCompilerMessages.AugmentMessagesInCompilationErrorsWithUnitySpecificAdvice(result[nextResultToAugment], editorCompilation);
totalErrors += result[nextResultToAugment].Count(m => m.type == CompilerMessageType.Error);
++nextResultToAugment;
}
return result;
}
public static CompilerMessage[] ParseCompilerOutput(NodeFinishedMessage nodeResult)
{
// TODO: future improvement opportunity: write a single parser that can parse warning, errors files from all tools that we use.
if (nodeResult.Node.Annotation.StartsWith("CopyFiles", StringComparison.Ordinal))
{
if (nodeResult.ExitCode == 0)
{
return Array.Empty<CompilerMessage>();
}
return new[]
{
new CompilerMessage
{
file = nodeResult.Node.OutputFile,
message = $"{nodeResult.Node.OutputFile}: {nodeResult.Output}",
type = CompilerMessageType.Error
}
};
}
var parser = nodeResult.Node.Annotation.StartsWith("ILPostProcess", StringComparison.Ordinal)
? (CompilerOutputParserBase) new PostProcessorOutputParser()
: (CompilerOutputParserBase) new MicrosoftCSharpCompilerOutputParser();
return parser
.Parse(
(nodeResult.Output ?? string.Empty).Split(new[] {'\r', '\n'},
StringSplitOptions.RemoveEmptyEntries),
nodeResult.ExitCode != 0).ToArray();
}
}
}
| UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/BeeDriver/BeeScriptCompilation.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/BeeDriver/BeeScriptCompilation.cs",
"repo_id": "UnityCsReference",
"token_count": 5059
} | 347 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute;
using System;
using UnityEditor.Compilation;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using CompilerMessageType = UnityEditor.Scripting.Compilers.CompilerMessageType;
namespace UnityEditor.Scripting.ScriptCompilation
{
static class EditorCompilationInterface
{
static EditorCompilation editorCompilation;
public static EditorCompilation Instance
{
get
{
if (editorCompilation == null)
{
editorCompilation = new EditorCompilation();
}
return editorCompilation;
}
}
static void LogException(Exception exception)
{
bool exceptionProcessed = Instance.CompilationSetupErrorsTracker.ProcessException(exception);
if (exceptionProcessed)
return;
UnityEngine.Debug.LogException(exception);
}
static void EmitExceptionsAsErrors(IEnumerable<Exception> exceptions)
{
if (exceptions == null)
return;
foreach (var exception in exceptions)
LogException(exception);
}
static T EmitExceptionAsError<T>(Func<T> func, T returnValue)
{
try
{
return func();
}
catch (Exception e)
{
LogException(e);
return returnValue;
}
}
static void LogWarning(string warning, string assetPath)
{
var asset = AssetDatabase.LoadAssetAtPath<TextAsset>(assetPath);
Debug.LogWarning(warning, asset);
}
[RequiredByNativeCode]
public static void SetAssetPathsMetaData(AssetPathMetaData[] assetPathMetaDatas)
{
Instance.SetAssetPathsMetaData(assetPathMetaDatas);
}
[RequiredByNativeCode]
public static void SetAdditionalVersionMetaDatas(VersionMetaData[] versionMetaDatas)
{
Instance.SetAdditionalVersionMetaDatas(versionMetaDatas);
}
[RequiredByNativeCode]
public static void SetAllScripts(string[] allScripts)
{
Instance.SetAllScripts(allScripts);
}
[RequiredByNativeCode]
public static bool HaveScriptsForEditorBeenCompiledSinceLastDomainReload()
{
return Instance.HaveScriptsForEditorBeenCompiledSinceLastDomainReload();
}
[RequiredByNativeCode]
public static void RequestScriptCompilation(string reason)
{
Instance.RequestScriptCompilation(reason);
}
[RequiredByNativeCode]
public static void SkipCustomScriptAssemblyGraphValidation(bool skipValidation)
{
Instance.SkipCustomScriptAssemblyGraphValidation(skipValidation);
}
[RequiredByNativeCode]
public static void ClearCustomScriptAssemblies()
{
Instance.ClearCustomScriptAssemblies();
}
[RequiredByNativeCode]
public static void DeleteScriptAssemblies()
{
Instance.DeleteScriptAssemblies();
}
[RequiredByNativeCode]
public static void SetAllUnityAssemblies(PrecompiledAssembly[] unityAssemblies)
{
Instance.SetAllUnityAssemblies(unityAssemblies);
}
// Burst package depends on this method, so we can't remove it.
[RequiredByNativeCode]
public static void SetCompileScriptsOutputDirectory(string directory)
{
Instance.SetCompileScriptsOutputDirectory(directory);
}
[RequiredByNativeCode]
public static string GetCompileScriptsOutputDirectory()
{
return EmitExceptionAsError(() => Instance.GetCompileScriptsOutputDirectory(), string.Empty);
}
[RequiredByNativeCode]
public static void SetAllCustomScriptAssemblyReferenceJsons(string[] allAssemblyReferenceJsons, string[] allAssemblyReferenceJsonContents)
{
EmitExceptionsAsErrors(Instance.SetAllCustomScriptAssemblyReferenceJsonsContents(allAssemblyReferenceJsons, allAssemblyReferenceJsonContents));
}
[RequiredByNativeCode]
public static void SetAllCustomScriptAssemblyJsonContents(string[] allAssemblyJsonPaths, string[] allAssemblyJsonContents, string[] guids)
{
EmitExceptionsAsErrors(Instance.SetAllCustomScriptAssemblyJsonContents(allAssemblyJsonPaths, allAssemblyJsonContents, guids));
}
[RequiredByNativeCode]
public static EditorCompilation.TargetAssemblyInfo[] GetAllCompiledAndResolvedTargetAssemblies(EditorScriptCompilationOptions options, BuildTarget buildTarget)
{
EditorCompilation.CustomScriptAssemblyAndReference[] assembliesWithMissingReference = null;
var result = EmitExceptionAsError(() => Instance.GetAllCompiledAndResolvedTargetAssemblies(options, buildTarget, out assembliesWithMissingReference), new EditorCompilation.TargetAssemblyInfo[0]);
if (assembliesWithMissingReference != null && assembliesWithMissingReference.Length > 0)
{
foreach (var assemblyAndReference in assembliesWithMissingReference)
{
LogWarning(string.Format("The assembly for Assembly Definition File '{0}' will not be loaded. Because the assembly for its reference '{1}'' does not exist on the file system. " +
"This can be caused by the reference assembly not being compiled due to errors or not having any scripts associated with it.",
assemblyAndReference.Assembly.FilePath,
assemblyAndReference.Reference.FilePath),
assemblyAndReference.Assembly.FilePath);
}
}
// Check we do not have any assembly definition references (asmref) without matching assembly definitions (asmdef)
List<CustomScriptAssemblyReference> referencesWithMissingAssemblies;
Instance.GetAssemblyDefinitionReferencesWithMissingAssemblies(out referencesWithMissingAssemblies);
if (referencesWithMissingAssemblies.Count > 0)
{
foreach (var asmref in referencesWithMissingAssemblies)
{
var warning = $"The Assembly Definition Reference file '{asmref.FilePath}' will not be used. ";
if (string.IsNullOrEmpty(asmref.Reference))
warning += "It does not contain a reference to an Assembly Definition File.";
else
warning += $"The reference to the Assembly Definition File with the name '{asmref.Reference}' could not be found.";
LogWarning(warning, asmref.FilePath);
}
}
return result;
}
[RequiredByNativeCode]
public static EditorCompilation.CompileStatus CompileScripts(EditorScriptCompilationOptions definesOptions, BuildTarget platform, int subtarget, string[] extraScriptingDefines = null)
{
return EmitExceptionAsError(() => Instance.CompileScripts(definesOptions, platform, subtarget, extraScriptingDefines),
EditorCompilation.CompileStatus.CompilationFailed);
}
[RequiredByNativeCode]
public static bool DoesProjectFolderHaveAnyScripts()
{
return Instance.DoesProjectFolderHaveAnyScripts();
}
[RequiredByNativeCode]
public static bool IsCompilationPending()
{
return Instance.IsScriptCompilationRequested();
}
[RequiredByNativeCode]
// Unlike IsCompiling, this will only return true if compilation has actually started (and not if compilation
// is requested but has not started yet). We are using this for the BuildPlayer check (to not allow starting
// a player build if script compilation is in progress). We do allow starting a player build if compilation is
// requested (with a warning), as a common flow used in user build scripts is "Change defines -> Build Player".
public static bool IsCompilationInProgress()
{
#pragma warning disable CS0612 // Type or member is obsolete
return Instance.IsCompilationTaskCompiling() || Instance.IsAnyAssemblyBuilderCompiling();
#pragma warning restore CS0612 // Type or member is obsolete
}
[RequiredByNativeCode]
public static bool IsCompiling()
{
return Instance.IsCompiling();
}
[RequiredByNativeCode]
public static EditorCompilation.CompileStatus TickCompilationPipeline(EditorScriptCompilationOptions options, BuildTarget platform, int subtarget, string[] extraScriptingDefines, bool allowBlocking)
{
try
{
return Instance.TickCompilationPipeline(options, platform, subtarget, extraScriptingDefines, allowBlocking);
}
catch (Exception e)
{
LogException(e);
return EditorCompilation.CompileStatus.CompilationFailed;
}
}
[RequiredByNativeCode]
public static EditorCompilation.TargetAssemblyInfo[] GetTargetAssemblyInfos()
{
return Instance.GetTargetAssemblyInfos();
}
[RequiredByNativeCode]
public static EditorCompilation.TargetAssemblyInfo[] GetCompatibleTargetAssemblyInfos(EditorScriptCompilationOptions definesOptions, BuildTarget platform, string[] extraScriptingDefines = null)
{
var scriptAssemblySettings = Instance.CreateScriptAssemblySettings(platform, EditorUserBuildSettings.GetActiveSubtargetFor(platform), definesOptions, extraScriptingDefines);
return Instance.GetTargetAssemblyInfos(scriptAssemblySettings);
}
[RequiredByNativeCode]
public static EditorCompilation.TargetAssemblyInfo GetTargetAssembly(string scriptPath)
{
return Instance.GetTargetAssembly(scriptPath);
}
public static EditorScriptCompilationOptions GetAdditionalEditorScriptCompilationOptions(
AssembliesType assembliesType)
{
var options = GetAdditionalEditorScriptCompilationOptions();
if (EditorUserBuildSettings.development && (assembliesType == AssembliesType.Player || assembliesType == AssembliesType.PlayerWithoutTestAssemblies))
options |= EditorScriptCompilationOptions.BuildingDevelopmentBuild;
switch (assembliesType)
{
case AssembliesType.Editor:
options |= EditorScriptCompilationOptions.BuildingIncludingTestAssemblies;
options |= EditorScriptCompilationOptions.BuildingForEditor;
break;
case AssembliesType.Player:
options |= EditorScriptCompilationOptions.BuildingIncludingTestAssemblies;
options &= ~EditorScriptCompilationOptions.BuildingForEditor;
break;
case AssembliesType.PlayerWithoutTestAssemblies:
options &= ~EditorScriptCompilationOptions.BuildingIncludingTestAssemblies;
options &= ~EditorScriptCompilationOptions.BuildingForEditor;
break;
default:
throw new ArgumentOutOfRangeException(nameof(assembliesType));
}
return options;
}
public static EditorScriptCompilationOptions GetAdditionalEditorScriptCompilationOptions()
{
var options = EditorScriptCompilationOptions.BuildingEmpty;
if (PlayerSettings.allowUnsafeCode)
options |= EditorScriptCompilationOptions.BuildingPredefinedAssembliesAllowUnsafeCode;
if (PlayerSettings.UseDeterministicCompilation)
options |= EditorScriptCompilationOptions.BuildingUseDeterministicCompilation;
return options;
}
}
}
| UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/EditorCompilationInterface.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/EditorCompilationInterface.cs",
"repo_id": "UnityCsReference",
"token_count": 4978
} | 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 UnityEngine.Bindings;
namespace UnityEditor.Scripting.ScriptCompilation
{
internal interface ISafeModeInfo
{
string[] GetWhiteListAssemblyNames();
}
[NativeHeader("Editor/Src/ScriptCompilation/ScriptCompilationPipeline.h")]
internal class SafeModeInfo : ISafeModeInfo
{
public string[] GetWhiteListAssemblyNames()
{
return GetWhiteListAssemblyNamesInternal();
}
[FreeFunction("GetSafeModeWhiteListTargetAssemblies")]
public static extern string[] GetWhiteListAssemblyNamesInternal();
}
}
| UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/SafeMode.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/SafeMode.cs",
"repo_id": "UnityCsReference",
"token_count": 260
} | 349 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
namespace UnityEditor.SearchService
{
delegate void AdvancedObjectSelectorHandler(AdvancedObjectSelectorEventType eventType, in AdvancedObjectSelectorParameters parameters);
delegate bool AdvancedObjectSelectorValidatorHandler(ObjectSelectorSearchContext context);
interface IAdvancedObjectSelectorAttribute
{
internal string id { get; }
}
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public class AdvancedObjectSelectorAttribute : Attribute, IAdvancedObjectSelectorAttribute
{
internal string id { get; }
internal string displayName { get; }
internal int defaultPriority { get; set; }
internal bool defaultActive { get; set; }
string IAdvancedObjectSelectorAttribute.id => id;
public AdvancedObjectSelectorAttribute(string id, string displayName, int defaultPriority, bool defaultActive = true)
{
this.id = id;
this.displayName = displayName;
this.defaultPriority = defaultPriority;
this.defaultActive = defaultActive;
}
public AdvancedObjectSelectorAttribute(string id, int defaultPriority, bool defaultActive = true)
: this(id, null, defaultPriority, defaultActive)
{ }
}
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public class AdvancedObjectSelectorValidatorAttribute : Attribute, IAdvancedObjectSelectorAttribute
{
internal string id { get; }
string IAdvancedObjectSelectorAttribute.id => id;
public AdvancedObjectSelectorValidatorAttribute(string id)
{
this.id = id;
}
}
public readonly struct AdvancedObjectSelectorParameters
{
public ObjectSelectorSearchContext context { get; }
public Action<UnityEngine.Object, bool> selectorClosedHandler { get; }
public Action<UnityEngine.Object> trackingHandler { get; }
public string searchFilter { get; }
internal AdvancedObjectSelectorParameters(ObjectSelectorSearchContext context, Action<UnityEngine.Object, bool> selectorClosedHandler, Action<UnityEngine.Object> trackingHandler, string searchFilter)
{
this.context = context;
this.selectorClosedHandler = selectorClosedHandler;
this.trackingHandler = trackingHandler;
this.searchFilter = searchFilter;
}
internal AdvancedObjectSelectorParameters(ObjectSelectorSearchContext context)
: this(context, null, null, string.Empty)
{ }
internal AdvancedObjectSelectorParameters(ObjectSelectorSearchContext context, Action<UnityEngine.Object, bool> selectorClosedHandler, Action<UnityEngine.Object> trackingHandler)
: this(context, selectorClosedHandler, trackingHandler, string.Empty)
{ }
internal AdvancedObjectSelectorParameters(ObjectSelectorSearchContext context, string searchFilter)
: this(context, null, null, searchFilter)
{ }
internal AdvancedObjectSelectorParameters(ISearchContext context)
: this((ObjectSelectorSearchContext)context, null, null, string.Empty)
{ }
internal AdvancedObjectSelectorParameters(ISearchContext context, Action<UnityEngine.Object, bool> selectorClosedHandler, Action<UnityEngine.Object> trackingHandler)
: this((ObjectSelectorSearchContext)context, selectorClosedHandler, trackingHandler, string.Empty)
{ }
internal AdvancedObjectSelectorParameters(ISearchContext context, string searchFilter)
: this((ObjectSelectorSearchContext)context, null, null, searchFilter)
{ }
}
public enum AdvancedObjectSelectorEventType
{
BeginSession,
EndSession,
OpenAndSearch,
SetSearchFilter
}
}
| UnityCsReference/Editor/Mono/Search/AdvancedObjectSelectorAttribute.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Search/AdvancedObjectSelectorAttribute.cs",
"repo_id": "UnityCsReference",
"token_count": 1367
} | 350 |
// 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;
using System;
using Object = UnityEngine.Object;
namespace UnityEditor
{
[NativeHeader("Editor/Src/Utility/SerializedProperty.h")]
[NativeHeader("Editor/Src/Utility/SerializedObject.bindings.h")]
[NativeHeader("Editor/Src/Utility/SerializedObjectCache.h")]
// SerializedObject and [[SerializedProperty]] are classes for editing properties on objects in a completely generic way that automatically handles undo and styling UI for prefabs.
public class SerializedObject : IDisposable
{
#pragma warning disable 414
internal IntPtr m_NativeObjectPtr;
// Create SerializedObject for inspected object.
public SerializedObject(Object obj)
{
m_NativeObjectPtr = InternalCreate(new Object[] {obj}, null);
}
public SerializedObject(Object obj, Object context)
{
m_NativeObjectPtr = InternalCreate(new Object[] {obj}, context);
}
// Create SerializedObject for inspected object.
public SerializedObject(Object[] objs)
{
m_NativeObjectPtr = InternalCreate(objs, null);
}
public SerializedObject(Object[] objs, Object context)
{
m_NativeObjectPtr = InternalCreate(objs, context);
}
internal SerializedObject(IntPtr nativeObjectPtr)
{
m_NativeObjectPtr = nativeObjectPtr;
}
~SerializedObject() { Dispose(); }
[ThreadAndSerializationSafe()]
public void Dispose()
{
if (m_NativeObjectPtr != IntPtr.Zero)
{
Internal_Destroy(m_NativeObjectPtr);
m_NativeObjectPtr = IntPtr.Zero;
}
}
[FreeFunction("SerializedObjectBindings::Internal_Destroy", IsThreadSafe = true)]
private static extern void Internal_Destroy(IntPtr ptr);
// Get the first serialized property.
public SerializedProperty GetIterator()
{
SerializedProperty i = GetIterator_Internal();
// This is so the garbage collector won't clean up SerializedObject behind the scenes,
// when we are still iterating properties
i.m_SerializedObject = this;
return i;
}
// Find serialized property by name.
public SerializedProperty FindProperty(string propertyPath)
{
SerializedProperty i = GetIterator_Internal();
// This is so the garbage collector won't clean up SerializedObject behind the scenes,
// when we are still iterating properties
i.m_SerializedObject = this;
if (i.FindPropertyInternal(propertyPath))
return i;
else
return null;
}
/// <summary>
/// Given a path of the form "managedReferences[refid].field" this finds the first field
/// that references that reference id and returns a serialized property based on that path.
/// For example if an object "Foo" with id 1 is referenced by multiple fields "a", "b" and
/// "c.nested" on a MonoBehaviour (declared in that order), then calling this method with
/// "managedReferences[1].x" would return the SerializedProperty with property path "a.x".
/// </summary>
internal SerializedProperty FindFirstPropertyFromManagedReferencePath(string propertyPath)
{
SerializedProperty i = GetIterator_Internal();
// This is so the garbage collector won't clean up SerializedObject behind the scenes,
// when we are still iterating properties
i.m_SerializedObject = this;
if (i.FindFirstPropertyFromManagedReferencePathInternal(propertyPath))
return i;
else
return null;
}
extern public bool ApplyModifiedProperties();
// Update /hasMultipleDifferentValues/ cache on the next /Update()/ call.
extern public void SetIsDifferentCacheDirty();
[FreeFunction(Name = "SerializedObjectBindings::GetIteratorInternal", HasExplicitThis = true)]
extern private SerializedProperty GetIterator_Internal();
// Update serialized object's representation.
extern public void Update();
// Update serialized object's representation, only if the object has been modified since the last call to Update or if it is a script.
[Obsolete("UpdateIfDirtyOrScript has been deprecated. Use UpdateIfRequiredOrScript instead.", false)]
[NativeName("UpdateIfRequiredOrScript")]
extern public void UpdateIfDirtyOrScript();
// Update serialized object's representation, only if the object has been modified since the last call to Update or if it is a script.
extern public bool UpdateIfRequiredOrScript();
// Updates this serialized object's isExpanded value to the global inspector's expanded state for this object
extern internal void UpdateExpandedState();
[NativeMethod(Name = "SerializedObjectBindings::InternalCreate", IsFreeFunction = true, ThrowsException = true)]
extern static IntPtr InternalCreate(Object[] monoObjs, Object context);
internal PropertyModification ExtractPropertyModification(string propertyPath)
{
return InternalExtractPropertyModification(propertyPath) as PropertyModification;
}
[FreeFunction("SerializedObjectBindings::ExtractPropertyModification", HasExplicitThis = true)]
extern private object InternalExtractPropertyModification(string propertyPath);
// The inspected object (RO).
public extern Object targetObject { get; }
// The inspected objects (RO).
public extern Object[] targetObjects { get; }
// The inspected objects (RO).
internal extern int targetObjectsCount { get; }
// The context object (used to resolve scene references via ExposedReference<>)
[NativeProperty("ContextObject")]
public extern Object context { get; }
internal void Cache(int instanceID)
{
CacheInternal(instanceID);
m_NativeObjectPtr = IntPtr.Zero;
}
[FreeFunction("SerializedObjectCache::SaveToCache", HasExplicitThis = true)]
private extern void CacheInternal(int instanceID);
[FreeFunction("SerializedObjectCache::LoadFromCache")]
internal extern static SerializedObject LoadFromCache(int instanceID);
public extern bool ApplyModifiedPropertiesWithoutUndo();
// Enable/Disable live property feature globally.
internal extern static void EnableLivePropertyFeatureGlobally(bool value);
// Get live property global state.
internal extern static bool GetLivePropertyFeatureGlobalState();
// Copies a value from a SerializedProperty to the same serialized property on this serialized object.
public void CopyFromSerializedProperty(SerializedProperty prop)
{
if (prop == null)
throw new ArgumentNullException("prop");
prop.Verify(SerializedProperty.VerifyFlags.IteratorNotAtEnd);
CopyFromSerializedPropertyInternal(prop);
}
[FreeFunction("SerializedObjectBindings::CopyFromSerializedPropertyInternal", HasExplicitThis = true)]
private extern void CopyFromSerializedPropertyInternal(SerializedProperty prop);
// Copies a value from a SerializedProperty to the same serialized property on this serialized object.
public bool CopyFromSerializedPropertyIfDifferent(SerializedProperty prop)
{
if (prop == null)
throw new ArgumentNullException("prop");
prop.Verify(SerializedProperty.VerifyFlags.IteratorNotAtEnd);
return CopyFromSerializedPropertyIfDifferentInternal(prop);
}
[FreeFunction("SerializedObjectBindings::CopyFromSerializedPropertyIfDifferentInternal", HasExplicitThis = true)]
private extern bool CopyFromSerializedPropertyIfDifferentInternal(SerializedProperty prop);
public extern bool hasModifiedProperties
{
[NativeMethod("HasModifiedProperties")]
get;
}
internal extern InspectorMode inspectorMode
{
get;
set;
}
internal extern DataMode inspectorDataMode
{
get;
set;
}
// Does the serialized object represents multiple objects due to multi-object editing? (RO)
public extern bool isEditingMultipleObjects
{
[NativeMethod("IsEditingMultipleObjects")]
get;
}
public extern int maxArraySizeForMultiEditing
{
get;
set;
}
internal extern bool IsValid();
internal bool isValid => m_NativeObjectPtr != IntPtr.Zero && IsValid();
internal extern uint objectVersion
{
[NativeMethod("GetObjectVersion")]
get;
}
public extern bool forceChildVisibility
{
[NativeMethod("GetForceChildVisibiltyFlag")]
get;
[NativeMethod("SetForceChildVisibiltyFlag")]
set;
}
[NativeMethod("HasAnyInstantiatedPrefabsWithValidAsset")]
internal extern bool HasAnyInstantiatedPrefabsWithValidAsset();
internal static bool VersionEquals(SerializedObject x, SerializedObject y)
{
if (x == null || y == null || x.m_NativeObjectPtr == IntPtr.Zero || y.m_NativeObjectPtr == IntPtr.Zero
|| !x.isValid || !y.isValid) return false;
return VersionEqualsInternal(x, y);
}
[FreeFunction("SerializedObjectBindings::VersionEqualsInternal")]
extern static bool VersionEqualsInternal(SerializedObject x, SerializedObject y);
internal static class BindingsMarshaller
{
public static IntPtr ConvertToNative(SerializedObject obj) => obj.m_NativeObjectPtr;
public static SerializedObject ConvertToManaged(IntPtr ptr) => new SerializedObject(ptr);
}
}
}
| UnityCsReference/Editor/Mono/SerializedObject.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/SerializedObject.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 3909
} | 351 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
namespace UnityEditor
{
[CustomEditor(typeof(RenderSettings))]
internal class OtherRenderingEditor : Editor
{
internal static class Styles
{
public static readonly GUIContent HaloStrength = EditorGUIUtility.TrTextContent("Halo Strength", "Controls the visibility of the halo effect around lights in the Scene.");
public static readonly GUIContent HaloTexture = EditorGUIUtility.TrTextContent("Halo Texture", "Specifies the Texture used when drawing the halo effect around lights in the Scene");
public static readonly GUIContent FlareStrength = EditorGUIUtility.TrTextContent("Flare Strength", "Controls the visibility of lens flares from lights in the Scene.");
public static readonly GUIContent FlareFadeSpeed = EditorGUIUtility.TrTextContent("Flare Fade Speed", "Controls the time over which lens flares fade from view after initially appearing.");
public static readonly GUIContent SpotCookie = EditorGUIUtility.TrTextContent("Spot Cookie", "Specifies the Texture mask used to cast shadows, create silhouettes, or patterned illumination when using spot lights.");
}
protected SerializedProperty m_HaloStrength;
protected SerializedProperty m_FlareStrength;
protected SerializedProperty m_FlareFadeSpeed;
protected SerializedProperty m_HaloTexture;
protected SerializedProperty m_SpotCookie;
protected SerializedObject m_RenderSettings;
SerializedObject renderSettings
{
get
{
// if we set a new scene as the active scene, we need to make sure to respond to those changes
if (m_RenderSettings == null || m_RenderSettings.targetObject != RenderSettings.GetRenderSettings())
{
m_RenderSettings = new SerializedObject(RenderSettings.GetRenderSettings());
m_HaloStrength = m_RenderSettings.FindProperty("m_HaloStrength");
m_FlareStrength = m_RenderSettings.FindProperty("m_FlareStrength");
m_FlareFadeSpeed = m_RenderSettings.FindProperty("m_FlareFadeSpeed");
m_HaloTexture = m_RenderSettings.FindProperty("m_HaloTexture");
m_SpotCookie = m_RenderSettings.FindProperty("m_SpotCookie");
}
return m_RenderSettings;
}
}
public virtual void OnDisable() {}
public override void OnInspectorGUI()
{
renderSettings.Update();
EditorGUILayout.PropertyField(m_HaloTexture, Styles.HaloTexture);
EditorGUILayout.Slider(m_HaloStrength, 0.0f, 1.0f, Styles.HaloStrength);
EditorGUILayout.PropertyField(m_FlareFadeSpeed, Styles.FlareFadeSpeed);
EditorGUILayout.Slider(m_FlareStrength, 0.0f, 1.0f, Styles.FlareStrength);
EditorGUILayout.PropertyField(m_SpotCookie, Styles.SpotCookie);
renderSettings.ApplyModifiedProperties();
}
}
}
| UnityCsReference/Editor/Mono/SettingsWindow/OtherRenderingEditor.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/SettingsWindow/OtherRenderingEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 1230
} | 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 UnityEngine;
using UnityEngine.Bindings;
using UnityEngine.Scripting;
using UnityEditor;
using System.Runtime.InteropServices;
namespace UnityEditor.Animations
{
[NativeHeader("Editor/Src/Animation/StateMachineBehaviourContext.h")]
[System.Serializable]
[StructLayout(LayoutKind.Sequential)]
[NativeAsStruct]
public partial class StateMachineBehaviourContext
{
[NativeName("m_AnimatorController")]
public AnimatorController animatorController;
[NativeName("m_AnimatorObject")]
public UnityEngine.Object animatorObject;
[NativeName("m_LayerIndex")]
public int layerIndex;
}
}
| UnityCsReference/Editor/Mono/StateMachineBehaviourContext.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/StateMachineBehaviourContext.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 324
} | 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;
using System.ComponentModel;
namespace UnityEditor.EditorTools
{
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("EditorTools has been deprecated. Use ToolManager instead (UnityUpgradable) -> ToolManager")]
public static class EditorTools
{
public static Type activeToolType => ToolManager.activeToolType;
public static event Action activeToolChanging;
public static event Action activeToolChanged;
internal static void ActiveToolWillChange()
{
if (activeToolChanging != null)
activeToolChanging();
}
internal static void ActiveToolDidChange()
{
if (activeToolChanged != null)
activeToolChanged();
}
public static void SetActiveTool<T>() where T : EditorTool
{
SetActiveTool(typeof(T));
}
public static void SetActiveTool(Type type)
{
ToolManager.SetActiveTool(type);
}
public static void SetActiveTool(EditorTool tool)
{
ToolManager.SetActiveTool(tool);
}
public static void RestorePreviousTool()
{
ToolManager.RestorePreviousTool();
}
public static void RestorePreviousPersistentTool()
{
ToolManager.RestorePreviousTool();
}
public static bool IsActiveTool(EditorTool tool)
{
return ToolManager.IsActiveTool(tool);
}
}
}
| UnityCsReference/Editor/Mono/Tools/EditorTools.deprecated.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Tools/EditorTools.deprecated.cs",
"repo_id": "UnityCsReference",
"token_count": 681
} | 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 UnityEditor;
using UnityEngine.Bindings;
using UnityEngine.Scripting;
namespace UnityEditor
{
[NativeHeader("Editor/Mono/TypeSystem/UnityType.bindings.h")]
internal partial class UnityType
{
#pragma warning disable 649
[UsedByNativeCode]
private struct UnityTypeTransport
{
public uint runtimeTypeIndex;
public uint descendantCount;
public uint baseClassIndex;
public string className;
public string classNamespace;
public string module;
public int persistentTypeID;
public uint flags;
}
private static extern UnityTypeTransport[] Internal_GetAllTypes();
}
}
| UnityCsReference/Editor/Mono/TypeSystem/UnityType.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/TypeSystem/UnityType.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 347
} | 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.Linq;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.UIElements
{
/// <summary>
/// An interface for toolbar items that display drop-down menus.
/// </summary>
public interface IToolbarMenuElement
{
/// <summary>
/// The drop-down menu for the element.
/// </summary>
DropdownMenu menu { get; }
}
/// <summary>
/// An extension class that handles menu management for elements that are implemented with the IToolbarMenuElement interface, but are identical to DropdownMenu.
/// </summary>
public static class ToolbarMenuElementExtensions
{
/// <summary>
/// Display the menu for the element.
/// </summary>
/// <param name="tbe">The element that is part of the menu to be displayed.</param>
public static void ShowMenu(this IToolbarMenuElement tbe)
{
if (tbe == null || !tbe.menu.MenuItems().Any())
return;
var ve = tbe as VisualElement;
if (ve == null)
return;
var worldBound = ve.worldBound;
if (worldBound.x <= 0f)
{
// If the toolbar menu element is going over its allowed left edge, the menu won't be drawn.
// (IMGUI seems to to the same as toolbar menus appear less attached to the left edge when the
// windows are stuck to the left side of the screen as well as our menus)
worldBound.x = 1f;
}
tbe.menu.DoDisplayEditorMenu(worldBound);
}
}
}
| UnityCsReference/Editor/Mono/UIElements/Controls/Toolbar/IToolbarMenuElement.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/UIElements/Controls/Toolbar/IToolbarMenuElement.cs",
"repo_id": "UnityCsReference",
"token_count": 706
} | 356 |
// 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
{
[LibraryFolderPath("UIElements/EditorWindows")]
internal class EditorWindowViewData : ScriptableSingletonDictionary<
EditorWindowViewData,
UnityEditor.UIElements.SerializableJsonDictionary>
{
public static UnityEditor.UIElements.SerializableJsonDictionary GetEditorData(EditorWindow window)
{
string editorPrefFileName = window.GetType().ToString();
return instance[editorPrefFileName];
}
}
}
| UnityCsReference/Editor/Mono/UIElements/EditorWindowPersistentViewData.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/UIElements/EditorWindowPersistentViewData.cs",
"repo_id": "UnityCsReference",
"token_count": 233
} | 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.IO;
using UnityEngine.Bindings;
using Object = UnityEngine.Object;
namespace UnityEditor.UIElements.StyleSheets
{
enum URIValidationResult
{
OK,
InvalidURILocation,
InvalidURIScheme,
InvalidURIProjectAssetPath
}
[VisibleToOtherModules("UnityEditor.UIBuilderModule")]
static class URIHelpers
{
private const string k_ProjectScheme = "project";
private const string k_ProjectSchemeEmptyHint = k_ProjectScheme + "://?";
private const string k_AssetDatabaseHost = "database";
static readonly Uri s_ProjectRootUri = new UriBuilder(k_ProjectScheme, "").Uri;
static readonly Uri s_ThemeUri = new UriBuilder(ThemeRegistry.kThemeScheme, "").Uri;
private const string k_AttrFileId = nameof(RawPPtrReference.fileID);
private const string k_AttrGuid = nameof(RawPPtrReference.guid);
private const string k_AttrType = nameof(RawPPtrReference.type);
private const string k_ContainerRefName = nameof(RawPPtrContainer.o);
public static string MakeAssetUri(Object asset)
{
return MakeAssetUri(asset, false);
}
public static string MakeAssetUri(Object asset, bool compact)
{
if (!asset)
return null;
// TODO: refactor to avoid the unnecessary JSON serialization
var container = s_PPtrContainer;
container.o = asset;
var jsonContainer = EditorJsonUtility.ToJson(container);
var rawContainer = s_RawPPtrContainer;
EditorJsonUtility.FromJsonOverwrite(jsonContainer, rawContainer);
var path = AssetDatabase.GetAssetPath(asset);
var fileID = rawContainer.o.fileID;
var guid = rawContainer.o.guid;
var type = rawContainer.o.type;
var query = $"{k_AttrFileId}={fileID}&{k_AttrGuid}={guid}&{k_AttrType}={type}";
if (compact)
{
return $"?{query}";
}
var fragment = asset.name;
// note: UriBuilder makes assumptions based on the input scheme
// using a custom scheme with an empty host produces unexpected results
var u = new UriBuilder(k_ProjectScheme, k_AssetDatabaseHost, -1, path);
u.Query = query;
u.Fragment = fragment;
return u.ToString();
}
public static string EncodeUri(string uri)
{
uri = uri.Replace("&", "&"); // Has to be done first!
uri = uri.Replace("\"", """);
uri = uri.Replace("\'", "'");
uri = uri.Replace("<", "<");
uri = uri.Replace(">", ">");
uri = uri.Replace("\n", " ");
uri = uri.Replace("\r", "");
uri = uri.Replace("\t", "	");
return uri;
}
public struct URIValidationResponse
{
public URIValidationResult result;
public string errorToken;
public string warningMessage;
public string resolvedProjectRelativePath;
public string resolvedSubAssetPath;
public Object resolvedQueryAsset;
public bool hasWarningMessage => !string.IsNullOrEmpty(warningMessage);
public bool isLibraryAsset =>
resolvedProjectRelativePath?.StartsWith("Library/", StringComparison.Ordinal) ?? false;
}
public static URIValidationResult ValidAssetURL(string assetPath, string path, out string errorToken, out string resolvedProjectRelativePath)
{
var response = ValidateAssetURL(assetPath, path);
errorToken = response.errorToken;
resolvedProjectRelativePath = response.resolvedProjectRelativePath;
return response.result;
}
public static URIValidationResult ValidAssetURL(string assetPath, string path, out string errorToken,
out string resolvedProjectRelativePath, out string resolvedSubAssetPath)
{
var response = ValidateAssetURL(assetPath, path);
errorToken = response.errorToken;
resolvedProjectRelativePath = response.resolvedProjectRelativePath;
resolvedSubAssetPath = response.resolvedSubAssetPath;
return response.result;
}
public static URIValidationResponse ValidateAssetURL(string assetPath, string path)
{
var response = new URIValidationResponse();
if (string.IsNullOrEmpty(path))
{
response.errorToken = "''";
response.result = URIValidationResult.InvalidURILocation;
return response;
}
// UriBuilder isn't able to process '#' fragments with our URL scheme,
// so we process them manually here instead.
var originalPath = path;
response.resolvedSubAssetPath = ExtractUrlFragment(ref path);
Uri absoluteUri = null;
bool isUnityThemePath = path.StartsWith($"{ThemeRegistry.kThemeScheme}://");
// Always treat URIs starting with "/" as implicit project schemes
if (path.StartsWith("/"))
{
var builder = new UriBuilder(s_ProjectRootUri.Scheme, "", 0, path);
absoluteUri = builder.Uri;
}
else if (isUnityThemePath)
{
var themeName = path.Substring($"{s_ThemeUri.Scheme}://".Length);
var builder = new UriBuilder(s_ThemeUri.Scheme, "", -1, themeName);
absoluteUri = builder.Uri;
}
else if (Uri.TryCreate(path, UriKind.Absolute, out absoluteUri) == false)
{
// Resolve a relative URI compared to current file
Uri assetPathUri = new Uri(s_ProjectRootUri, assetPath);
if (Uri.TryCreate(assetPathUri, path, out absoluteUri) == false)
{
response.errorToken = assetPath;
response.result = URIValidationResult.InvalidURILocation;
return response;
}
}
else if (absoluteUri.Scheme != s_ProjectRootUri.Scheme)
{
response.errorToken = absoluteUri.Scheme;
response.result = URIValidationResult.InvalidURIScheme;
return response;
}
string projectRelativePath = Uri.UnescapeDataString(absoluteUri.AbsolutePath);
// Remove any leading "/" as this now used as a path relative to the current directory
if (projectRelativePath.StartsWith("/"))
{
projectRelativePath = projectRelativePath.Substring(1);
}
if (isUnityThemePath)
{
if (string.IsNullOrEmpty(path))
{
response.errorToken = string.Empty;
response.result = URIValidationResult.InvalidURIProjectAssetPath;
return response;
}
response.resolvedProjectRelativePath = path;
}
else
{
response.resolvedProjectRelativePath = projectRelativePath;
// support for: project://asset.type/Assets/Path/To/File.ext?fileID=FILEID&guid=GUID&type=TYPE#subAssetName
// the idea here is to keep UXML/USS human-readable, but also support location-independent asset references
var query = ExtractUriQueryParameters(absoluteUri);
// note: we could relax this and support queries with only a guid parameter, resolving the main asset
if (query.hasAllReferenceParams)
{
// TODO: refactor to avoid the unnecessary JSON serialization
var json = $"{{\"{k_ContainerRefName}\":{{\"{k_AttrFileId}\": {query.fileId}, \"{k_AttrGuid}\":\"{query.guid}\", \"{k_AttrType}\": {query.type}}}}}";
var container = s_PPtrContainer;
EditorJsonUtility.FromJsonOverwrite(json, container);
var resolvedAssetReference = container.o;
response.resolvedQueryAsset = resolvedAssetReference;
// empty paths are resolved to the input assetPath, which is not an issue here
// since the GUID parameter takes precedence
// this case happens with compact asset URIs, and we don't want to warn users
var hasEmptyPathHint = originalPath.StartsWith("?", StringComparison.Ordinal) ||
originalPath.StartsWith(k_ProjectSchemeEmptyHint, StringComparison.Ordinal);
if (!resolvedAssetReference)
{
// could not resolve asset reference from query
var pathFromGuid = AssetDatabase.GUIDToAssetPath(query.guid);
if (!string.IsNullOrEmpty(pathFromGuid))
{
// but that's just because the ADB can't return the asset at the moment
// e.g. during GatherDependenciesFromSourceFile
if (pathFromGuid != response.resolvedProjectRelativePath)
{
if (!hasEmptyPathHint)
{
response.warningMessage = string.Format(
L10n.Tr(
"Asset reference to GUID '{0}' resolved to '{2}', but URL path hints at '{1}'. Update the URL '{3}' to remove this warning."),
query.guid, response.resolvedProjectRelativePath, pathFromGuid, originalPath);
}
response.resolvedProjectRelativePath = pathFromGuid;
}
}
else if (AssetExistsAtPath(response.resolvedProjectRelativePath))
{
// but the path points to a valid asset, so let's use that
response.warningMessage = string.Format(
L10n.Tr(
"Could not resolve asset with GUID '{0}' and file ID '{1}' from URL '{2}'. Using asset path '{3}' instead. Update the URL to remove this warning."),
query.guid, query.fileId, path, response.resolvedProjectRelativePath);
}
else
{
response.warningMessage = string.Format(L10n.Tr("Invalid asset path hint \"{0}\" for referenced asset GUID \"{1}\""),
response.resolvedProjectRelativePath, query.guid);
response.errorToken = originalPath;
response.result = URIValidationResult.InvalidURIProjectAssetPath;
return response;
}
}
else
{
// the GUID-based asset reference takes precedence over paths and names
// warn users about any inconsistencies
var realAssetPath = AssetDatabase.GetAssetPath(resolvedAssetReference);
if (!hasEmptyPathHint &&
!string.IsNullOrEmpty(response.resolvedProjectRelativePath) &&
realAssetPath != response.resolvedProjectRelativePath)
{
// URL path differs from real path (from GUID)
if (AssetExistsAtPath(response.resolvedProjectRelativePath))
{
// URL path points to some other asset -> warn the user
response.warningMessage = string.Format(
L10n.Tr(
"Ambiguous asset reference detected. Asset reference to GUID '{0}' resolved to '{2}', but URL path hints at '{1}', which is also valid asset path. Update the URL '{3}' to remove this warning."),
query.guid, response.resolvedProjectRelativePath, realAssetPath, originalPath);
}
else
{
// URL path points to nothing -> warn the user
response.warningMessage = string.Format(
L10n.Tr(
"Asset reference to GUID '{0}' was moved from '{1}' to '{2}'. Update the URL '{3}' to remove this warning."),
query.guid, response.resolvedProjectRelativePath, realAssetPath, originalPath);
}
}
response.resolvedProjectRelativePath = realAssetPath;
var realAssetName = resolvedAssetReference.name;
if (!string.IsNullOrEmpty(response.resolvedSubAssetPath) &&
realAssetName != response.resolvedSubAssetPath)
{
response.warningMessage = string.Format(
L10n.Tr(
"Asset reference to GUID '{0}' and file ID '{1}' was renamed from '{2}' to '{3}'. Update the URL '{4}' to remove this warning."),
query.guid, query.fileId, response.resolvedSubAssetPath, realAssetName, originalPath);
}
response.resolvedSubAssetPath = realAssetName;
}
}
else
{
if (!AssetExistsAtPath(response.resolvedProjectRelativePath))
{
response.errorToken = string.IsNullOrEmpty(response.resolvedProjectRelativePath) ?
originalPath : response.resolvedProjectRelativePath;
response.result = URIValidationResult.InvalidURIProjectAssetPath;
return response;
}
}
}
response.result = URIValidationResult.OK;
return response;
}
private static bool AssetExistsAtPath(string path)
{
var guidFromPath = AssetDatabase.GUIDFromAssetPath(path);
// also testing for file existence to cover scenarios where the ADB did not import the asset yet
return !guidFromPath.Empty() || File.Exists(path);
}
// the following types exist only to (de)serialize UnityEngine.Object references (PPtr) from/to JSON
#pragma warning disable 649
// serialize a PPtr to json: {"o":{"fileID":1234,"guid":"abcd1234","type":3}}
private class PPtrContainer
{
// keep name in sync with RawPPtrContainer.o
public UnityEngine.Object o;
}
// raw representation of the PPtrContainer serialization result
// keep member names and types synchronized with PPtr serialization
[Serializable]
private struct RawPPtrReference
{
public long fileID;
public string guid;
public int type;
}
private class RawPPtrContainer
{
// keep name in sync with PPtrContainer.o
public RawPPtrReference o;
}
#pragma warning restore 649
// pre-allocate these containers to avoid repeated managed allocations
// JSON serialization only works on classes
private static readonly PPtrContainer s_PPtrContainer = new PPtrContainer();
private static readonly RawPPtrContainer s_RawPPtrContainer = new RawPPtrContainer();
private static readonly char[] s_Separator = {'&'};
private struct UriQueryParameters
{
public string query;
public string guid;
public long fileId;
public int type;
public bool hasQuery, hasValidQuery, hasExtraQueryParams;
public bool hasGuid, hasFileId, hasType;
public bool hasAllReferenceParams => hasValidQuery && hasGuid && hasFileId && hasType;
}
private static UriQueryParameters ExtractUriQueryParameters(Uri uri)
{
var result = new UriQueryParameters();
var query = uri.Query;
if (query == null || query.Length <= 1)
return result;
query = query.Substring(1); // skip '?'
result.query = query;
result.hasQuery = true;
result.hasValidQuery = true;
// no access to System.Web.dll here
var queryParameters = query.Split(s_Separator);
// all 3 parameters must be found in the query string for the asset reference to be valid
foreach (var queryParameter in queryParameters)
{
var splitIndex = queryParameter.IndexOf('=');
if (splitIndex > 0 && splitIndex < queryParameter.Length - 1)
{
var key = queryParameter.Substring(0, splitIndex);
var value = queryParameter.Substring(splitIndex + 1);
switch (key)
{
case k_AttrGuid:
result.guid = value;
result.hasGuid = !string.IsNullOrEmpty(result.guid);
break;
case k_AttrFileId:
result.hasFileId = long.TryParse(value, out result.fileId);
break;
case k_AttrType:
result.hasType = int.TryParse(value, out result.type);
break;
default:
result.hasExtraQueryParams = true;
break;
}
}
else
{
result.hasValidQuery = false;
return result;
}
}
return result;
}
private static string ExtractUrlFragment(ref string path)
{
int fragmentLocation = path.LastIndexOf('#');
if (fragmentLocation == -1)
return string.Empty;
var fragment = Uri.UnescapeDataString(path.Substring(fragmentLocation + 1));
path = path.Substring(0, fragmentLocation);
return fragment;
}
public static string InjectFileNameSuffix(string path, string suffix)
{
string ext = Path.GetExtension(path);
string fileRenamed = Path.GetFileNameWithoutExtension(path) + suffix + ext;
return Path.Combine(Path.GetDirectoryName(path), fileRenamed);
}
}
}
| UnityCsReference/Editor/Mono/UIElements/StyleSheets/URIHelpers.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/UIElements/StyleSheets/URIHelpers.cs",
"repo_id": "UnityCsReference",
"token_count": 9688
} | 358 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Mono.Cecil;
using Mono.Cecil.Cil;
using UnityEditor.Utils;
using UnityEngine.Scripting;
namespace UnityEditor
{
internal class AssemblyReferenceChecker
{
private readonly HashSet<string> _referencedMethods = new HashSet<string>();
private HashSet<string> _referencedTypes = new HashSet<string>();
private readonly HashSet<string> _userReferencedMethods = new HashSet<string>();
private readonly HashSet<string> _definedMethods = new HashSet<string>();
private HashSet<AssemblyDefinition> _assemblyDefinitions = new HashSet<AssemblyDefinition>();
private readonly HashSet<string> _assemblyFileNames = new HashSet<string>();
private readonly INetStandardPathProvider _netStandardPathProvider;
private DateTime _startTime = DateTime.MinValue;
private float _progressValue = 0.0f;
private Action _updateProgressAction;
public bool HasMouseEvent { get; private set; }
public AssemblyReferenceChecker() : this(new DefaultStandardPathProvider()) { }
internal AssemblyReferenceChecker(INetStandardPathProvider netStandardPathProvider)
{
HasMouseEvent = false;
_updateProgressAction = DisplayProgress;
_netStandardPathProvider = netStandardPathProvider;
}
static HashSet<string> BuildReferencedTypeList(AssemblyDefinition[] assemblies)
{
HashSet<string> res = new HashSet<string>();
foreach (AssemblyDefinition ass in assemblies)
{
//string assname = ass.Name.Name;
if (!ass.Name.Name.StartsWith("System") && !ass.Name.Name.Equals("UnityEngine"))
{
foreach (TypeReference typ in ass.MainModule.GetTypeReferences())
{
res.Add(typ.FullName);
}
}
}
return res;
}
internal interface INetStandardPathProvider
{
IEnumerable<string> GetNetStandardReferenceAndCompatShimDirs();
}
internal class DefaultStandardPathProvider : INetStandardPathProvider
{
public IEnumerable<string> GetNetStandardReferenceAndCompatShimDirs()
{
yield return NetStandardFinder.GetReferenceDirectory();
yield return NetStandardFinder.GetDotNetFrameworkCompatShimsDirectory();
yield return NetStandardFinder.GetNetStandardCompatShimsDirectory();
}
}
public static AssemblyReferenceChecker AssemblyReferenceCheckerWithUpdateProgressAction(Action action)
{
var checker = new AssemblyReferenceChecker();
checker._updateProgressAction = action;
return checker;
}
internal static AssemblyReferenceChecker AssemblyReferenceCheckerWithUpdateProgressAction(Action action, INetStandardPathProvider netStandardPathProvider)
{
var checker = new AssemblyReferenceChecker(netStandardPathProvider);
checker._updateProgressAction = action;
return checker;
}
// Follows actually referenced libraries only
private void CollectReferencesFromRootsRecursive(string dir, IEnumerable<string> roots, bool ignoreSystemDlls)
{
using (var resolver = AssemblyResolverFor(dir))
{
foreach (var assemblyFileName in roots)
{
var fileName = Path.Combine(dir, assemblyFileName);
if (_assemblyFileNames.Contains(assemblyFileName))
continue;
// It is possible to have references to missing assemblies, if the compiler emitted an assembly reference
// which was not actually needed (https://github.com/dotnet/roslyn/issues/31192), so that UnityLinker would
// then delete such an assembly.
if (!File.Exists(fileName))
continue;
var assemblyDefinition = AssemblyDefinition.ReadAssembly(fileName, new ReaderParameters { AssemblyResolver = resolver });
if (ignoreSystemDlls && IsIgnoredSystemDll(assemblyDefinition))
continue;
_assemblyFileNames.Add(assemblyFileName);
_assemblyDefinitions.Add(assemblyDefinition);
foreach (var reference in assemblyDefinition.MainModule.AssemblyReferences)
{
var refFileName = reference.Name + ".dll";
if (_assemblyFileNames.Contains(refFileName))
continue;
CollectReferencesFromRootsRecursive(dir, new string[] {refFileName}, ignoreSystemDlls);
}
}
}
}
// Follows actually referenced libraries only
public void CollectReferencesFromRoots(string dir, IEnumerable<string> roots, bool collectMethods, float progressValue, bool ignoreSystemDlls)
{
_progressValue = progressValue;
CollectReferencesFromRootsRecursive(dir, roots, ignoreSystemDlls);
var assemblyDefinitionsAsArray = _assemblyDefinitions.ToArray();
_referencedTypes = BuildReferencedTypeList(assemblyDefinitionsAsArray);
if (collectMethods)
CollectReferencedAndDefinedMethods(assemblyDefinitionsAsArray);
}
public void CollectReferences(string path, bool collectMethods, float progressValue, bool ignoreSystemDlls)
{
_progressValue = progressValue;
_assemblyDefinitions = new HashSet<AssemblyDefinition>();
var filePaths = Directory.Exists(path) ? Directory.GetFiles(path) : new string[0];
using (var resolver = AssemblyResolverFor(path))
{
foreach (var filePath in filePaths)
{
if (Path.GetExtension(filePath) != ".dll")
continue;
var assembly = AssemblyDefinition.ReadAssembly(filePath, new ReaderParameters { AssemblyResolver = resolver });
if (ignoreSystemDlls && IsIgnoredSystemDll(assembly))
continue;
_assemblyFileNames.Add(Path.GetFileName(filePath));
_assemblyDefinitions.Add(assembly);
}
}
var assemblyDefinitionsAsArray = _assemblyDefinitions.ToArray();
_referencedTypes = BuildReferencedTypeList(assemblyDefinitionsAsArray);
if (collectMethods)
CollectReferencedAndDefinedMethods(assemblyDefinitionsAsArray);
}
private void CollectReferencedAndDefinedMethods(IEnumerable<AssemblyDefinition> assemblyDefinitions)
{
foreach (var assembly in assemblyDefinitions)
{
bool boolIsSystem = IsIgnoredSystemDll(assembly);
foreach (var type in assembly.MainModule.Types)
CollectReferencedAndDefinedMethods(type, boolIsSystem);
}
}
internal void CollectReferencedAndDefinedMethods(TypeDefinition type)
{
CollectReferencedAndDefinedMethods(type, false);
}
internal void CollectReferencedAndDefinedMethods(TypeDefinition type, bool isSystem)
{
if (_updateProgressAction != null)
_updateProgressAction();
foreach (var nestedType in type.NestedTypes)
CollectReferencedAndDefinedMethods(nestedType, isSystem);
foreach (var method in type.Methods)
{
try
{
if (!method.HasBody)
continue;
foreach (var instr in method.Body.Instructions)
{
if (OpCodes.Call == instr.OpCode)
{
var name = instr.Operand.ToString();
if (!isSystem)
{
_userReferencedMethods.Add(name);
}
_referencedMethods.Add(name);
}
}
_definedMethods.Add(method.ToString());
HasMouseEvent |= MethodIsMouseEvent(method);
}
catch (Exception ex)
{
throw new InvalidOperationException($"Error while observing opcode in {type.FullName}::{method?.ToString()}", ex);
}
}
}
private bool MethodIsMouseEvent(MethodDefinition method)
{
var methodNameIsMouseEvent =
method.Name == "OnMouseDown"
|| method.Name == "OnMouseDrag"
|| method.Name == "OnMouseEnter"
|| method.Name == "OnMouseExit"
|| method.Name == "OnMouseOver"
|| method.Name == "OnMouseUp"
|| method.Name == "OnMouseUpAsButton";
if (!methodNameIsMouseEvent)
return false;
if (method.Parameters.Count != 0)
return false;
bool isInUnityEngineBehavior = InheritsFromMonoBehaviour(method.DeclaringType);
if (!isInUnityEngineBehavior)
return false;
return true;
}
private bool InheritsFromMonoBehaviour(TypeReference type)
{
// Case 833157: StagingArea\Data\Managed contains user and dependency assemblies, but doesn't contain UnityEngine.dll. This applies for all platforms
// Thus we wouldn't be able to load UnityEngine.dll when Resolve() is called. That's why we're delaying Resolve() as much as possible
if (type.Namespace == "UnityEngine" && type.Name == "MonoBehaviour")
return true;
try
{
var typeDefinition = type.Resolve();
if (typeDefinition.BaseType != null)
return InheritsFromMonoBehaviour(typeDefinition.BaseType);
}
catch (AssemblyResolutionException)
{
// We weren't able to resolve the base type - let's assume it's not a monobehaviour
}
return false;
}
private void DisplayProgress()
{
var elapsedTime = DateTime.Now - _startTime;
var progressStrings = new[]
{
"Fetching assembly references",
"Building list of referenced assemblies..."
};
if (elapsedTime.TotalMilliseconds >= 100)
{
if (EditorUtility.DisplayCancelableProgressBar(progressStrings[0], progressStrings[1], _progressValue))
throw new OperationCanceledException();
_startTime = DateTime.Now;
}
}
public bool HasReferenceToMethod(string methodName)
{
return HasReferenceToMethod(methodName, false);
}
public bool HasReferenceToMethod(string methodName, bool ignoreSystemDlls)
{
return !ignoreSystemDlls? _referencedMethods.Any(item => item.Contains(methodName)) : _userReferencedMethods.Any(item => item.Contains(methodName));
}
public bool HasDefinedMethod(string methodName)
{
return _definedMethods.Any(item => item.Contains(methodName));
}
public bool HasReferenceToType(string typeName)
{
return _referencedTypes.Any(item => item.StartsWith(typeName));
}
public AssemblyDefinition[] GetAssemblyDefinitions()
{
return _assemblyDefinitions.ToArray();
}
public string[] GetAssemblyFileNames()
{
return _assemblyFileNames.ToArray();
}
public string WhoReferencesClass(string klass, bool ignoreSystemDlls)
{
foreach (var assembly in _assemblyDefinitions)
{
if (ignoreSystemDlls && IsIgnoredSystemDll(assembly))
continue;
var assemblyDefinitionsAsArray = new[] {assembly};
var types = BuildReferencedTypeList(assemblyDefinitionsAsArray);
if (types.Any(item => item.StartsWith(klass)))
return assembly.Name.Name;
}
return null;
}
public static bool IsIgnoredSystemDll(AssemblyDefinition assembly)
{
if (AssemblyHelper.IsUnityEngineModule(assembly))
return true;
var name = assembly.Name.Name;
return name.StartsWith("System")
|| name.Equals("UnityEngine")
|| name.Equals("UnityEngine.Networking")
|| name.Equals("Mono.Posix")
|| name.Equals("Moq")
|| name.StartsWith("Unity.VisualScripting");
}
[RequiredByNativeCode]
public static bool GetScriptsHaveMouseEvents(string path)
{
var checker = new AssemblyReferenceChecker();
checker.CollectReferences(path, true, 0.0f, true);
return checker.HasMouseEvent;
}
private DefaultAssemblyResolver AssemblyResolverFor(string path)
{
var resolver = new DefaultAssemblyResolver();
if (File.Exists(path) || Directory.Exists(path))
{
var attributes = File.GetAttributes(path);
if ((attributes & FileAttributes.Directory) != FileAttributes.Directory)
path = Path.GetDirectoryName(path);
resolver.AddSearchDirectory(Path.GetFullPath(path));
}
// add .net standard ref and compat shims dirs
foreach(var dir in _netStandardPathProvider.GetNetStandardReferenceAndCompatShimDirs())
{
resolver.AddSearchDirectory(dir);
}
return resolver;
}
}
}
| UnityCsReference/Editor/Mono/Utils/AssemblyReferenceChecker.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Utils/AssemblyReferenceChecker.cs",
"repo_id": "UnityCsReference",
"token_count": 6696
} | 359 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using UnityEngine.Bindings;
namespace UnityEditor.Utils
{
[VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal static class Paths
{
internal static char[] invalidFilenameChars;
static Paths()
{
var uniqueChars = new HashSet<char>(Path.GetInvalidFileNameChars());
uniqueChars.Add(Path.DirectorySeparatorChar);
uniqueChars.Add(Path.AltDirectorySeparatorChar);
invalidFilenameChars = uniqueChars.ToArray();
}
public static string Combine(params string[] components)
{
if (components.Length < 1)
throw new ArgumentException("At least one component must be provided!");
string path = components[0];
for (int i = 1; i < components.Length; i++)
path = Path.Combine(path, components[i]);
return path;
}
public static string[] Split(string path)
{
List<string> result = new List<string>(path.Split(Path.DirectorySeparatorChar));
for (int i = 0; i < result.Count;)
{
result[i] = result[i].Trim();
if (result[i].Equals(""))
{
result.RemoveAt(i);
}
else
{
i++;
}
}
return result.ToArray();
}
public static string GetFileOrFolderName(string path)
{
string name;
if (File.Exists(path))
{
name = Path.GetFileName(path);
}
else if (Directory.Exists(path))
{
string[] pathSplit = Split(path);
name = pathSplit[pathSplit.Length - 1];
}
else
{
throw new ArgumentException("Target '" + path + "' does not exist.");
}
return name;
}
public static string CreateTempDirectory()
{
for (int i = 0; i < 32; ++i)
{
string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
if (File.Exists(tempDirectory) || Directory.Exists(tempDirectory))
continue;
Directory.CreateDirectory(tempDirectory);
return tempDirectory;
}
throw new IOException("CreateTempDirectory failed");
}
public static string NormalizePath(this string path)
{
if (Path.DirectorySeparatorChar == '\\')
return path.Replace('/', Path.DirectorySeparatorChar);
return path.Replace('\\', Path.DirectorySeparatorChar);
}
public static string ConvertSeparatorsToWindows(this string path)
{
return path.Replace('/', '\\');
}
public static string ConvertSeparatorsToUnity(this string path)
{
return path.Replace('\\', '/');
}
public static string TrimTrailingSlashes(this string path)
{
return path.TrimEnd(new[] { '/', '\\' });
}
public static string GetPathRelativeToProjectDirectory(string filePath)
{
return String.Join(separator: "/",
value: filePath.ConvertSeparatorsToUnity().TrimTrailingSlashes().Split('/').SkipWhile(s => s != "assets" && s != "Assets").ToArray());
}
public static string SkipPathPrefix(string path, string prefix)
{
if (path.StartsWith(prefix))
return path.Substring(prefix.Length + 1);
return path;
}
public static string UnifyDirectorySeparator(string path)
{
return path.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar);
}
public static bool AreEqual(string pathA, string pathB, bool ignoreCase)
{
if (pathA == "" && pathB == "" ||
pathA == null && pathB == null)
return true;
if (String.IsNullOrEmpty(pathA) || String.IsNullOrEmpty(pathB))
{
// GetFullPath will throw otherwise.
return false;
}
return string.Compare(Path.GetFullPath(pathA), Path.GetFullPath(pathB), ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0;
}
public static bool CheckValidAssetPathAndThatDirectoryExists(string assetFilePath, string requiredExtensionWithDot)
{
if (!IsValidAssetPathWithErrorLogging(assetFilePath, requiredExtensionWithDot))
return false;
string dir = Path.GetDirectoryName(assetFilePath);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
{
UnityEngine.Debug.LogError("Parent directory must exist before creating asset at: " + assetFilePath);
return false;
}
return true;
}
public static bool IsValidAssetPathWithErrorLogging(string assetPath, string requiredExtensionWithDot)
{
string errorMsg;
if (!IsValidAssetPath(assetPath, requiredExtensionWithDot, out errorMsg))
{
UnityEngine.Debug.LogError(errorMsg);
return false;
}
return true;
}
public static bool IsValidAssetPath(string assetPath)
{
const string requiredExtension = null;
return IsValidAssetPath(assetPath, requiredExtension);
}
public static bool IsValidAssetPath(string assetPath, string requiredExtensionWithDot)
{
string errorMsg = null;
return CheckIfAssetPathIsValid(assetPath, requiredExtensionWithDot, ref errorMsg);
}
public static bool IsValidAssetPath(string assetPath, string requiredExtensionWithDot, out string errorMsg)
{
errorMsg = string.Empty;
return CheckIfAssetPathIsValid(assetPath, requiredExtensionWithDot, ref errorMsg);
}
// If an error message is wanted then input an empty string for 'errorMsg'. If 'errorMsg' is null then no error string is allocated.
static bool CheckIfAssetPathIsValid(string assetPath, string requiredExtensionWithDot, ref string errorMsg)
{
string fileName;
try
{
if (string.IsNullOrEmpty(assetPath))
{
if (errorMsg != null)
SetFullErrorMessage("Asset path is empty", assetPath, ref errorMsg);
return false;
}
fileName = Path.GetFileName(assetPath); // Will throw an ArgumentException if the path contains one or more of the invalid characters defined in GetInvalidPathChars
}
catch (Exception e)
{
if (errorMsg != null)
SetFullErrorMessage(e.Message, assetPath, ref errorMsg);
return false;
}
return CheckIfFilenameIsValid(fileName, "asset name", requiredExtensionWithDot, ref errorMsg);
}
public static bool IsValidFilename(string assetPath)
{
const string requiredExtension = null;
return IsValidFilename(assetPath, requiredExtension);
}
public static bool IsValidFilename(string assetPath, string requiredExtensionWithDot)
{
string errorMsg = null;
return CheckIfFilenameIsValid(assetPath, "filename", requiredExtensionWithDot, ref errorMsg);
}
public static bool IsValidFilename(string assetPath, string requiredExtensionWithDot, out string errorMsg)
{
errorMsg = string.Empty;
return CheckIfFilenameIsValid(assetPath, "filename", requiredExtensionWithDot, ref errorMsg);
}
static bool CheckIfFilenameIsValid(string fileName, string argumentName, string requiredExtensionWithDot, ref string errorMsg)
{
try
{
if (string.IsNullOrEmpty(fileName))
{
if (errorMsg != null)
SetFullErrorMessage(string.Format("The {0} is empty", argumentName), fileName, ref errorMsg);
return false;
}
if (fileName.IndexOfAny(invalidFilenameChars) >= 0)
{
if (errorMsg != null)
SetFullErrorMessage(string.Format("The {0} contains invalid characters", argumentName), fileName, ref errorMsg);
return false;
}
if (fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
{
if (errorMsg != null)
SetFullErrorMessage("Invalid characters in file name: ", fileName, ref errorMsg);
return false;
}
if (fileName.StartsWith("."))
{
if (errorMsg != null)
SetFullErrorMessage(string.Format("Do not prefix {0} with '.'", argumentName), fileName, ref errorMsg);
return false;
}
if (fileName.StartsWith(" "))
{
if (errorMsg != null)
SetFullErrorMessage(string.Format("Do not prefix {0} with white space", argumentName), fileName, ref errorMsg);
return false;
}
if (!string.IsNullOrEmpty(requiredExtensionWithDot))
{
string extension = Path.GetExtension(fileName);
if (!String.Equals(extension, requiredExtensionWithDot, StringComparison.OrdinalIgnoreCase))
{
if (errorMsg != null)
SetFullErrorMessage(string.Format("Incorrect extension. Required extension is: '{0}'", requiredExtensionWithDot), fileName, ref errorMsg);
return false;
}
}
}
catch (Exception e)
{
if (errorMsg != null)
SetFullErrorMessage(e.Message, fileName, ref errorMsg);
return false;
}
return true;
}
static void SetFullErrorMessage(string error, string assetPath, ref string errorMsg)
{
errorMsg = string.Format("Asset path error: '{0}' is not valid: {1}", ToLiteral(assetPath), error);
}
/// Escapes a string so that escape sequences of ASCII and unicode characters are shown. Taken from http://stackoverflow.com/a/14087738
static string ToLiteral(string input)
{
if (string.IsNullOrEmpty(input))
return string.Empty;
var literal = new System.Text.StringBuilder(input.Length + 2);
foreach (var c in input)
{
switch (c)
{
case '\'': literal.Append(@"\'"); break;
case '\"': literal.Append("\\\""); break;
case '\\': literal.Append(@"\\"); break;
case '\0': literal.Append(@"\0"); break;
case '\a': literal.Append(@"\a"); break;
case '\b': literal.Append(@"\b"); break;
case '\f': literal.Append(@"\f"); break;
case '\n': literal.Append(@"\n"); break;
case '\r': literal.Append(@"\r"); break;
case '\t': literal.Append(@"\t"); break;
case '\v': literal.Append(@"\v"); break;
default:
// ASCII printable character
if (c >= 0x20 && c <= 0x7e)
{
literal.Append(c);
}
// As UTF16 escaped character
else
{
literal.Append(@"\u");
literal.Append(((int)c).ToString("x4"));
}
break;
}
}
return literal.ToString();
}
public static string MakeValidFileName(string unsafeFileName)
{
var normalizedFileName = unsafeFileName.Trim().Normalize(NormalizationForm.FormD);
var stringBuilder = new StringBuilder();
// We need to use a TextElementEmumerator in order to support UTF16 characters that may take up more than one char(case 1169358)
TextElementEnumerator charEnum = StringInfo.GetTextElementEnumerator(normalizedFileName);
while (charEnum.MoveNext())
{
var c = charEnum.GetTextElement();
if (c.Length == 1 && invalidFilenameChars.Contains(c[0]))
continue;
var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c, 0);
if (unicodeCategory != UnicodeCategory.NonSpacingMark)
stringBuilder.Append(c);
}
return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
}
static readonly char[] PathSeparators = new[] { '\\', '/' };
public static string MakeRelativePath(string basePath, string filePath)
{
var basePathComponents = basePath.Split(PathSeparators, StringSplitOptions.RemoveEmptyEntries);
var filePathComponents = filePath.Split(PathSeparators, StringSplitOptions.RemoveEmptyEntries);
int commonParts;
for (commonParts = 0; commonParts < basePathComponents.Length && commonParts < filePathComponents.Length; commonParts++)
{
if (basePathComponents[commonParts].ToLower() != filePathComponents[commonParts].ToLower())
break;
}
var relativePathParts = new List<string>();
var parentDirCount = basePathComponents.Length - commonParts;
for (int i = 0; i < parentDirCount; i++)
relativePathParts.Add("..");
for (int i = commonParts; i < filePathComponents.Length; i++)
relativePathParts.Add(filePathComponents[i]);
return string.Join("\\", relativePathParts.ToArray());
}
}
}
| UnityCsReference/Editor/Mono/Utils/Paths.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Utils/Paths.cs",
"repo_id": "UnityCsReference",
"token_count": 7225
} | 360 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
using UnityEditor;
using UnityEditor.VersionControl;
namespace UnityEditorInternal.VersionControl
{
// This is a custom nested, double linked list. This provides flexibility to search quickly up and down
// the list. Particularly when parts of the list are expanded or not.
public class ListItem
{
ListItem m_Parent;
ListItem m_FirstChild;
ListItem m_LastChild;
ListItem m_Prev;
ListItem m_Next;
Texture m_Icon;
string m_Name;
int m_Indent;
bool m_Expanded;
bool m_Exclusive;
bool m_Dummy;
bool m_Hidden;
bool m_Accept;
object m_Item;
string[] m_Actions;
int m_Identifier;
static Texture2D s_DefaultIcon = null;
public ListItem()
{
Clear();
m_Identifier = (int)(VCSProviderIdentifier.UnsetIdentifier);
}
~ListItem()
{
Clear();
}
public Texture Icon
{
get
{
if (s_DefaultIcon == null)
{
s_DefaultIcon = EditorGUIUtility.LoadIcon("VersionControl/File");
s_DefaultIcon.hideFlags = HideFlags.HideAndDontSave;
}
Asset asset = m_Item as Asset;
if (m_Icon == null && asset != null)
{
if (asset.isInCurrentProject)
{
m_Icon = AssetDatabase.GetCachedIcon(asset.path);
}
else
{
m_Icon = s_DefaultIcon;
}
}
return m_Icon;
}
set { m_Icon = value; }
}
public int Identifier
{
get
{
if (m_Identifier == (int)(VCSProviderIdentifier.UnsetIdentifier))
{
m_Identifier = Provider.GenerateID();
}
return m_Identifier;
}
}
public string Name
{
get { return m_Name; }
set { m_Name = value; }
}
public int Indent
{
get { return m_Indent; }
set { SetIntent(this, value); }
}
public object Item
{
get { return m_Item; }
set { m_Item = value; }
}
public Asset Asset
{
get { return m_Item as Asset; }
set { m_Item = value; }
}
public bool HasPath()
{
Asset a = m_Item as Asset;
return a != null && a.path != null;
}
public ChangeSet Change
{
get { return m_Item as ChangeSet; }
set { m_Item = value; }
}
public bool Expanded
{
get { return m_Expanded; }
set { m_Expanded = value; }
}
public bool Exclusive
{
get { return m_Exclusive; }
set { m_Exclusive = value; }
}
public bool Dummy
{
get { return m_Dummy; }
set { m_Dummy = value; }
}
public bool Hidden
{
get { return m_Hidden; }
set { m_Hidden = value; }
}
public bool HasChildren
{
get { return FirstChild != null; }
}
public bool HasActions
{
get { return m_Actions != null && m_Actions.Length != 0; }
}
public string[] Actions
{
get { return m_Actions; }
set { m_Actions = value; }
}
public bool CanExpand
{
get
{
// Asset asset = item as Asset;
ChangeSet change = m_Item as ChangeSet;
// return ((asset != null && asset.isFolder) ||
// change != null ||
// HasChildren);
return (change != null || HasChildren);
}
}
public bool CanAccept
{
get { return m_Accept; }
set { m_Accept = value; }
}
public int OpenCount
{
get
{
if (!Expanded)
return 0;
int count = 0;
ListItem listItem = m_FirstChild;
while (listItem != null)
{
if (!listItem.Hidden)
{
++count;
count += listItem.OpenCount;
}
listItem = listItem.m_Next;
}
return count;
}
}
public int ChildCount
{
get
{
int count = 0;
ListItem listItem = m_FirstChild;
while (listItem != null)
{
++count;
listItem = listItem.m_Next;
}
return count;
}
}
internal int VisibleChildCount
{
get
{
if (!m_Expanded) return 0;
int count = 0;
ListItem listItem = m_FirstChild;
while (listItem != null)
{
if (!listItem.Hidden && !listItem.Dummy) ++count;
listItem = listItem.m_Next;
}
return count;
}
}
internal int VisibleItemCount
{
get
{
if (!m_Expanded) return 0;
int count = 0;
ListItem listItem = m_FirstChild;
while (listItem != null)
{
if (!listItem.Hidden) ++count;
listItem = listItem.m_Next;
}
return count;
}
}
public ListItem Parent
{
get { return m_Parent; }
}
public ListItem FirstChild
{
get { return m_FirstChild; }
}
public ListItem LastChild
{
get { return m_LastChild; }
}
public ListItem Prev
{
get { return m_Prev; }
}
public ListItem Next
{
get { return m_Next; }
}
public ListItem PrevOpen
{
get
{
// Previous sibbling or its last open child
ListItem enumChild = m_Prev;
while (enumChild != null)
{
if (enumChild.m_LastChild == null || !enumChild.Expanded)
return enumChild;
enumChild = enumChild.m_LastChild;
}
// Move to parent as long as its not the root
if (m_Parent != null && m_Parent.m_Parent != null)
return m_Parent;
return null;
}
}
public ListItem NextOpen
{
get
{
// Next child
if (Expanded && m_FirstChild != null)
return m_FirstChild;
// Next sibbling
if (m_Next != null)
return m_Next;
// Find a parent with a next
ListItem enumParent = m_Parent;
while (enumParent != null)
{
if (enumParent.Next != null)
return enumParent.Next;
enumParent = enumParent.m_Parent;
}
return null;
}
}
public ListItem PrevOpenSkip
{
get
{
ListItem listItem = PrevOpen;
while (listItem != null && (listItem.Dummy || listItem.Hidden))
listItem = listItem.PrevOpen;
return listItem;
}
}
public ListItem NextOpenSkip
{
get
{
ListItem listItem = NextOpen;
while (listItem != null && (listItem.Dummy || listItem.Hidden))
listItem = listItem.NextOpen;
return listItem;
}
}
public ListItem PrevOpenVisible
{
get
{
ListItem listItem = PrevOpen;
while (listItem != null && listItem.Hidden)
listItem = listItem.PrevOpen;
return listItem;
}
}
public ListItem NextOpenVisible
{
get
{
ListItem listItem = NextOpen;
while (listItem != null && listItem.Hidden)
listItem = listItem.NextOpen;
return listItem;
}
}
public bool IsChildOf(ListItem listItem)
{
ListItem it = Parent;
while (it != null)
{
if (it == listItem)
return true;
it = it.Parent;
}
return false;
}
public void Clear()
{
m_Parent = null;
m_FirstChild = null;
m_LastChild = null;
m_Prev = null;
m_Next = null;
m_Icon = null;
m_Name = string.Empty;
m_Indent = 0;
m_Expanded = false;
m_Exclusive = false;
m_Dummy = false;
m_Accept = false;
m_Item = null;
}
public void Add(ListItem listItem)
{
listItem.m_Parent = this;
listItem.m_Next = null;
listItem.m_Prev = m_LastChild;
// recursively update the indent
listItem.Indent = m_Indent + 1;
if (m_FirstChild == null)
m_FirstChild = listItem;
if (m_LastChild != null)
m_LastChild.m_Next = listItem;
m_LastChild = listItem;
}
public bool Remove(ListItem listItem)
{
if (listItem == null)
return false;
// Can only remove children of this item
if (listItem.m_Parent != this)
return false;
if (listItem == m_FirstChild)
m_FirstChild = listItem.m_Next;
if (listItem == m_LastChild)
m_LastChild = listItem.m_Prev;
if (listItem.m_Prev != null)
listItem.m_Prev.m_Next = listItem.m_Next;
if (listItem.m_Next != null)
listItem.m_Next.m_Prev = listItem.m_Prev;
listItem.m_Parent = null;
listItem.m_Prev = null;
listItem.m_Next = null;
return true;
}
public void RemoveAll()
{
ListItem en = m_FirstChild;
while (en != null)
{
en.m_Parent = null;
en = en.m_Next;
}
m_FirstChild = null;
m_LastChild = null;
}
public ListItem FindWithIdentifierRecurse(int inIdentifier)
{
if (Identifier == inIdentifier)
return this;
ListItem listItem = m_FirstChild;
while (listItem != null)
{
ListItem found = listItem.FindWithIdentifierRecurse(inIdentifier);
if (found != null)
return found;
listItem = listItem.m_Next;
}
return null;
}
void SetIntent(ListItem listItem, int indent)
{
listItem.m_Indent = indent;
// Update children
ListItem en = listItem.FirstChild;
while (en != null)
{
SetIntent(en, indent + 1);
en = en.Next;
}
}
}
}
| UnityCsReference/Editor/Mono/VersionControl/UI/VCListItem.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/VersionControl/UI/VCListItem.cs",
"repo_id": "UnityCsReference",
"token_count": 7238
} | 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.Collections.Generic;
using UnityEngine;
using UnityEngine.Bindings;
using UnityEngine.Scripting;
using System.Runtime.InteropServices;
using System.Linq;
namespace UnityEditor.VersionControl
{
// This MUST be kept synchronized with the VCS_PROVIDER_UNSET_IDENTIFIER enum in VCProvider.cpp
enum VCSProviderIdentifier
{
UnsetIdentifier = -1
}
// Keep internal and undocumented until we expose more functionality
[NativeHeader("Editor/Src/VersionControl/VC_bindings.h")]
[NativeHeader("Editor/Src/VersionControl/VCProvider.h")]
[NativeHeader("Editor/Src/VersionControl/VCPlugin.h")]
[NativeHeader("Editor/Src/VersionControl/VCTask.h")]
[NativeHeader("Editor/Src/VersionControl/VCCache.h")]
public partial class Provider
{
[StaticAccessor("GetVCProvider()", StaticAccessorType.Dot)]
public static extern bool enabled
{
[NativeMethod("Enabled")]
get;
}
[StaticAccessor("GetVCProvider()", StaticAccessorType.Dot)]
public static extern bool isActive
{
[NativeMethod("IsActive")]
get;
}
[UsedByNativeCode]
[StructLayout(LayoutKind.Sequential)]
private struct Traits
{
public bool requiresNetwork;
public bool enablesCheckout;
public bool enablesVersioningFolders;
public bool enablesChangelists;
public bool enablesLocking;
}
private static extern Traits activeTraits
{
[FreeFunction("VersionControlBindings::VCProvider::GetActiveTraits")]
get;
}
public static bool requiresNetwork
{
get { return activeTraits.requiresNetwork; }
}
public static bool hasChangelistSupport
{
get { return activeTraits.enablesChangelists; }
}
public static bool hasCheckoutSupport
{
get { return activeTraits.enablesCheckout; }
}
public static bool hasLockingSupport
{
get { return activeTraits.enablesLocking; }
}
public static bool isVersioningFolders
{
get { return activeTraits.enablesVersioningFolders; }
}
[StaticAccessor("GetVCProvider()", StaticAccessorType.Dot)]
public static extern OnlineState onlineState
{
[NativeMethod("GetOnlineState")]
get;
}
[StaticAccessor("GetVCProvider()", StaticAccessorType.Dot)]
public static extern string offlineReason
{
[NativeMethod("OfflineReason")]
get;
}
public static extern Task activeTask
{
[FreeFunction("VersionControlBindings::VCProvider::GetActiveTask")]
get;
}
[StaticAccessor("GetVCProvider()", StaticAccessorType.Dot)]
internal static extern Texture2D overlayAtlas
{
[NativeMethod("GetOverlayAtlas")]
get;
}
[FreeFunction("VersionControlBindings::VCProvider::GetAtlasRectForState")]
internal static extern Rect GetAtlasRectForState(int state);
[FreeFunction("VersionControlBindings::VCProvider::GetActivePlugin")]
public static extern Plugin GetActivePlugin();
[FreeFunction("VersionControlBindings::VCProvider::GetActiveConfigFields")]
public static extern ConfigField[] GetActiveConfigFields();
[StaticAccessor("GetVCProvider()", StaticAccessorType.Dot)]
internal static extern bool IsCustomCommandEnabled(string name);
[StaticAccessor("GetVCProvider()", StaticAccessorType.Dot)]
internal static extern CustomCommand[] customCommands
{
[NativeMethod("GetMonoCustomCommands")]
get;
}
[StaticAccessor("GetVCProvider()", StaticAccessorType.Dot)]
internal static extern void ClearCustomCommands();
[FreeFunction("VersionControlBindings::VCProvider::Internal_CacheStatus")]
private static extern Asset Internal_CacheStatus(string assetPath);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_Status")]
private static extern Task Internal_Status(Asset[] assets, bool recursively);
[FreeFunction("VersionControlBindings::VCProvider::Internal_StatusStrings")]
private static extern Task Internal_StatusStrings(string[] assetsProjectPaths, bool recursively);
[FreeFunction("VersionControlBindings::VCProvider::Internal_StatusAbsolutePath")]
private static extern Task Internal_StatusAbsolutePath(string assetPath);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_CheckoutIsValid")]
private static extern bool Internal_CheckoutIsValid(Asset[] assets, CheckoutMode mode);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_Checkout")]
private static extern Task Internal_Checkout(Asset[] assets, CheckoutMode mode, ChangeSet changeset);
[FreeFunction("VersionControlBindings::VCProvider::MakeEditable")]
internal static extern bool MakeEditableImpl(string[] assets, string prompt, ChangeSet changeSet, object outNotEditablePathsList);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_Delete")]
private static extern Task Internal_Delete(Asset[] assets);
[FreeFunction("VersionControlBindings::VCProvider::Internal_DeleteAtProjectPath")]
private static extern Task Internal_DeleteAtProjectPath([NotNull] string assetProjectPath);
[FreeFunction("VersionControlBindings::VCProvider::Internal_MoveAsStrings")]
private static extern Task Internal_MoveAsStrings([NotNull] string from, [NotNull] string to);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_AddIsValid")]
private static extern bool Internal_AddIsValid(Asset[] assets);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_Add")]
private static extern Task Internal_Add(Asset[] assets, bool recursive);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_DeleteChangeSetsIsValid")]
private static extern bool Internal_DeleteChangeSetsIsValid(ChangeSet[] changesets);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_DeleteChangeSets")]
private static extern Task Internal_DeleteChangeSets(ChangeSet[] changesets);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_RevertChangeSets")]
private static extern Task Internal_RevertChangeSets(ChangeSet[] changesets, RevertMode mode);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_SubmitIsValid")]
private static extern bool Internal_SubmitIsValid(ChangeSet changeset, Asset[] assets);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_Submit")]
private static extern Task Internal_Submit(ChangeSet changeset, Asset[] assets, string description, bool saveOnly);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_DiffIsValid")]
private static extern bool Internal_DiffIsValid(Asset[] assets);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_DiffHead")]
private static extern Task Internal_DiffHead(Asset[] assets, bool includingMetaFiles);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_ResolveIsValid")]
private static extern bool Internal_ResolveIsValid(Asset[] assets);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_Resolve")]
private static extern Task Internal_Resolve(Asset[] assets, ResolveMethod resolveMethod);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_Merge")]
private static extern Task Internal_Merge(Asset[] assets);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_LockIsValid")]
private static extern bool Internal_LockIsValid(Asset[] assets);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_UnlockIsValid")]
private static extern bool Internal_UnlockIsValid(Asset[] assets);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_Lock")]
private static extern Task Internal_Lock(Asset[] assets, bool locked);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_RevertIsValid")]
private static extern bool Internal_RevertIsValid(Asset[] assets, RevertMode revertMode);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_Revert")]
private static extern Task Internal_Revert(Asset[] assets, RevertMode revertMode);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_GetLatestIsValid")]
private static extern bool Internal_GetLatestIsValid(Asset[] assets);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_GetLatest")]
private static extern Task Internal_GetLatest(Asset[] assets);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_SetFileMode")]
private static extern Task Internal_SetFileMode(Asset[] assets, FileMode fileMode);
[FreeFunction("VersionControlBindings::VCProvider::Internal_SetFileModeStrings")]
private static extern Task Internal_SetFileModeStrings(string[] assets, FileMode fileMode);
[FreeFunction("VersionControlBindings::VCProvider::Internal_ChangeSetDescription")]
private static extern Task Internal_ChangeSetDescription([NotNull] ChangeSet changeset);
[FreeFunction("VersionControlBindings::VCProvider::Internal_ChangeSetStatus")]
private static extern Task Internal_ChangeSetStatus([NotNull] ChangeSet changeset);
[FreeFunction("VersionControlBindings::VCProvider::ChangeSets")]
public static extern Task ChangeSets();
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_ChangeSetMove")]
private static extern Task Internal_ChangeSetMove(Asset[] assets, [NotNull] ChangeSet target);
[FreeFunction("VersionControlBindings::VCProvider::Incoming")]
public static extern Task Incoming();
[FreeFunction("VersionControlBindings::VCProvider::Internal_IncomingChangeSetAssets")]
private static extern Task Internal_IncomingChangeSetAssets([NotNull] ChangeSet changeset);
[FreeFunction("VersionControlBindings::VCProvider::UpdateSettings")]
public static extern Task UpdateSettings();
[FreeFunction("VersionControlBindings::VCProvider::GetAssetByPath")]
public static extern Asset GetAssetByPath(string unityPath);
[FreeFunction("VersionControlBindings::VCProvider::GetAssetByGUID")]
public static extern Asset GetAssetByGUID(string guid);
[FreeFunction("VersionControlBindings::VCProvider::Internal_GetAssetArrayFromSelection")]
private static extern Asset[] Internal_GetAssetArrayFromSelection();
[FreeFunction("VersionControlBindings::VCProvider::IsOpenForEdit")]
public static extern bool IsOpenForEdit([NotNull] Asset asset);
[StaticAccessor("GetVCProvider()", StaticAccessorType.Dot)]
internal static extern int GenerateID();
[StaticAccessor("GetVCCache()", StaticAccessorType.Dot)]
[NativeMethod("Clear")]
public static extern void ClearCache();
[StaticAccessor("GetVCCache()", StaticAccessorType.Dot)]
[NativeMethod("Invalidate")]
internal static extern void InvalidateCache();
[FreeFunction("VersionControlBindings::VCProvider::Internal_CreateWarningTask")]
public static extern Task Internal_WarningTask([NotNull] string message);
[FreeFunction("VersionControlBindings::VCProvider::Internal_CreateErrorTask")]
public static extern Task Internal_ErrorTask([NotNull] string message);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_ConsolidateAssetList")]
private static extern Asset[] Internal_ConsolidateAssetList(Asset[] assets, CheckoutMode mode);
[StaticAccessor("VCProvider", StaticAccessorType.DoubleColon)]
[NativeMethod("ShouldAddMetaFile")]
static internal extern bool PathHasMetaFile(string path);
[StaticAccessor("VCProvider", StaticAccessorType.DoubleColon)]
[NativeMethod("ShouldPathBeVersioned")]
static internal extern bool PathIsVersioned(string path);
[NativeThrows]
[FreeFunction("VersionControlBindings::VCProvider::Internal_WaitForRelatedTasks")]
internal static extern void WaitForRelatedTasks(Asset[] assets);
internal static void WaitForRelatedTasks(string[] assets) => WaitForRelatedTasks(assets.Select(a => new Asset(a)).ToArray());
internal static void WaitForRelatedTasks(Asset asset) => WaitForRelatedTasks(new[] { asset });
internal static void WaitForRelatedTasks(string asset) => WaitForRelatedTasks(new[] { new Asset(asset) });
}
}
| UnityCsReference/Editor/Mono/VersionControl/VCProvider.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/VersionControl/VCProvider.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 4913
} | 362 |
//
// File autogenerated from Include/C/Baselib_Timer.h
//
using System;
using System.Runtime.InteropServices;
using UnityEngine.Bindings;
using size_t = System.UIntPtr;
namespace Unity.Baselib.LowLevel
{
[NativeHeader("baselib/CSharp/BindingsUnity/Baselib_Timer.gen.binding.h")]
internal static unsafe partial class Binding
{
/// <summary>Time conversion factors.</summary>
/// <remarks>(not an enum since Int32 can't represent Baselib_NanosecondsPerMinute)</remarks>
public const UInt64 Baselib_SecondsPerMinute = 60;
public const UInt64 Baselib_MillisecondsPerSecond = 1000;
public const UInt64 Baselib_MillisecondsPerMinute = 60000;
public const UInt64 Baselib_MicrosecondsPerMillisecond = 1000;
public const UInt64 Baselib_MicrosecondsPerSecond = 1000000;
public const UInt64 Baselib_MicrosecondsPerMinute = 60000000;
public const UInt64 Baselib_NanosecondsPerMicrosecond = 1000;
public const UInt64 Baselib_NanosecondsPerMillisecond = 1000000;
public const UInt64 Baselib_NanosecondsPerSecond = 1000000000;
public const UInt64 Baselib_NanosecondsPerMinute = 60000000000;
/// <summary>Baselib_Timer_Ticks are guaranteed to be more granular than this constant.</summary>
public const UInt64 Baselib_Timer_MaxNumberOfNanosecondsPerTick = 1000;
/// <summary>Baselib_Timer_Ticks are guaranteed to be less granular than this constant.</summary>
public const double Baselib_Timer_MinNumberOfNanosecondsPerTick = 0.01;
/// <summary>When comparing results of Baselib_Timer_GetHighPrecisionTimerTicks on different threads, timestamps are strictly monotonous with a tolerance of this many nanoseconds.</summary>
public const double Baselib_Timer_HighPrecisionTimerCrossThreadMontotonyTolerance_InNanoseconds = 100;
/// <summary>Defines the conversion ratio from Baselib_Timer_Ticks to nanoseconds as a fraction.</summary>
[StructLayout(LayoutKind.Sequential)]
public struct Baselib_Timer_TickToNanosecondConversionRatio
{
public UInt64 ticksToNanosecondsNumerator;
public UInt64 ticksToNanosecondsDenominator;
}
/// <summary>Returns the conversion ratio between ticks and nanoseconds.</summary>
/// <remarks>
/// The conversion factor is guaranteed to be constant for the entire application for its entire lifetime.
/// However, it may be different on every start of the application.
/// </remarks>
/// <returns>The conversion factor from ticks to nanoseconds as an integer fraction.</returns>
[FreeFunction(IsThreadSafe = true)]
public static extern Baselib_Timer_TickToNanosecondConversionRatio Baselib_Timer_GetTicksToNanosecondsConversionRatio();
/// <summary>Get the current tick count of the high precision timer.</summary>
/// <remarks>
/// Accuracy:
/// It is assumed that the accuracy corresponds to the granularity of Baselib_Timer_Ticks (which is determined by Baselib_Timer_GetTicksToNanosecondsConversionRatio).
/// However, there are no strict guarantees on the accuracy of the timer.
///
/// Monotony:
/// * ATTENTION: On some platforms this clock is suspended during application/device sleep states.
/// * The timer is not susceptible to wall clock time changes by the user.
/// * The timer is strictly monotonous on a thread
/// * When comparing times from different threads, timestamps are strictly monotonous with a tolerance of Baselib_Timer_HighPrecisionTimerCrossThreadMontotonyTolerance_InNanoseconds.
///
/// Known issues:
/// * Some web browsers impose Spectre mitigation which can introduce jitter in this timer.
/// * Some web browsers may have different timelines per thread/webworker if they are not spawned on startup (this is a bug according to newest W3C specification)
/// </remarks>
/// <returns>Current tick value of the high precision timer.</returns>
[FreeFunction(IsThreadSafe = true)]
public static extern UInt64 Baselib_Timer_GetHighPrecisionTimerTicks();
/// <summary>This function will wait for at least the requested amount of time before returning.</summary>
/// <remarks>Unlike some implementations of 'sleep', passing 0 does NOT guarantee a thread yield and may return immediately! Use the corresponding functionality in Baselib_Thread instead.</remarks>
/// <param name="timeInMilliseconds">Time to wait in milliseconds</param>
[FreeFunction(IsThreadSafe = true)]
public static extern void Baselib_Timer_WaitForAtLeast(UInt32 timeInMilliseconds);
/// <summary>Time since application startup in seconds.</summary>
/// <remarks>Disregarding potential rounding errors, all threads are naturally on the same timeline (i.e. time since process start).</remarks>
[FreeFunction(IsThreadSafe = true)]
public static extern double Baselib_Timer_GetTimeSinceStartupInSeconds();
}
}
| UnityCsReference/External/baselib/baselib/CSharp/BindingsUnity/Baselib_Timer.gen.binding.cs/0 | {
"file_path": "UnityCsReference/External/baselib/baselib/CSharp/BindingsUnity/Baselib_Timer.gen.binding.cs",
"repo_id": "UnityCsReference",
"token_count": 1739
} | 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;
namespace UnityEngine.AI;
public partial struct NavMeshLinkInstance
{
[Obsolete("valid has been deprecated. Use NavMesh.IsLinkValid() instead.")]
public bool valid => NavMesh.IsValidLinkHandle(id);
[Obsolete("Remove() has been deprecated. Use NavMesh.RemoveLink() instead.")]
public void Remove()
{
NavMesh.RemoveLinkInternal(id);
}
[Obsolete("owner has been deprecated. Use NavMesh.GetLinkOwner() and NavMesh.SetLinkOwner() instead.")]
public Object owner
{
get => NavMesh.InternalGetLinkOwner(id);
set
{
var ownerID = value != null ? value.GetInstanceID() : 0;
if (!NavMesh.InternalSetLinkOwner(id, ownerID))
Debug.LogError("Cannot set 'owner' on an invalid NavMeshLinkInstance");
}
}
}
| UnityCsReference/Modules/AI/NavMesh/NavMesh.deprecated.cs/0 | {
"file_path": "UnityCsReference/Modules/AI/NavMesh/NavMesh.deprecated.cs",
"repo_id": "UnityCsReference",
"token_count": 359
} | 364 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine.Bindings;
using UnityEngine.Scripting;
namespace UnityEngine.Accessibility;
[NativeHeader("Modules/Accessibility/Native/AccessibilitySettings.h")]
public static partial class AccessibilitySettings
{
/// <summary>
/// Gets the font scale set by the user in the system settings.
/// </summary>
static extern float GetFontScale();
/// <summary>
/// Checks whether or not bold text is enabled in the system settings.
/// </summary>
static extern bool IsBoldTextEnabled();
/// <summary>
/// Checks whether or not closed captioning is enabled in the system
/// settings.
/// </summary>
static extern bool IsClosedCaptioningEnabled();
[RequiredByNativeCode]
static void Internal_OnFontScaleChanged(float newFontScale)
{
AccessibilityManager.QueueNotification(new AccessibilityManager.NotificationContext
{
notification = AccessibilityNotification.FontScaleChanged,
fontScale = newFontScale,
});
}
[RequiredByNativeCode]
static void Internal_OnBoldTextStatusChanged(bool enabled)
{
AccessibilityManager.QueueNotification(new AccessibilityManager.NotificationContext
{
notification = AccessibilityNotification.BoldTextStatusChanged,
isBoldTextEnabled = enabled,
});
}
[RequiredByNativeCode]
static void Internal_OnClosedCaptioningStatusChanged(bool enabled)
{
AccessibilityManager.QueueNotification(new AccessibilityManager.NotificationContext
{
notification = AccessibilityNotification.ClosedCaptioningStatusChanged,
isClosedCaptioningEnabled = enabled,
});
}
}
| UnityCsReference/Modules/Accessibility/Bindings/AccessibilitySettings.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/Accessibility/Bindings/AccessibilitySettings.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 636
} | 365 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.Accessibility
{
/// <summary>
/// Search field used to search items by id, label or role in a accessibility hierarchy tree view.
/// </summary>
internal class TreeViewSearchBar : VisualElement
{
private static readonly string s_UssClassName = "hierarchy-tree-view__search-bar";
private static readonly string s_HiddenElementUssClassName = "hierarchy-tree-view__search-bar__element-hidden";
private static readonly string s_SearchLabelUssClassName = s_UssClassName + "__label";
private static readonly string s_SearchLabelHelpUssClassName = s_UssClassName + "__label-help";
private static readonly string s_SearchFieldUssClassName = s_UssClassName + "__field";
private static readonly string s_SearchButtonUssClassName = s_UssClassName + "__button";
private static readonly string s_SearchPrevButtonUssClassName = s_SearchButtonUssClassName + "-prev";
private static readonly string s_SearchNextButtonUssClassName = s_UssClassName + "-next";
class SearchResultItem
{
public int itemId;
}
[Serializable]
public new class UxmlSerializedData : VisualElement.UxmlSerializedData
{
public override object CreateInstance() => new TreeViewSearchBar();
}
private List<SearchResultItem> m_FoundItems;
private int m_SelectedIndex;
private string m_CurrentQuery;
private TextField m_SearchTextField;
private TreeView m_TreeView;
private Label m_CountLabel;
private Label m_FieldHelpLabel;
private List<VisualElement> m_SearchResultsHightlights;
public string currentQuery => m_CurrentQuery;
/// <summary>
/// The tree view on which search is performed.
/// </summary>
public TreeView treeView
{
get => m_TreeView;
set => m_TreeView = value;
}
/// <summary>
/// Constructor.
/// </summary>
public TreeViewSearchBar()
{
m_FoundItems = new List<SearchResultItem>();
m_SearchResultsHightlights = new List<VisualElement>();
AddToClassList(s_UssClassName);
m_FieldHelpLabel = new Label(L10n.Tr("Search by id, label, role"));
m_FieldHelpLabel.pickingMode = PickingMode.Ignore;
m_FieldHelpLabel.AddToClassList(s_SearchLabelUssClassName);
m_FieldHelpLabel.AddToClassList(s_SearchLabelHelpUssClassName);
Add(m_FieldHelpLabel);
m_SearchTextField = new TextField();
m_SearchTextField.AddToClassList(s_SearchFieldUssClassName);
m_SearchTextField.RegisterValueChangedCallback((e) => PerformSearch());
m_SearchTextField.RegisterCallback<KeyDownEvent>((e) =>
{
var targetField = m_SearchTextField;
if (e.keyCode == KeyCode.F3 || e.keyCode == KeyCode.Return || e.keyCode == KeyCode.KeypadEnter)
{
if (e.modifiers.HasFlag(EventModifiers.Shift))
SelectPrev();
else
SelectNext();
}
else if (e.keyCode == KeyCode.Escape)
{
targetField.value = string.Empty;
ClearSearchResults();
treeView.Focus();
}
}, TrickleDown.TrickleDown);
Add(m_SearchTextField);
m_CountLabel = new Label();
m_CountLabel.AddToClassList(s_SearchLabelUssClassName);
m_CountLabel.AddToClassList(s_HiddenElementUssClassName);
Add(m_CountLabel);
var prevButton = new Button(SelectPrev) {text = "<"};
prevButton.AddToClassList(s_SearchButtonUssClassName);
prevButton.AddToClassList(s_SearchPrevButtonUssClassName);
Add(prevButton);
var nextButton = new Button(SelectNext) {text = ">"};
nextButton.AddToClassList(s_SearchButtonUssClassName);
nextButton.AddToClassList(s_SearchNextButtonUssClassName);
Add(nextButton);
}
private IEnumerable<TreeViewItemData<AccessibilityViewModelNode>> GetAllItems()
{
if (m_TreeView?.viewController == null)
{
yield break;
}
var treeViewController = m_TreeView?.viewController as DefaultTreeViewController<AccessibilityViewModelNode>;
foreach (var itemId in m_TreeView.viewController.GetAllItemIds())
{
yield return treeViewController.GetTreeViewItemDataForId(itemId);
}
}
/// <summary>
/// Clears the text of the search field.
/// </summary>
public void ClearSearch()
{
m_SearchTextField.value = string.Empty;
}
private void SelectNext()
{
if (m_FoundItems.Count == 0)
return;
m_SelectedIndex = (m_SelectedIndex + 1) % m_FoundItems.Count;
SelectElement(m_FoundItems[m_SelectedIndex].itemId, m_CurrentQuery);
m_CountLabel.text = $"{m_SelectedIndex + 1} of {m_FoundItems.Count}";
}
private void SelectPrev()
{
if (m_FoundItems.Count == 0)
return;
var count = m_FoundItems.Count;
m_SelectedIndex--;
m_SelectedIndex = (m_SelectedIndex % count + count) % count;
SelectElement(m_FoundItems[m_SelectedIndex].itemId, m_CurrentQuery);
m_CountLabel.text = $"{m_SelectedIndex + 1} of {m_FoundItems.Count}";
}
/// <summary>
/// Performs a search.
/// </summary>
public void PerformSearch()
{
m_FoundItems.Clear();
m_SelectedIndex = 0;
m_CountLabel.text = string.Empty;
m_CountLabel.AddToClassList(s_HiddenElementUssClassName);
ClearSearchResults();
m_FieldHelpLabel.AddToClassList(s_HiddenElementUssClassName);
m_CurrentQuery = m_SearchTextField.text;
m_TreeView.RefreshItems();
if (string.IsNullOrEmpty(m_CurrentQuery))
{
m_FieldHelpLabel.RemoveFromClassList(s_HiddenElementUssClassName);
return;
}
var items = GetAllItems();
if (items == null)
return;
foreach (var treeItem in items)
{
var element = treeItem.data;
if (element.isRoot)
continue;
var idText = element.id.ToString();
var labelText = AccessibilityHierarchyTreeViewItem.GetDisplayLabelText(element.isActive, element.label);
var roleText = AccessibilityHierarchyTreeViewItem.GetDisplayRoleText(element.role);
if ((idText.IndexOf(m_CurrentQuery, StringComparison.OrdinalIgnoreCase) >= 0)
|| (labelText?.IndexOf(m_CurrentQuery, StringComparison.OrdinalIgnoreCase) >= 0)
|| (roleText.IndexOf(m_CurrentQuery, StringComparison.OrdinalIgnoreCase) >= 0))
{
m_FoundItems.Add(new SearchResultItem() {itemId = treeItem.id});
}
}
if (m_FoundItems.Count == 0)
return;
m_CountLabel.RemoveFromClassList(s_HiddenElementUssClassName);
m_CountLabel.text = $"{m_SelectedIndex + 1} of {m_FoundItems.Count}";
var firstItem = m_FoundItems[0];
SelectElement(firstItem.itemId, m_CurrentQuery);
}
private void ClearSearchResults()
{
foreach (var hl in m_SearchResultsHightlights)
hl.RemoveFromHierarchy();
m_SearchResultsHightlights.Clear();
}
private void SelectElement(int itemId, string query)
{
ClearSearchResults();
var node = m_TreeView.GetItemDataForId<AccessibilityViewModelNode>(itemId);
if (node.isNull || node.isRoot)
return;
m_TreeView.SetSelectionById(itemId);
m_TreeView.ScrollToItemById(itemId);
}
}
}
| UnityCsReference/Modules/AccessibilityEditor/Managed/TreeViewSearchBar.cs/0 | {
"file_path": "UnityCsReference/Modules/AccessibilityEditor/Managed/TreeViewSearchBar.cs",
"repo_id": "UnityCsReference",
"token_count": 4009
} | 366 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine;
using UnityEngine.Animations;
namespace UnityEngine.Playables
{
public static class AnimationPlayableUtilities
{
[Obsolete("This function is no longer used as it overrides the Time Update Mode of the Playable Graph. Refer to the documentation for an example of an equivalent function.")]
static public void Play(Animator animator, Playable playable, PlayableGraph graph)
{
AnimationPlayableOutput playableOutput = AnimationPlayableOutput.Create(graph, "AnimationClip", animator);
playableOutput.SetSourcePlayable(playable, 0);
graph.SyncUpdateAndTimeMode(animator);
graph.Play();
}
static public AnimationClipPlayable PlayClip(Animator animator, AnimationClip clip, out PlayableGraph graph)
{
graph = PlayableGraph.Create();
AnimationPlayableOutput playableOutput = AnimationPlayableOutput.Create(graph, "AnimationClip", animator);
var clipPlayable = AnimationClipPlayable.Create(graph, clip);
playableOutput.SetSourcePlayable(clipPlayable);
graph.SyncUpdateAndTimeMode(animator);
graph.Play();
return clipPlayable;
}
static public AnimationMixerPlayable PlayMixer(Animator animator, int inputCount, out PlayableGraph graph)
{
graph = PlayableGraph.Create();
AnimationPlayableOutput playableOutput = AnimationPlayableOutput.Create(graph, "Mixer", animator);
var mixer = AnimationMixerPlayable.Create(graph, inputCount);
playableOutput.SetSourcePlayable(mixer);
graph.SyncUpdateAndTimeMode(animator);
graph.Play();
return mixer;
}
static public AnimationLayerMixerPlayable PlayLayerMixer(Animator animator, int inputCount, out PlayableGraph graph)
{
graph = PlayableGraph.Create();
AnimationPlayableOutput playableOutput = AnimationPlayableOutput.Create(graph, "Mixer", animator);
var mixer = AnimationLayerMixerPlayable.Create(graph, inputCount);
playableOutput.SetSourcePlayable(mixer);
graph.SyncUpdateAndTimeMode(animator);
graph.Play();
return mixer;
}
static public AnimatorControllerPlayable PlayAnimatorController(Animator animator, RuntimeAnimatorController controller, out PlayableGraph graph)
{
graph = PlayableGraph.Create();
AnimationPlayableOutput playableOutput = AnimationPlayableOutput.Create(graph, "AnimatorControllerPlayable", animator);
var controllerPlayable = AnimatorControllerPlayable.Create(graph, controller);
playableOutput.SetSourcePlayable(controllerPlayable);
graph.SyncUpdateAndTimeMode(animator);
graph.Play();
return controllerPlayable;
}
}
}
| UnityCsReference/Modules/Animation/Managed/AnimationPlayableUtilities.cs/0 | {
"file_path": "UnityCsReference/Modules/Animation/Managed/AnimationPlayableUtilities.cs",
"repo_id": "UnityCsReference",
"token_count": 1154
} | 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 UnityEngine.Bindings;
using UnityEngine.Scripting;
using UnityEngine.Playables;
using UnityObject = UnityEngine.Object;
namespace UnityEngine.Animations
{
[NativeHeader("Modules/Animation/ScriptBindings/AnimationLayerMixerPlayable.bindings.h")]
[NativeHeader("Modules/Animation/Director/AnimationLayerMixerPlayable.h")]
[NativeHeader("Runtime/Director/Core/HPlayable.h")]
[StaticAccessor("AnimationLayerMixerPlayableBindings", StaticAccessorType.DoubleColon)]
[RequiredByNativeCode]
public struct AnimationLayerMixerPlayable : IPlayable, IEquatable<AnimationLayerMixerPlayable>
{
PlayableHandle m_Handle;
static readonly AnimationLayerMixerPlayable m_NullPlayable = new AnimationLayerMixerPlayable(PlayableHandle.Null);
public static AnimationLayerMixerPlayable Null { get { return m_NullPlayable; } }
public static AnimationLayerMixerPlayable Create(PlayableGraph graph, int inputCount = 0)
{
return Create(graph, inputCount,true);
}
public static AnimationLayerMixerPlayable Create(PlayableGraph graph, int inputCount ,bool singleLayerOptimization)
{
var handle = CreateHandle(graph, inputCount);
var mixer = new AnimationLayerMixerPlayable(handle, singleLayerOptimization);
return mixer;
}
private static PlayableHandle CreateHandle(PlayableGraph graph, int inputCount = 0)
{
PlayableHandle handle = PlayableHandle.Null;
if (!CreateHandleInternal(graph, ref handle))
return PlayableHandle.Null;
handle.SetInputCount(inputCount);
return handle;
}
internal AnimationLayerMixerPlayable(PlayableHandle handle, bool singleLayerOptimization = true)
{
if (handle.IsValid())
{
if (!handle.IsPlayableOfType<AnimationLayerMixerPlayable>())
throw new InvalidCastException("Can't set handle: the playable is not an AnimationLayerMixerPlayable.");
SetSingleLayerOptimizationInternal(ref handle, singleLayerOptimization);
}
m_Handle = handle;
}
public PlayableHandle GetHandle()
{
return m_Handle;
}
public static implicit operator Playable(AnimationLayerMixerPlayable playable)
{
return new Playable(playable.GetHandle());
}
public static explicit operator AnimationLayerMixerPlayable(Playable playable)
{
return new AnimationLayerMixerPlayable(playable.GetHandle());
}
public bool Equals(AnimationLayerMixerPlayable other)
{
return GetHandle() == other.GetHandle();
}
public bool IsLayerAdditive(uint layerIndex)
{
if (layerIndex >= m_Handle.GetInputCount())
throw new ArgumentOutOfRangeException("layerIndex", String.Format("layerIndex {0} must be in the range of 0 to {1}.", layerIndex, m_Handle.GetInputCount() - 1));
return IsLayerAdditiveInternal(ref m_Handle, layerIndex);
}
public void SetLayerAdditive(uint layerIndex, bool value)
{
if (layerIndex >= m_Handle.GetInputCount())
throw new ArgumentOutOfRangeException("layerIndex", String.Format("layerIndex {0} must be in the range of 0 to {1}.", layerIndex, m_Handle.GetInputCount() - 1));
SetLayerAdditiveInternal(ref m_Handle, layerIndex, value);
}
public void SetLayerMaskFromAvatarMask(uint layerIndex, AvatarMask mask)
{
if (layerIndex >= m_Handle.GetInputCount())
throw new ArgumentOutOfRangeException("layerIndex", String.Format("layerIndex {0} must be in the range of 0 to {1}.", layerIndex, m_Handle.GetInputCount() - 1));
if (mask == null)
throw new System.ArgumentNullException("mask");
SetLayerMaskFromAvatarMaskInternal(ref m_Handle, layerIndex, mask);
}
[NativeThrows]
extern private static bool CreateHandleInternal(PlayableGraph graph, ref PlayableHandle handle);
[NativeThrows]
extern private static bool IsLayerAdditiveInternal(ref PlayableHandle handle, uint layerIndex);
[NativeThrows]
extern private static void SetLayerAdditiveInternal(ref PlayableHandle handle, uint layerIndex, bool value);
[NativeThrows]
extern private static void SetSingleLayerOptimizationInternal(ref PlayableHandle handle, bool value);
[NativeThrows]
extern private static void SetLayerMaskFromAvatarMaskInternal(ref PlayableHandle handle, uint layerIndex, AvatarMask mask);
}
}
| UnityCsReference/Modules/Animation/ScriptBindings/AnimationLayerMixerPlayable.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/Animation/ScriptBindings/AnimationLayerMixerPlayable.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 1867
} | 368 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine.Bindings;
using UnityEngine.Internal;
using UnityEngine.Scripting.APIUpdating;
using Unity.Jobs;
namespace UnityEngine.Animations
{
[MovedFrom("UnityEngine.Experimental.Animations")]
public enum CustomStreamPropertyType
{
Float = BindType.Float,
Bool = BindType.Bool,
Int = BindType.Int
}
[MovedFrom("UnityEngine.Experimental.Animations")]
[NativeHeader("Modules/Animation/ScriptBindings/AnimatorJobExtensions.bindings.h")]
[NativeHeader("Modules/Animation/Animator.h")]
[NativeHeader("Modules/Animation/Director/AnimationStreamHandles.h")]
[NativeHeader("Modules/Animation/Director/AnimationSceneHandles.h")]
[NativeHeader("Modules/Animation/Director/AnimationStream.h")]
[StaticAccessor("AnimatorJobExtensionsBindings", StaticAccessorType.DoubleColon)]
public static class AnimatorJobExtensions
{
public static void AddJobDependency(this Animator animator, JobHandle jobHandle)
{
InternalAddJobDependency(animator, jobHandle);
}
public static TransformStreamHandle BindStreamTransform(this Animator animator, Transform transform)
{
TransformStreamHandle transformStreamHandle = new TransformStreamHandle();
InternalBindStreamTransform(animator, transform, out transformStreamHandle);
return transformStreamHandle;
}
public static PropertyStreamHandle BindStreamProperty(this Animator animator, Transform transform, Type type, string property)
{
return BindStreamProperty(animator, transform, type, property, false);
}
public static PropertyStreamHandle BindCustomStreamProperty(this Animator animator, string property, CustomStreamPropertyType type)
{
PropertyStreamHandle propertyStreamHandle = new PropertyStreamHandle();
InternalBindCustomStreamProperty(animator, property, type, out propertyStreamHandle);
return propertyStreamHandle;
}
public static PropertyStreamHandle BindStreamProperty(this Animator animator, Transform transform, Type type, string property, [DefaultValue("false")] bool isObjectReference)
{
PropertyStreamHandle propertyStreamHandle = new PropertyStreamHandle();
InternalBindStreamProperty(animator, transform, type, property, isObjectReference, out propertyStreamHandle);
return propertyStreamHandle;
}
public static TransformSceneHandle BindSceneTransform(this Animator animator, Transform transform)
{
TransformSceneHandle transformSceneHandle = new TransformSceneHandle();
InternalBindSceneTransform(animator, transform, out transformSceneHandle);
return transformSceneHandle;
}
public static PropertySceneHandle BindSceneProperty(this Animator animator, Transform transform, Type type, string property)
{
return BindSceneProperty(animator, transform, type, property, false);
}
public static PropertySceneHandle BindSceneProperty(this Animator animator, Transform transform, Type type, string property, [DefaultValue("false")] bool isObjectReference)
{
PropertySceneHandle propertySceneHandle = new PropertySceneHandle();
InternalBindSceneProperty(animator, transform, type, property, isObjectReference, out propertySceneHandle);
return propertySceneHandle;
}
public static bool OpenAnimationStream(this Animator animator, ref AnimationStream stream)
{
return InternalOpenAnimationStream(animator, ref stream);
}
public static void CloseAnimationStream(this Animator animator, ref AnimationStream stream)
{
InternalCloseAnimationStream(animator, ref stream);
}
public static void ResolveAllStreamHandles(this Animator animator)
{
InternalResolveAllStreamHandles(animator);
}
public static void ResolveAllSceneHandles(this Animator animator)
{
InternalResolveAllSceneHandles(animator);
}
internal static void UnbindAllHandles(this Animator animator)
{
InternalUnbindAllStreamHandles(animator);
InternalUnbindAllSceneHandles(animator);
}
public static void UnbindAllStreamHandles(this Animator animator)
{
InternalUnbindAllStreamHandles(animator);
}
public static void UnbindAllSceneHandles(this Animator animator)
{
InternalUnbindAllSceneHandles(animator);
}
extern private static void InternalAddJobDependency([NotNull] Animator animator, JobHandle jobHandle);
extern private static void InternalBindStreamTransform([NotNull] Animator animator, [NotNull] Transform transform, out TransformStreamHandle transformStreamHandle);
extern private static void InternalBindStreamProperty([NotNull] Animator animator, [NotNull] Transform transform, [NotNull] Type type, [NotNull] string property, bool isObjectReference, out PropertyStreamHandle propertyStreamHandle);
extern private static void InternalBindCustomStreamProperty([NotNull] Animator animator, [NotNull] string property, CustomStreamPropertyType propertyType, out PropertyStreamHandle propertyStreamHandle);
extern private static void InternalBindSceneTransform([NotNull] Animator animator, [NotNull] Transform transform, out TransformSceneHandle transformSceneHandle);
extern private static void InternalBindSceneProperty([NotNull] Animator animator, [NotNull] Transform transform, [NotNull] Type type, [NotNull] string property, bool isObjectReference, out PropertySceneHandle propertySceneHandle);
extern private static bool InternalOpenAnimationStream([NotNull] Animator animator, ref AnimationStream stream);
extern private static void InternalCloseAnimationStream([NotNull] Animator animator, ref AnimationStream stream);
extern private static void InternalResolveAllStreamHandles([NotNull] Animator animator);
extern private static void InternalResolveAllSceneHandles([NotNull] Animator animator);
extern private static void InternalUnbindAllStreamHandles([NotNull] Animator animator);
extern private static void InternalUnbindAllSceneHandles([NotNull] Animator animator);
}
}
| UnityCsReference/Modules/Animation/ScriptBindings/AnimatorJobExtensions.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/Animation/ScriptBindings/AnimatorJobExtensions.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 2157
} | 369 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using UnityEngine;
namespace UnityEditor
{
internal partial class ArtifactDifferenceReporter
{
delegate void ArtifactDifferenceMessageFormatter(ref ArtifactInfoDifference diff, List<string> msgsList);
internal enum DiffType
{
None, Modified, Added, Removed
}
internal class ArtifactInfoDifference
{
public readonly string key;
public readonly DiffType diffType;
public readonly ArtifactInfo oldArtifactInfo;
public readonly ArtifactInfo newArtifactInfo;
public string message;
public string categoryKey;
private IDictionary<string, ArtifactInfoDependency> m_OldDependencies;
private IDictionary<string, ArtifactInfoDependency> m_NewDependencies;
internal IDictionary<string, ArtifactInfoDependency> oldDependencies
{
get
{
if(m_OldDependencies == null && oldArtifactInfo != null)
{
m_OldDependencies = oldArtifactInfo.dependencies;
}
return m_OldDependencies;
}
set
{
m_OldDependencies = value;
}
}
internal IDictionary<string, ArtifactInfoDependency> newDependencies
{
get
{
if (m_NewDependencies == null && newArtifactInfo != null)
{
m_NewDependencies = newArtifactInfo.dependencies;
}
return m_NewDependencies;
}
set
{
m_NewDependencies = value;
}
}
internal ArtifactInfoDifference(string key, DiffType diffType, ArtifactInfo oldArtifactInfo, ArtifactInfo newArtifactInfo)
{
this.key = key;
this.diffType = diffType;
this.oldArtifactInfo = oldArtifactInfo;
this.newArtifactInfo = newArtifactInfo;
this.message = "";
}
internal ArtifactInfoDifference(ArtifactInfoDifference other)
{
this.key = other.key;
this.diffType = other.diffType;
this.oldArtifactInfo = other.oldArtifactInfo;
this.newArtifactInfo = other.newArtifactInfo;
this.message = other.message;
}
}
private List<ArtifactInfoDifference> m_AllDiffs;
public static string kGlobal_artifactFormatVersion = "Global/artifactFormatVersion";
public static string kGlobal_allImporterVersion = "Global/allImporterVersion";
public static string kImportParameter_ImporterType = "ImportParameter/ImporterType";
public static string kImporterRegister_ImporterVersion = "ImporterRegistry/ImporterVersion";
public static string kImporterRegistry_PostProcessorVersionHash = "ImporterRegistry/PostProcessorVersionHash";
public static string kImportParameter_NameOfAsset = "ImportParameter/NameOfAsset";
public static string kSourceAsset_GuidOfPathLocation = "SourceAsset/GuidOfPathLocation";
public static string kSourceAsset_HashOfSourceAssetByGUID = "SourceAsset/HashOfSourceAssetByGUID";
public static string kSourceAsset_MetaFileHash = "SourceAsset/MetaFileHash";
public static string kArtifact_HashOfContent = "Artifact/HashOfContent";
public static string kArtifact_HashOfGuidsOfChildren = "SourceAsset/HashOfGuidsOfChildren";
public static string kArtifact_FileIdOfMainObject = "Artifact/Property";
public static string kImportParameter_Platform = "ImportParameter/Platform";
public static string kEnvironment_TextureImportCompression = "Environment/TextureImportCompression";
public static string kEnvironment_ColorSpace = "Environment/ColorSpace";
public static string kEnvironment_GraphicsAPIMask = "Environment/GraphicsAPIMask";
public static string kEnvironment_ScriptingRuntimeVersion = "Environment/ScriptingRuntimeVersion";
public static string kEnvironment_CustomDependency = "Environment/CustomDependency";
public static string kImportParameter_PlatformGroup = "ImportParameter/BuildTargetPlatformGroup";
public static string kIndeterministicImporter = "ImporterRegistry/IndeterministicImporter";
internal IEnumerable<ArtifactInfoDifference> GetAllDifferences()
{
return m_AllDiffs;
}
internal IEnumerable<string> GatherDifferences(ArtifactInfo oldInfo, ArtifactInfo newInfo)
{
IEnumerable<ArtifactInfoDifference> ignoreDifferences = null;
var messages = GatherDifferences(oldInfo, newInfo, ref ignoreDifferences);
return messages;
}
internal IEnumerable<string> GatherDifferences(ArtifactInfo oldInfo, ArtifactInfo newInfo, ref IEnumerable<ArtifactInfoDifference> differences)
{
m_AllDiffs = newInfo.dependencies.Except(oldInfo.dependencies)
.Concat(oldInfo.dependencies.Except(newInfo.dependencies))
.Select(e => e.Key)
.Distinct()
.Select(key =>
{
// Default is modified, since all non-changed dependencies are filtered out
var diffType = DiffType.Modified;
// check if it is a new dependency
if (!oldInfo.dependencies.ContainsKey(key))
diffType = DiffType.Added;
// check if dependency was removed from the asset
if (!newInfo.dependencies.ContainsKey(key))
diffType = DiffType.Removed;
return new ArtifactInfoDifference(key, diffType, oldInfo, newInfo);
}).ToList();
var msgs = new List<string>();
for (int i = 0; i < m_AllDiffs.Count(); ++i)
{
var artifactInfoDiff = m_AllDiffs[i];
foreach (var formatter in getMessageFormatters())
{
// we're invoking all of the formatters if the condition is true
// formatter methods should probably return the value instead of adding it to the list
// in that case we could yield it here
if (artifactInfoDiff.key.StartsWith(formatter.startsWith, StringComparison.Ordinal))
{
formatter.formatterMethod.Invoke(ref artifactInfoDiff, msgs);
artifactInfoDiff.categoryKey = formatter.startsWith;
}
}
}
if (m_AllDiffs.Count() == 0 && newInfo.artifactID != oldInfo.artifactID)
{
var indeterministicImporterDifference = new ArtifactInfoDifference(kIndeterministicImporter, DiffType.Modified, oldInfo, newInfo);
indeterministicImporterDifference.message = "the importer used is non-deterministic, as it has produced a different result even though all the dependencies are the same";
msgs.Add(indeterministicImporterDifference.message);
}
differences = m_AllDiffs;
return msgs;
}
private static IEnumerable<(string startsWith, ArtifactDifferenceMessageFormatter formatterMethod)> getMessageFormatters()
{
yield return (kEnvironment_CustomDependency, EnvironmentCustomDependencyDifference);
yield return (kEnvironment_TextureImportCompression, TextureCompressionModified);
yield return (kEnvironment_ColorSpace, ColorSpaceModified);
yield return (kImportParameter_ImporterType, ImporterTypeModified);
yield return (kImporterRegister_ImporterVersion, ImporterVersionModified);
yield return (kImportParameter_NameOfAsset, NameOfAssetModified);
yield return (kSourceAsset_HashOfSourceAssetByGUID, HashOfSourceAssetModified);
yield return (kSourceAsset_MetaFileHash, MetaFileHashModified);
yield return (kArtifact_HashOfContent, ArtifactHashOfContentDifference);
yield return (kArtifact_HashOfGuidsOfChildren, ArtifactHashOfGuidsOfChildrenContentDifference);
yield return (kImportParameter_Platform, PlatformDependencyModified);
yield return (kSourceAsset_GuidOfPathLocation, GuidOfPathLocationModified);
yield return (kImporterRegistry_PostProcessorVersionHash, PostProcessorVersionHashModified);
yield return (kEnvironment_GraphicsAPIMask, GraphicsAPIMaskModified);
yield return (kEnvironment_ScriptingRuntimeVersion, ScriptingRuntimeVersionModified);
yield return (kGlobal_artifactFormatVersion, GlobalArtifactFormatVersionModified);
yield return (kGlobal_allImporterVersion, GlobalAllImporterVersionModified);
yield return (kArtifact_FileIdOfMainObject, ArtifactFileIdOfMainObjectModified);
yield return (kImportParameter_PlatformGroup, PlatformGroupModified);
}
private static void PlatformGroupModified(ref ArtifactInfoDifference diff, List<string> msgsList)
{
if (diff.diffType == DiffType.Modified)
{
var oldPlatformGroup = diff.oldDependencies[diff.key].value;
var newPlatformGroup = diff.newDependencies[diff.key].value;
diff.message = $"the PlatformGroup value was changed from '{oldPlatformGroup}' to '{newPlatformGroup}'";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Added)
{
var platformGroup = diff.newDependencies[diff.key].value;
var assetName = GetAssetName(diff.newArtifactInfo);
diff.message = $"a dependency on the PlatformGroup '{platformGroup}' was added";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Removed)
{
var platformGroup = diff.oldDependencies[diff.key].value;
var assetName = GetAssetName(diff.newArtifactInfo);
diff.message = $"a dependency on the PlatformGroup '{platformGroup}' was removed";
msgsList.Add(diff.message);
}
}
private static void ArtifactFileIdOfMainObjectModified(ref ArtifactInfoDifference diff, List<string> msgsList)
{
//The propertyName is special, in the sense that
//the key contains both the name (i.e. "Artifact/Property" and a value "SomeProperty")
//so we split it in order to report it in a more legible way
var propertyName = diff.key.Split('/')[2];
if (diff.diffType == DiffType.Modified)
{
var oldVersion = diff.oldDependencies[diff.key].value;
var newVersion = diff.newDependencies[diff.key].value;
var assetName = GetAssetName(diff.newDependencies);
diff.message = $"the property '{propertyName}' was changed from '{oldVersion}' to '{newVersion}', which is registered as a dependency of '{assetName}'";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Added)
{
diff.message = $"a dependency on the property '{propertyName}' was added";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Removed)
{
diff.message = $"a dependency on the property '{propertyName}' was removed";
msgsList.Add(diff.message);
}
}
private static void GlobalAllImporterVersionModified(ref ArtifactInfoDifference diff, List<string> msgsList)
{
if (diff.diffType == DiffType.Modified)
{
var oldVersion = diff.oldDependencies[diff.key].value;
var newVersion = diff.newDependencies[diff.key].value;
diff.message = $"the Global Importer version value was changed from '{oldVersion}' to '{newVersion}'";
msgsList.Add(diff.message);
}
else if(diff.diffType == DiffType.Added)
{
var assetName = GetAssetName(diff.newDependencies);
var addedValue = diff.newDependencies[diff.key].value;
diff.message = $"a dependency on the Global AllImporter Version with value {addedValue} was added to {assetName}";
msgsList.Add(diff.message);
}
else if(diff.diffType == DiffType.Removed)
{
var assetName = GetAssetName(diff.oldDependencies);
diff.message = $"a dependency on the Global AllImporter Version was removed from {assetName}";
msgsList.Add(diff.message);
}
}
private static void GlobalArtifactFormatVersionModified(ref ArtifactInfoDifference diff, List<string> msgsList)
{
if (diff.diffType == DiffType.Modified)
{
var oldVersion = diff.oldDependencies[diff.key].value;
var newVersion = diff.newDependencies[diff.key].value;
diff.message = $"the global artifact format version changed from '{oldVersion}' to '{newVersion}'";
msgsList.Add(diff.message);
}
else if(diff.diffType == DiffType.Added)
{
var assetName = GetAssetName(diff.newDependencies);
var addedValue = diff.newDependencies[diff.key].value;
diff.message = $"a dependency on the Global Artifact Format Version with value {addedValue} was added to {assetName}";
msgsList.Add(diff.message);
}
else if(diff.diffType == DiffType.Removed)
{
var assetName = GetAssetName(diff.oldDependencies);
diff.message = $"a dependency on the Global Artifact Format Version was removed from {assetName}";
msgsList.Add(diff.message);
}
}
private static void ScriptingRuntimeVersionModified(ref ArtifactInfoDifference diff, List<string> msgsList)
{
if (diff.diffType == DiffType.Modified)
{
var oldVersion = diff.oldDependencies[diff.key].value;
var newVersion = diff.newDependencies[diff.key].value;
diff.message = $"the project's ScriptingRuntimeVersion changed from '{oldVersion}' to '{newVersion}";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Added)
{
var addedVersion = diff.newDependencies[diff.key].value;
diff.message = $"a dependency on the selected Scripting Runtime Version '{addedVersion}' was added";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Removed)
{
var removedVersion = diff.oldDependencies[diff.key].value;
diff.message = $"a dependency on the selected Scripting Runtime Version '{removedVersion}' was removed";
msgsList.Add(diff.message);
}
}
private static void GraphicsAPIMaskModified(ref ArtifactInfoDifference diff, List<string> msgsList)
{
//UnityEngine.Rendering.GraphicsDeviceType
if (diff.diffType == DiffType.Modified)
{
var oldGraphicsAPIValue = diff.oldDependencies[diff.key].value;
var newGraphicsAPIValue = diff.newDependencies[diff.key].value;
diff.message = $"the project's GraphicsAPIMask changed from '{oldGraphicsAPIValue}' to '{newGraphicsAPIValue}'";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Added)
{
var assetName = GetAssetName(diff.newDependencies);
var newGraphicsAPIValue = diff.newDependencies[diff.key].value;
diff.message = $"a dependency on the Graphics API '{newGraphicsAPIValue}' was added to '{assetName}'";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Removed)
{
var assetName = GetAssetName(diff.oldDependencies);
var oldGraphicsAPIValue = diff.oldDependencies[diff.key].value;
diff.message = $"the dependency on the Graphics API '{oldGraphicsAPIValue}' was removed from '{assetName}'";
msgsList.Add(diff.message);
}
}
private static void PostProcessorVersionHashModified(ref ArtifactInfoDifference diff, List<string> msgsList)
{
var oldPostProcessorKey = diff.oldDependencies.Keys.FirstOrDefault(key => key.StartsWith(kImporterRegistry_PostProcessorVersionHash, StringComparison.Ordinal));
var newPostProcessorKey = diff.newDependencies.Keys.FirstOrDefault(key => key.StartsWith(kImporterRegistry_PostProcessorVersionHash, StringComparison.Ordinal));
if (!string.IsNullOrEmpty(oldPostProcessorKey) && !string.IsNullOrEmpty(newPostProcessorKey) && oldPostProcessorKey != newPostProcessorKey)
{
var assetName = GetAssetName(diff.newDependencies);
var key = newPostProcessorKey;
var start = key.LastIndexOf("/") + 1;
var newPostProcessorName = key.Substring(start, key.Length - start);
key = oldPostProcessorKey;
start = key.LastIndexOf("/") + 1;
var oldPostProcessorName = key.Substring(start, key.Length - start);
diff.message = $"a PostProcessor associated with '{assetName}' changed from '{oldPostProcessorName}' to '{newPostProcessorName}'";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Modified)
{
var assetName = GetAssetName(diff.newDependencies);
var key = newPostProcessorKey;
var start = key.LastIndexOf("/") + 1;
var postProcessor = key.Substring(start, key.Length - start);
var oldValue = diff.oldDependencies[key].value;
var newValue = diff.newDependencies[key].value;
diff.message = $"the value for the PostProcessor '{postProcessor}' was changed from '{oldValue}' to '{newValue}'";
msgsList.Add(diff.message);
}
else
{
if (diff.diffType == DiffType.Removed)
{
var assetName = GetAssetName(diff.oldDependencies);
var key = oldPostProcessorKey;
var start = key.LastIndexOf("/") + 1;
var postProcessor = key.Substring(start, key.Length - start);
diff.message = $"the PostProcessor '{postProcessor}' associated with '{assetName}' was removed as a dependency";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Added)
{
var assetName = GetAssetName(diff.newDependencies);
var key = newPostProcessorKey;
var start = key.LastIndexOf("/") + 1;
var postProcessor = key.Substring(start, key.Length - start);
diff.message = $"the PostProcessor '{postProcessor}' was added as a dependency for '{assetName}'";
msgsList.Add(diff.message);
}
}
}
private static void GuidOfPathLocationModified(ref ArtifactInfoDifference diff, List<string> msgsList)
{
if (diff.diffType == DiffType.Added)
{
var entry = diff.newDependencies[diff.key];
string guid = entry.value.ToString();
var pathOfDependency = AssetDatabase.GUIDToAssetPath(guid);
var assetName = GetAssetName(diff.newArtifactInfo);
diff.message = $"a dependency on '{pathOfDependency}' was added to '{assetName}'";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Removed)
{
var entry = diff.oldDependencies[diff.key];
string guid = entry.value.ToString();
var pathOfDependency = AssetDatabase.GUIDToAssetPath(guid);
var assetName = GetAssetName(diff.newArtifactInfo);
diff.message = $"a dependency on '{pathOfDependency}' was removed from '{assetName}'";
msgsList.Add(diff.message);
}
}
private static void GuidOfPathLocationModifiedViaHashOfSourceAsset(ref ArtifactInfoDifference diff, List<string> msgsList, string pathOfDependency)
{
if (diff.diffType == DiffType.Modified)
{
var assetName = GetAssetName(diff.newDependencies);
diff.message = $"the asset '{pathOfDependency}' was changed, which is registered as a dependency of '{assetName}'";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Added)
{
var assetName = GetAssetName(diff.newDependencies);
diff.message = $"a dependency on '{pathOfDependency}' was added to '{assetName}'";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Removed)
{
var assetName = diff.oldDependencies[kImportParameter_NameOfAsset].value;
diff.message = $"a dependency on '{pathOfDependency}' was removed from '{assetName}'";
msgsList.Add(diff.message);
}
}
private static void PlatformDependencyModified(ref ArtifactInfoDifference diff, List<string> msgsList)
{
if (diff.diffType == DiffType.Removed)
{
var assetName = GetAssetName(diff.newArtifactInfo);
diff.message = $"the dynamic dependency for the current build target was removed for '{assetName}'";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Added)
{
var assetName = GetAssetName(diff.newArtifactInfo);
diff.message = $"a dynamic dependency which makes '{assetName}' dependent on the current build target was added";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Modified)
{
var oldPlatformValue = diff.oldDependencies[diff.key].value;
var newPlatformValue = diff.newDependencies[diff.key].value;
diff.message = $"the project's build target was changed from '{oldPlatformValue}' to '{newPlatformValue}'";
msgsList.Add(diff.message);
}
}
private static void ImporterVersionModified(ref ArtifactInfoDifference diff, List<string> msgsList)
{
if (diff.diffType == DiffType.Modified)
{
var oldImporterVersion = diff.oldDependencies[diff.key].value;
var newImporterVersion = diff.newDependencies[diff.key].value;
var importerName = diff.newDependencies[kImportParameter_ImporterType].value;
diff.message = $"the version of the importer '{importerName}' changed from '{oldImporterVersion}' to '{newImporterVersion}'";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Added)
{
var newImporterVersion = diff.newDependencies[diff.key].value;
var importerName = diff.newDependencies[kImportParameter_ImporterType].value;
diff.message = $"a dependency on the importer '{importerName}' was added, with version '{newImporterVersion}'";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Removed)
{
var importerName = diff.oldDependencies[kImportParameter_ImporterType].value;
diff.message = $"a dependency on the importer '{importerName}' was removed";
msgsList.Add(diff.message);
}
}
private static void ImporterTypeModified(ref ArtifactInfoDifference diff, List<string> msgsList)
{
var newImporterTypeName = diff.newDependencies[diff.key].value;
var oldImporterTypeName = diff.oldDependencies[diff.key].value;
var assetName = GetAssetName(diff.newArtifactInfo);
diff.message = $"the importer associated with '{assetName}' changed from '{oldImporterTypeName}' now it is '{newImporterTypeName}'";
msgsList.Add(diff.message);
}
// formatter methods below
private static void EnvironmentCustomDependencyDifference(ref ArtifactInfoDifference diff, List<string> msgsList)
{
if (diff.diffType == DiffType.Added)
{
var newCustomDependencyValue = diff.newDependencies[diff.key].value;
var customDependencyName = diff.key.Substring(kEnvironment_CustomDependency.Length + 1);
diff.message = $"the custom dependency '{customDependencyName}' was added with value '{newCustomDependencyValue}'";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Removed)
{
var customDependencyName = diff.key.Substring(kEnvironment_CustomDependency.Length + 1);
diff.message = $"the custom dependency '{customDependencyName}' was removed";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Modified)
{
var oldCustomDependencyValue = diff.oldDependencies[diff.key].value;
var newCustomDependencyValue = diff.newDependencies[diff.key].value;
var customDependencyName = diff.key.Substring(kEnvironment_CustomDependency.Length + 1);
diff.message = $"the value of the custom dependency '{customDependencyName}' was changed from '{oldCustomDependencyValue}' to '{newCustomDependencyValue}'";
msgsList.Add(diff.message);
}
}
private static void ArtifactHashOfContentDifference(ref ArtifactInfoDifference diff, List<string> msgsList)
{
var startIndex = diff.key.IndexOf('(') + 1;
var guid = diff.key.Substring(startIndex, 32);
var path = AssetDatabase.GUIDToAssetPath(guid);
var assetName = GetAssetName(diff.newArtifactInfo);
if (diff.diffType == DiffType.Added)
{
diff.message = $"the asset at '{path}' was added as a dependency of '{assetName}'";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Removed)
{
diff.message = $"the asset at '{path}' was removed as a dependency of '{assetName}'";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Modified)
{
diff.message = $"the asset at '{path}' changed, which is registered as a dependency of '{assetName}'";
msgsList.Add(diff.message);
}
}
private static void ArtifactHashOfGuidsOfChildrenContentDifference(ref ArtifactInfoDifference diff, List<string> msgsList)
{
var startIndex = diff.key.LastIndexOf('/') + 1;
var guid = diff.key.Substring(startIndex, 32);
var folderpath = AssetDatabase.GUIDToAssetPath(guid);
if (diff.diffType == DiffType.Removed)
{
diff.message = $"a dependency on the Hash of all the GUIDs belonging to assets inside of the folder '{folderpath}' was removed";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Added)
{
diff.message = $"a dependency on the Hash of all the GUIDs belonging to assets inside of the folder '{folderpath}' was added";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Modified)
{
var oldHash = diff.oldDependencies[diff.key].value;
var newHash = diff.newDependencies[diff.key].value;
diff.message = $"the Hash of all the GUIDs belonging to assets inside the folder '{folderpath}' changed from '{oldHash}' to '{newHash}'";
msgsList.Add(diff.message);
}
}
private static void TextureCompressionModified(ref ArtifactInfoDifference diff, List<string> msgsList)
{
if (diff.diffType == DiffType.Removed)
{
var assetName = GetAssetName(diff.newDependencies);
diff.message = $"the asset '{assetName}' no longer depends on texture compression";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Added)
{
diff.message = $"a dependency on the project's texture compression was added";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Modified)
{
var oldTextureCompressionSetting = diff.oldDependencies[diff.key].value;
var newTextureCompressionSetting = diff.newDependencies[diff.key].value;
diff.message = $"the project's texture compression setting changed from {oldTextureCompressionSetting} to {newTextureCompressionSetting}";
msgsList.Add(diff.message);
}
}
private static void ColorSpaceModified(ref ArtifactInfoDifference diff, List<string> msgsList)
{
if (diff.diffType == DiffType.Removed)
{
var assetName = GetAssetName(diff.newArtifactInfo);
diff.message = $"the asset '{assetName}' no longer depends color space";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Modified)
{
var oldColorSpace = diff.oldDependencies[diff.key].value;
var newColorSpace = diff.newDependencies[diff.key].value;
diff.message = $"the project's color space changed from {oldColorSpace} to {newColorSpace}";
msgsList.Add(diff.message);
}
}
private static void NameOfAssetModified(ref ArtifactInfoDifference diff, List<string> msgsList)
{
var oldName = diff.oldDependencies[diff.key].value;
var newName = diff.newDependencies[diff.key].value;
diff.message = $"the name of the asset was changed from '{oldName}' to '{newName}'";
msgsList.Add(diff.message);
}
private static void HashOfSourceAssetModified(ref ArtifactInfoDifference diff, List<string> msgs)
{
//This means that a source asset that this asset depends on was modified, so we need to do some extra work
//to get the name out
if (ContainsGuidOfPathLocationChange(ref diff, out var pathOfDependency))
{
GuidOfPathLocationModifiedViaHashOfSourceAsset(ref diff, msgs, pathOfDependency);
return;
}
var startIndex = diff.key.IndexOf('(') + 1;
var guid = diff.key.Substring(startIndex, 32);
diff.message = $"the source asset was changed";
msgs.Add(diff.message);
}
private static bool ContainsGuidOfPathLocationChange(ref ArtifactInfoDifference diff, out string pathOfDependency)
{
pathOfDependency = string.Empty;
var startIndex = diff.key.LastIndexOf('/') + 1;
if (startIndex < 0)
return false;
var guid = diff.key.Substring(startIndex, 32);
pathOfDependency = AssetDatabase.GUIDToAssetPath(guid);
if (string.IsNullOrEmpty(pathOfDependency))
return false;
//lowercase and replace slashes
var goodPath = pathOfDependency.ToLower(CultureInfo.InvariantCulture);
goodPath = goodPath.Replace("\\", "/");
goodPath = goodPath.Replace("//", "/");
var guidOfPathLocationKey = $"{kSourceAsset_GuidOfPathLocation}/{goodPath}";
return diff.oldDependencies.ContainsKey(guidOfPathLocationKey);
}
private static void MetaFileHashModified(ref ArtifactInfoDifference diff, List<string> msgsList)
{
var startIndex = diff.key.LastIndexOf('/') + 1;
var guid = diff.key.Substring(startIndex, 32);
var path = AssetDatabase.GUIDToAssetPath(guid);
if (diff.diffType == DiffType.Added)
{
diff.message = $"a dependency on the .meta file '{path}.meta' was added";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Removed)
{
diff.message = $"a dependency on the .meta file '{path}.meta' was removed";
msgsList.Add(diff.message);
}
else if (diff.diffType == DiffType.Modified)
{
diff.message = $"the .meta file '{path}.meta' was changed";
msgsList.Add(diff.message);
}
}
private static string GetAssetName(ArtifactInfo artifactInfo)
{
var assetName = artifactInfo.dependencies[kImportParameter_NameOfAsset].value.ToString();
return assetName;
}
private static string GetAssetName(IDictionary<string, ArtifactInfoDependency> dependencies)
{
var assetName = dependencies[kImportParameter_NameOfAsset].value.ToString();
return assetName;
}
}
}
| UnityCsReference/Modules/AssetDatabase/Editor/V2/Managed/ArtifactDifferenceReporter.cs/0 | {
"file_path": "UnityCsReference/Modules/AssetDatabase/Editor/V2/Managed/ArtifactDifferenceReporter.cs",
"repo_id": "UnityCsReference",
"token_count": 15791
} | 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.IO;
using System.Linq;
using UnityEngine;
namespace UnityEditor
{
[CustomEditor(typeof(ModelImporter))]
[CanEditMultipleObjects]
internal class ModelImporterEditor : AssetImporterTabbedEditor
{
static string s_LocalizedTitle = L10n.Tr("Model Import Settings");
static string s_C4DDeprecationWarning = L10n.Tr("Starting with the Unity 2019.3 release, direct import of Cinema4D files will require an external plugin. Keep an eye on our External Tools forum for updates.\n\nPlease note that FBX files exported from Cinema4D will still be supported.");
public override void OnInspectorGUI()
{
if (targets.Any(t => t != null && Path.GetExtension(((AssetImporter)t).assetPath).Equals(".c4d", StringComparison.OrdinalIgnoreCase)))
EditorGUILayout.HelpBox(s_C4DDeprecationWarning, MessageType.Warning);
base.OnInspectorGUI();
}
// The modelimporterclipeditor is drawing its own preview for clips to be editable.
protected override bool useAssetDrawPreview => !(activeTab is ModelImporterClipEditor);
public override void OnEnable()
{
if (tabs == null)
{
tabs = new BaseAssetImporterTabUI[] { new ModelImporterModelEditor(this), new ModelImporterRigEditor(this), new ModelImporterClipEditor(this), new ModelImporterMaterialEditor(this) };
m_TabNames = new string[] {"Model", "Rig", "Animation", "Materials"};
}
base.OnEnable();
}
public override void OnDisable()
{
foreach (var tab in tabs)
{
tab.OnDisable();
}
base.OnDisable();
}
//None of the ModelImporter sub editors support multi preview
public override bool HasPreviewGUI()
{
return base.HasPreviewGUI() && targets.Length < 2;
}
public override GUIContent GetPreviewTitle()
{
var tab = activeTab as ModelImporterClipEditor;
if (tab != null)
return new GUIContent(tab.selectedClipName);
return base.GetPreviewTitle();
}
protected override void Apply()
{
base.Apply();
// This is necessary to enforce redrawing the static preview icons in the project browser,
// because some settings may have changed the preview completely.
foreach (ProjectBrowser pb in ProjectBrowser.GetAllProjectBrowsers())
pb.Repaint();
}
// Only show the imported GameObject when the Model tab is active; not when the Animation tab is active
public override bool showImportedObject { get { return activeTab is ModelImporterModelEditor; } }
internal override string targetTitle
{
get
{
if (assetTargets == null || assetTargets.Length == 1 || !m_AllowMultiObjectAccess)
return base.targetTitle;
else
return assetTargets.Length + " " + s_LocalizedTitle;
}
}
}
}
| UnityCsReference/Modules/AssetPipelineEditor/ImportSettings/ModelImporterEditor.cs/0 | {
"file_path": "UnityCsReference/Modules/AssetPipelineEditor/ImportSettings/ModelImporterEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 1372
} | 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.IO;
using UnityEditor.Utils;
using UnityEngine;
using UnityEngine.Bindings;
namespace UnityEditor
{
[NativeHeader("Editor/Src/ScriptCompilation/RoslynAnalyzerConfig.h")]
[ExcludeFromPreset]
internal sealed class RoslynAnalyzerConfigFiles
{
[FreeFunction] internal static extern string[] GetAllAnalyzerConfigs();
[FreeFunction("GetAnalyzerConfigRootFolder")] internal static extern string ConfigForRootFolder(string assemblyName);
[FreeFunction] internal static extern string GetAnalyzerConfigForAssembly(string assemblyPath);
internal static string GetAnalyzerConfigRootFolder(string assemblyName)
{
var ret = ConfigForRootFolder(assemblyName);
return ret;
}
}
}
| UnityCsReference/Modules/AssetPipelineEditor/Public/RoslynAnalyzerConfig.binding.cs/0 | {
"file_path": "UnityCsReference/Modules/AssetPipelineEditor/Public/RoslynAnalyzerConfig.binding.cs",
"repo_id": "UnityCsReference",
"token_count": 311
} | 372 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine;
using UnityEngine.Bindings;
using UnityEngine.Playables;
namespace UnityEngine.Audio
{
[NativeHeader("Modules/Audio/Public/ScriptBindings/AudioPlayableGraphExtensions.bindings.h")]
[NativeHeader("Runtime/Director/Core/HPlayableOutput.h")]
[StaticAccessor("AudioPlayableGraphExtensionsBindings", StaticAccessorType.DoubleColon)]
internal static class AudioPlayableGraphExtensions
{
[NativeThrows]
extern internal static bool InternalCreateAudioOutput(ref PlayableGraph graph, string name, out PlayableOutputHandle handle);
}
}
| UnityCsReference/Modules/Audio/Public/ScriptBindings/AudioPlayableGraphExtensions.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/Audio/Public/ScriptBindings/AudioPlayableGraphExtensions.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 234
} | 373 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.ObjectModel;
using System.Runtime.InteropServices;
using UnityEngine.Bindings;
using UnityEngine.Scripting;
namespace UnityEditor.Build.Content
{
[Serializable]
[UsedByNativeCode]
[StructLayout(LayoutKind.Sequential)]
public struct GameManagerDependencyInfo
{
[NativeName("managerObjects")]
internal ObjectIdentifier[] m_ManagerObjects;
public ReadOnlyCollection<ObjectIdentifier> managerObjects { get { return Array.AsReadOnly(m_ManagerObjects); } }
[NativeName("referencedObjects")]
internal ObjectIdentifier[] m_ReferencedObjects;
public ReadOnlyCollection<ObjectIdentifier> referencedObjects { get { return Array.AsReadOnly(m_ReferencedObjects); } }
[NativeName("includedTypes")]
internal Type[] m_IncludedTypes;
public ReadOnlyCollection<Type> includedTypes { get { return Array.AsReadOnly(m_IncludedTypes); } }
}
}
| UnityCsReference/Modules/BuildPipeline/Editor/Managed/GameManagerDependencyInfo.cs/0 | {
"file_path": "UnityCsReference/Modules/BuildPipeline/Editor/Managed/GameManagerDependencyInfo.cs",
"repo_id": "UnityCsReference",
"token_count": 376
} | 374 |
// 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.Build.Profile.Elements
{
/// <summary>
/// List item showing a build profile name and icon in the <see cref="BuildProfileWindow"/>
/// classic platform or build profile columns.
/// </summary>
internal class BuildProfileListLabel : VisualElement
{
readonly Image m_Icon;
protected virtual string k_Uxml => "BuildProfile/UXML/BuildProfileLabelElement.uxml";
protected readonly Label m_Text;
protected readonly Label m_ActiveIndicator;
internal BuildProfileListLabel()
{
var uxml = EditorGUIUtility.LoadRequired(k_Uxml) as VisualTreeAsset;
var stylesheet = EditorGUIUtility.LoadRequired(Util.k_StyleSheet) as StyleSheet;
styleSheets.Add(stylesheet);
uxml.CloneTree(this);
m_Icon = this.Q<Image>();
m_Text = this.Q<Label>("profile-list-label-name");
m_ActiveIndicator = this.Q<Label>("profile-list-label-active");
m_ActiveIndicator.text = TrText.active;
SetActiveIndicator(false);
}
internal void Set(string displayName, Texture2D icon)
{
m_Icon.image = icon;
m_Text.text = displayName;
}
internal void SetActiveIndicator(bool active)
{
if (active)
m_ActiveIndicator.Show();
else
m_ActiveIndicator.Hide();
}
}
}
| UnityCsReference/Modules/BuildProfileEditor/Elements/BuildProfileListLabel.cs/0 | {
"file_path": "UnityCsReference/Modules/BuildProfileEditor/Elements/BuildProfileListLabel.cs",
"repo_id": "UnityCsReference",
"token_count": 702
} | 375 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine.Bindings;
namespace UnityEditor.Build.Reporting
{
[NativeType(Header = "Modules/BuildReportingEditor/Managed/BuildSummary.bindings.h", CodegenOptions = CodegenOptions.Custom)]
public struct BuildSummary
{
internal Int64 buildStartTimeTicks;
public DateTime buildStartedAt { get { return new DateTime(buildStartTimeTicks); } }
[NativeName("buildGUID")]
public GUID guid { get; }
public BuildTarget platform { get; }
public BuildTargetGroup platformGroup { get; }
internal int subtarget { get; }
public BuildOptions options { get; }
internal BuildAssetBundleOptions assetBundleOptions { get; }
public string outputPath { get; }
internal uint crc { get; }
public ulong totalSize { get; }
internal UInt64 totalTimeTicks;
public TimeSpan totalTime { get { return new TimeSpan((long)totalTimeTicks); } }
public DateTime buildEndedAt { get { return buildStartedAt + totalTime; } }
public int totalErrors { get; }
public int totalWarnings { get; }
[NativeName("buildResult")]
public BuildResult result { get; }
internal BuildType buildType { get; }
public bool multiProcessEnabled { get; }
private T ParseSubtarget<T, S>() where T : Enum where S : Enum
{
if (typeof(T) != typeof(S))
throw new ArgumentException($"Subtarget type ({typeof(T).ToString()}) is not valid for the platform ({platform}). Expected: {typeof(S).ToString()}");
if (!Enum.IsDefined(typeof(T), subtarget))
throw new InvalidOperationException($"The subtarget value ({subtarget}) is not a valid {typeof(T).ToString()}");
return (T)(object)subtarget;
}
public T GetSubtarget<T>() where T : Enum
{
switch (platform)
{
// ADD_NEW_PLATFORM_HERE
case BuildTarget.StandaloneWindows:
case BuildTarget.StandaloneWindows64:
case BuildTarget.StandaloneOSX:
case BuildTarget.StandaloneLinux64:
return ParseSubtarget<T, StandaloneBuildSubtarget>();
case BuildTarget.PS4:
return ParseSubtarget<T, PS4BuildSubtarget>();
case BuildTarget.XboxOne:
return ParseSubtarget<T, XboxBuildSubtarget>();
default:
throw new ArgumentException($"Subtarget property is not available for the platform ({platform})");
}
}
}
}
| UnityCsReference/Modules/BuildReportingEditor/Managed/BuildSummary.cs/0 | {
"file_path": "UnityCsReference/Modules/BuildReportingEditor/Managed/BuildSummary.cs",
"repo_id": "UnityCsReference",
"token_count": 1173
} | 376 |
// 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.Purchasing
{
[NativeHeader("Modules/UnityConnect/UnityPurchasing/UnityPurchasingSettings.h")]
[StaticAccessor("GetUnityPurchasingSettings()", StaticAccessorType.Dot)]
public static partial class PurchasingSettings
{
public static extern bool enabled
{
[ThreadSafe] get;
[ThreadSafe] set;
}
internal static extern bool enabledForPlatform { get; }
internal static extern void ApplyEnableSettings(BuildTarget target);
internal static extern void SetEnabledServiceWindow(bool enabled);
}
}
| UnityCsReference/Modules/CloudServicesSettingsEditor/Purchasing/ScriptBindings/PurchasingSettings.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/CloudServicesSettingsEditor/Purchasing/ScriptBindings/PurchasingSettings.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 277
} | 377 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.IO;
using UnityEngine;
using UnityEngine.Rendering;
namespace UnityEditor.DeviceSimulation
{
[Serializable]
internal class DeviceInfo
{
public string friendlyName;
public int version;
public ScreenData[] screens;
public SystemInfoData systemInfo;
public override string ToString()
{
return friendlyName;
}
public bool IsAndroidDevice()
{
return IsGivenDevice("android");
}
public bool IsiOSDevice()
{
return IsGivenDevice("ios");
}
internal bool IsMobileDevice()
{
return IsAndroidDevice() || IsiOSDevice();
}
internal bool IsConsoleDevice()
{
return false; // Return false for now, should revisit when adding console devices.
}
private bool IsGivenDevice(string os)
{
return systemInfo?.operatingSystem.ToLower().Contains(os) ?? false;
}
}
[Serializable]
internal class ScreenPresentation
{
public string name;
public string overlayPath;
public Vector4 borderSize;
public float cornerRadius;
}
[Serializable]
internal class ScreenData
{
public int width;
public int height;
public int navigationBarHeight;
public float dpi;
public OrientationData[] orientations;
public ScreenPresentation presentation;
}
[Serializable]
internal class OrientationData
{
public ScreenOrientation orientation;
public Rect safeArea;
public Rect[] cutouts;
}
[Serializable]
internal class SystemInfoData
{
public string deviceModel;
public DeviceType deviceType;
public string operatingSystem;
public OperatingSystemFamily operatingSystemFamily;
public int processorCount;
public int processorFrequency;
public string processorType;
public string processorModel;
public string processorManufacturer;
public bool supportsAccelerometer;
public bool supportsAudio;
public bool supportsGyroscope;
public bool supportsLocationService;
public bool supportsVibration;
public int systemMemorySize;
public GraphicsSystemInfoData[] graphicsDependentData;
}
[Serializable]
internal class GraphicsSystemInfoData
{
public GraphicsDeviceType graphicsDeviceType;
public int graphicsMemorySize;
public string graphicsDeviceName;
public string graphicsDeviceVendor;
public int graphicsDeviceID;
public int graphicsDeviceVendorID;
public bool graphicsUVStartsAtTop;
public string graphicsDeviceVersion;
public int graphicsShaderLevel;
public bool graphicsMultiThreaded;
public RenderingThreadingMode renderingThreadingMode;
public FoveatedRenderingCaps foveatedRenderingCaps;
public bool hasHiddenSurfaceRemovalOnGPU;
public bool hasDynamicUniformArrayIndexingInFragmentShaders;
public bool supportsShadows;
public bool supportsRawShadowDepthSampling;
public bool supportsMotionVectors;
public bool supports3DTextures;
public bool supports2DArrayTextures;
public bool supports3DRenderTextures;
public bool supportsCubemapArrayTextures;
public CopyTextureSupport copyTextureSupport;
public bool supportsComputeShaders;
public bool supportsGeometryShaders;
public bool supportsTessellationShaders;
public bool supportsInstancing;
public bool supportsHardwareQuadTopology;
public bool supports32bitsIndexBuffer;
public bool supportsSparseTextures;
public int supportedRenderTargetCount;
public bool supportsSeparatedRenderTargetsBlend;
public int supportedRandomWriteTargetCount;
public int supportsMultisampledTextures;
public bool supportsMultisampleAutoResolve;
public int supportsTextureWrapMirrorOnce;
public bool usesReversedZBuffer;
public NPOTSupport npotSupport;
public int maxTextureSize;
public int maxCubemapSize;
public int maxComputeBufferInputsVertex;
public int maxComputeBufferInputsFragment;
public int maxComputeBufferInputsGeometry;
public int maxComputeBufferInputsDomain;
public int maxComputeBufferInputsHull;
public int maxComputeBufferInputsCompute;
public int maxComputeWorkGroupSize;
public int maxComputeWorkGroupSizeX;
public int maxComputeWorkGroupSizeY;
public int maxComputeWorkGroupSizeZ;
public bool supportsAsyncCompute;
public bool supportsGraphicsFence;
public bool supportsAsyncGPUReadback;
public bool supportsRayTracing;
public bool supportsRayTracingShaders;
public bool supportsInlineRayTracing;
public bool supportsIndirectDispatchRays;
public bool supportsSetConstantBuffer;
public bool hasMipMaxLevel;
public bool supportsMipStreaming;
public bool usesLoadStoreActions;
}
}
| UnityCsReference/Modules/DeviceSimulatorEditor/DeviceInfo/DeviceInfo.cs/0 | {
"file_path": "UnityCsReference/Modules/DeviceSimulatorEditor/DeviceInfo/DeviceInfo.cs",
"repo_id": "UnityCsReference",
"token_count": 2037
} | 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 UnityEngine;
using UnityEngine.Bindings;
using UnityEngine.Scripting;
using UnityEngine.Playables;
namespace UnityEngine.Playables
{
[NativeHeader("Modules/Director/PlayableDirector.h")]
[NativeHeader("Runtime/Mono/MonoBehaviour.h")]
[RequiredByNativeCode]
public partial class PlayableDirector : Behaviour, IExposedPropertyTable
{
public PlayState state
{
get { return GetPlayState(); }
}
public DirectorWrapMode extrapolationMode
{
set { SetWrapMode(value); }
get { return GetWrapMode(); }
}
public PlayableAsset playableAsset
{
get { return Internal_GetPlayableAsset() as PlayableAsset; }
set { SetPlayableAsset(value as ScriptableObject); }
}
public PlayableGraph playableGraph
{
get { return GetGraphHandle(); }
}
public bool playOnAwake
{
get { return GetPlayOnAwake(); }
set { SetPlayOnAwake(value); }
}
public void DeferredEvaluate()
{
EvaluateNextFrame();
}
internal void Play(FrameRate frameRate) => PlayOnFrame(frameRate);
public void Play(PlayableAsset asset)
{
if (asset == null)
throw new ArgumentNullException("asset");
Play(asset, extrapolationMode);
}
public void Play(PlayableAsset asset, DirectorWrapMode mode)
{
if (asset == null)
throw new ArgumentNullException("asset");
playableAsset = asset;
extrapolationMode = mode;
Play();
}
public void SetGenericBinding(Object key, Object value)
{
Internal_SetGenericBinding(key, value);
}
// Bindings properties.
extern public DirectorUpdateMode timeUpdateMode { set; get; }
extern public double time { set; get; }
extern public double initialTime { set; get; }
extern public double duration { get; }
// Bindings methods.
[NativeThrows]
extern public void Evaluate();
[NativeThrows]
extern private void PlayOnFrame(FrameRate frameRate);
[NativeThrows]
extern public void Play();
extern public void Stop();
extern public void Pause();
extern public void Resume();
[NativeThrows]
extern public void RebuildGraph();
extern public void ClearReferenceValue(PropertyName id);
extern public void SetReferenceValue(PropertyName id, UnityEngine.Object value);
extern public UnityEngine.Object GetReferenceValue(PropertyName id, out bool idValid);
[NativeMethod("GetBindingFor")]
extern public Object GetGenericBinding(Object key);
[NativeMethod("ClearBindingFor")]
extern public void ClearGenericBinding(Object key);
[NativeThrows]
extern public void RebindPlayableGraphOutputs();
extern internal void ProcessPendingGraphChanges();
[NativeMethod("HasBinding")]
extern internal bool HasGenericBinding(Object key);
extern private PlayState GetPlayState();
extern private void SetWrapMode(DirectorWrapMode mode);
extern private DirectorWrapMode GetWrapMode();
[NativeThrows]
extern private void EvaluateNextFrame();
extern private PlayableGraph GetGraphHandle();
extern private void SetPlayOnAwake(bool on);
extern private bool GetPlayOnAwake();
[NativeThrows]
extern private void Internal_SetGenericBinding(Object key, Object value);
extern private void SetPlayableAsset(ScriptableObject asset);
extern private ScriptableObject Internal_GetPlayableAsset();
//Delegates
public event Action<PlayableDirector> played;
public event Action<PlayableDirector> paused;
public event Action<PlayableDirector> stopped;
//internal director manager api;
[NativeHeader("Runtime/Director/Core/DirectorManager.h")]
[StaticAccessor("GetDirectorManager()", StaticAccessorType.Dot)]
internal extern static void ResetFrameTiming();
[RequiredByNativeCode]
void SendOnPlayableDirectorPlay()
{
if (played != null)
played(this);
}
[RequiredByNativeCode]
void SendOnPlayableDirectorPause()
{
if (paused != null)
paused(this);
}
[RequiredByNativeCode]
void SendOnPlayableDirectorStop()
{
if (stopped != null)
stopped(this);
}
}
}
| UnityCsReference/Modules/Director/ScriptBindings/PlayableDirector.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/Director/ScriptBindings/PlayableDirector.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 2025
} | 379 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine.UIElements;
namespace UnityEditor.Toolbars
{
[EditorToolbarElement("Editor Utility/Layers", typeof(DefaultMainToolbar))]
sealed class LayersDropdown : EditorToolbarDropdown
{
public LayersDropdown()
{
name = "LayersDropdown";
tooltip = L10n.Tr("Which layers are visible in the Scene views");
text = L10n.Tr("Layers");
clicked += () => LayerVisibilityWindow.ShowAtPosition(worldBound);
RegisterCallback<AttachToPanelEvent>(OnAttachedToPanel);
RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel);
EditorApplication.delayCall += CheckAvailability; //Immediately after a domain reload, calling check availability sometimes returns the wrong value
}
void OnAttachedToPanel(AttachToPanelEvent evt)
{
ModeService.modeChanged += OnModeChanged;
}
void OnDetachFromPanel(DetachFromPanelEvent evt)
{
ModeService.modeChanged -= OnModeChanged;
}
void OnModeChanged(ModeService.ModeChangedArgs args)
{
CheckAvailability();
}
void CheckAvailability()
{
style.display = ModeService.HasCapability(ModeCapability.Layers, true) ? DisplayStyle.Flex : DisplayStyle.None;
}
}
}
| UnityCsReference/Modules/EditorToolbar/ToolbarElements/LayersDropdown.cs/0 | {
"file_path": "UnityCsReference/Modules/EditorToolbar/ToolbarElements/LayersDropdown.cs",
"repo_id": "UnityCsReference",
"token_count": 593
} | 380 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.Experimental.GraphView
{
public class GridBackground : ImmediateModeElement
{
static CustomStyleProperty<float> s_SpacingProperty = new CustomStyleProperty<float>("--spacing");
static CustomStyleProperty<int> s_ThickLinesProperty = new CustomStyleProperty<int>("--thick-lines");
static CustomStyleProperty<Color> s_LineColorProperty = new CustomStyleProperty<Color>("--line-color");
static CustomStyleProperty<Color> s_ThickLineColorProperty = new CustomStyleProperty<Color>("--thick-line-color");
static CustomStyleProperty<Color> s_GridBackgroundColorProperty = new CustomStyleProperty<Color>("--grid-background-color");
static readonly float s_DefaultSpacing = 50f;
static readonly int s_DefaultThickLines = 10;
static readonly Color s_DefaultLineColor = new Color(0f, 0f, 0f, 0.18f);
static readonly Color s_DefaultThickLineColor = new Color(0f, 0f, 0f, 0.38f);
static readonly Color s_DefaultGridBackgroundColor = new Color(0.17f, 0.17f, 0.17f, 1.0f);
float m_Spacing = s_DefaultSpacing;
private float spacing => m_Spacing;
int m_ThickLines = s_DefaultThickLines;
private int thickLines => m_ThickLines;
Color m_LineColor = s_DefaultLineColor;
private Color lineColor => m_LineColor * playModeTintColor;
Color m_ThickLineColor = s_DefaultThickLineColor;
private Color thickLineColor => m_ThickLineColor * playModeTintColor;
Color m_GridBackgroundColor = s_DefaultGridBackgroundColor;
private Color gridBackgroundColor => m_GridBackgroundColor * playModeTintColor;
private VisualElement m_Container;
public GridBackground()
{
pickingMode = PickingMode.Ignore;
this.StretchToParentSize();
RegisterCallback<CustomStyleResolvedEvent>(OnCustomStyleResolved);
}
private Vector3 Clip(Rect clipRect, Vector3 _in)
{
if (_in.x < clipRect.xMin)
_in.x = clipRect.xMin;
if (_in.x > clipRect.xMax)
_in.x = clipRect.xMax;
if (_in.y < clipRect.yMin)
_in.y = clipRect.yMin;
if (_in.y > clipRect.yMax)
_in.y = clipRect.yMax;
return _in;
}
private void OnCustomStyleResolved(CustomStyleResolvedEvent e)
{
float spacingValue = 0f;
int thicklinesValue = 0;
Color thicklineColorValue = Color.clear;
Color lineColorValue = Color.clear;
Color gridColorValue = Color.clear;
ICustomStyle customStyle = e.customStyle;
if (customStyle.TryGetValue(s_SpacingProperty, out spacingValue))
m_Spacing = spacingValue;
if (customStyle.TryGetValue(s_ThickLinesProperty, out thicklinesValue))
m_ThickLines = thickLines;
if (customStyle.TryGetValue(s_ThickLineColorProperty, out thicklineColorValue))
m_ThickLineColor = thicklineColorValue;
if (customStyle.TryGetValue(s_LineColorProperty, out lineColorValue))
m_LineColor = lineColorValue;
if (customStyle.TryGetValue(s_GridBackgroundColorProperty, out gridColorValue))
m_GridBackgroundColor = gridColorValue;
}
protected override void ImmediateRepaint()
{
VisualElement target = parent;
var graphView = target as GraphView;
if (graphView == null)
{
throw new InvalidOperationException("GridBackground can only be added to a GraphView");
}
m_Container = graphView.contentViewContainer;
Rect clientRect = graphView.layout;
// Since we're always stretch to parent size, we will use (0,0) as (x,y) coordinates
clientRect.x = 0;
clientRect.y = 0;
var containerScale = new Vector3(m_Container.transform.matrix.GetColumn(0).magnitude,
m_Container.transform.matrix.GetColumn(1).magnitude,
m_Container.transform.matrix.GetColumn(2).magnitude);
var containerTranslation = m_Container.transform.matrix.GetColumn(3);
var containerPosition = m_Container.layout;
// background
HandleUtility.ApplyWireMaterial();
GL.Begin(GL.QUADS);
GL.Color(gridBackgroundColor);
GL.Vertex(new Vector3(clientRect.x, clientRect.y));
GL.Vertex(new Vector3(clientRect.xMax, clientRect.y));
GL.Vertex(new Vector3(clientRect.xMax, clientRect.yMax));
GL.Vertex(new Vector3(clientRect.x, clientRect.yMax));
GL.End();
// vertical lines
Vector3 from = new Vector3(clientRect.x, clientRect.y, 0.0f);
Vector3 to = new Vector3(clientRect.x, clientRect.height, 0.0f);
var tx = Matrix4x4.TRS(containerTranslation, Quaternion.identity, Vector3.one);
from = tx.MultiplyPoint(from);
to = tx.MultiplyPoint(to);
from.x += (containerPosition.x * containerScale.x);
from.y += (containerPosition.y * containerScale.y);
to.x += (containerPosition.x * containerScale.x);
to.y += (containerPosition.y * containerScale.y);
float thickGridLineX = from.x;
float thickGridLineY = from.y;
// Update from/to to start at beginning of clientRect
from.x = (from.x % (spacing * (containerScale.x)) - (spacing * (containerScale.x)));
to.x = from.x;
from.y = clientRect.y;
to.y = clientRect.y + clientRect.height;
while (from.x < clientRect.width)
{
from.x += spacing * containerScale.x;
to.x += spacing * containerScale.x;
GL.Begin(GL.LINES);
GL.Color(lineColor);
GL.Vertex(Clip(clientRect, from));
GL.Vertex(Clip(clientRect, to));
GL.End();
}
float thickLineSpacing = (spacing * thickLines);
from.x = to.x = (thickGridLineX % (thickLineSpacing * (containerScale.x)) - (thickLineSpacing * (containerScale.x)));
while (from.x < clientRect.width + thickLineSpacing)
{
GL.Begin(GL.LINES);
GL.Color(thickLineColor);
GL.Vertex(Clip(clientRect, from));
GL.Vertex(Clip(clientRect, to));
GL.End();
from.x += (spacing * containerScale.x * thickLines);
to.x += (spacing * containerScale.x * thickLines);
}
// horizontal lines
from = new Vector3(clientRect.x, clientRect.y, 0.0f);
to = new Vector3(clientRect.x + clientRect.width, clientRect.y, 0.0f);
from.x += (containerPosition.x * containerScale.x);
from.y += (containerPosition.y * containerScale.y);
to.x += (containerPosition.x * containerScale.x);
to.y += (containerPosition.y * containerScale.y);
from = tx.MultiplyPoint(from);
to = tx.MultiplyPoint(to);
from.y = to.y = (from.y % (spacing * (containerScale.y)) - (spacing * (containerScale.y)));
from.x = clientRect.x;
to.x = clientRect.width;
while (from.y < clientRect.height)
{
from.y += spacing * containerScale.y;
to.y += spacing * containerScale.y;
GL.Begin(GL.LINES);
GL.Color(lineColor);
GL.Vertex(Clip(clientRect, from));
GL.Vertex(Clip(clientRect, to));
GL.End();
}
thickLineSpacing = spacing * thickLines;
from.y = to.y = (thickGridLineY % (thickLineSpacing * (containerScale.y)) - (thickLineSpacing * (containerScale.y)));
while (from.y < clientRect.height + thickLineSpacing)
{
GL.Begin(GL.LINES);
GL.Color(thickLineColor);
GL.Vertex(Clip(clientRect, from));
GL.Vertex(Clip(clientRect, to));
GL.End();
from.y += spacing * containerScale.y * thickLines;
to.y += spacing * containerScale.y * thickLines;
}
}
}
}
| UnityCsReference/Modules/GraphViewEditor/Decorators/GridBackground.cs/0 | {
"file_path": "UnityCsReference/Modules/GraphViewEditor/Decorators/GridBackground.cs",
"repo_id": "UnityCsReference",
"token_count": 4038
} | 381 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.Experimental.GraphView
{
public class Node : GraphElement, ICollectibleElement
{
public VisualElement mainContainer { get; private set; }
public VisualElement titleContainer { get; private set; }
public VisualElement inputContainer { get; private set; }
public VisualElement outputContainer { get; private set; }
public VisualElement titleButtonContainer { get; private set; }
private VisualElement m_InputContainerParent;
private VisualElement m_OutputContainerParent;
//This directly contains input and output containers
public VisualElement topContainer { get; private set; }
public VisualElement extensionContainer { get; private set; }
private VisualElement m_CollapsibleArea;
private GraphView m_GraphView;
// TODO Maybe make protected and move to GraphElement!
private GraphView graphView
{
get
{
if (m_GraphView == null)
{
m_GraphView = GetFirstAncestorOfType<GraphView>();
}
return m_GraphView;
}
}
private bool m_Expanded;
public virtual bool expanded
{
get { return m_Expanded; }
set
{
if (m_Expanded == value)
return;
m_Expanded = value;
RefreshExpandedState();
}
}
public void RefreshExpandedState()
{
UpdateExpandedButtonState();
bool hasPorts = RefreshPorts();
VisualElement contents = mainContainer.Q("contents");
if (contents == null)
{
return;
}
VisualElement divider = contents.Q("divider");
if (divider != null)
{
SetElementVisible(divider, hasPorts);
}
UpdateCollapsibleAreaVisibility();
}
void UpdateCollapsibleAreaVisibility()
{
if (m_CollapsibleArea == null)
{
return;
}
bool displayBottom = expanded && extensionContainer.childCount > 0;
if (displayBottom)
{
if (m_CollapsibleArea.parent == null)
{
VisualElement contents = mainContainer.Q("contents");
if (contents == null)
{
return;
}
contents.Add(m_CollapsibleArea);
}
m_CollapsibleArea.BringToFront();
}
else
{
if (m_CollapsibleArea.parent != null)
{
m_CollapsibleArea.RemoveFromHierarchy();
}
}
}
private readonly Label m_TitleLabel;
public override string title
{
get { return m_TitleLabel != null ? m_TitleLabel.text : string.Empty; }
set { if (m_TitleLabel != null) m_TitleLabel.text = value; }
}
protected readonly VisualElement m_CollapseButton;
protected readonly VisualElement m_ButtonContainer;
private const string k_ExpandedStyleClass = "expanded";
private const string k_CollapsedStyleClass = "collapsed";
private void UpdateExpandedButtonState()
{
RemoveFromClassList(m_Expanded ? k_CollapsedStyleClass : k_ExpandedStyleClass);
AddToClassList(m_Expanded ? k_ExpandedStyleClass : k_CollapsedStyleClass);
}
public override Rect GetPosition()
{
if (resolvedStyle.position == Position.Absolute)
return new Rect(resolvedStyle.left, resolvedStyle.top, layout.width, layout.height);
return layout;
}
public override void SetPosition(Rect newPos)
{
style.position = Position.Absolute;
style.left = newPos.x;
style.top = newPos.y;
}
protected virtual void OnPortRemoved(Port port)
{}
public virtual Port InstantiatePort(Orientation orientation, Direction direction, Port.Capacity capacity, Type type)
{
return Port.Create<Edge>(orientation, direction, capacity, type);
}
private void SetElementVisible(VisualElement element, bool isVisible)
{
const string k_HiddenClassList = "hidden";
if (isVisible)
{
// Restore default value for visibility by setting it to StyleKeyword.Null.
// Setting it to Visibility.Visible would make it visible even if parent is hidden.
element.style.visibility = StyleKeyword.Null;
element.RemoveFromClassList(k_HiddenClassList);
}
else
{
element.style.visibility = Visibility.Hidden;
element.AddToClassList(k_HiddenClassList);
}
}
private bool AllElementsHidden(VisualElement element)
{
for (int i = 0; i < element.childCount; ++i)
{
if (element[i].visible)
return false;
}
return true;
}
private int ShowPorts(bool show, IList<Port> currentPorts)
{
int count = 0;
foreach (var port in currentPorts)
{
if (port.alwaysVisible || (show || port.connected) && !port.collapsed)
{
SetElementVisible(port, true);
count++;
}
else
{
SetElementVisible(port, false);
}
}
return count;
}
public bool RefreshPorts()
{
bool expandedState = expanded;
// Refresh the lists after all additions and everything took place
var updatedInputs = inputContainer.Query<Port>().ToList();
var updatedOutputs = outputContainer.Query<Port>().ToList();
foreach (Port input in updatedInputs)
{
// Make sure we don't register these more than once.
input.OnConnect -= OnPortConnectAction;
input.OnDisconnect -= OnPortConnectAction;
input.OnConnect += OnPortConnectAction;
input.OnDisconnect += OnPortConnectAction;
}
foreach (Port output in updatedOutputs)
{
// Make sure we don't register these more than once.
output.OnConnect -= OnPortConnectAction;
output.OnDisconnect -= OnPortConnectAction;
output.OnConnect += OnPortConnectAction;
output.OnDisconnect += OnPortConnectAction;
}
int inputCount = ShowPorts(expandedState, updatedInputs);
int outputCount = ShowPorts(expandedState, updatedOutputs);
VisualElement divider = topContainer.Q("divider");
bool outputVisible = outputCount > 0 || !AllElementsHidden(outputContainer);
bool inputVisible = inputCount > 0 || !AllElementsHidden(inputContainer);
// Show output container only if we have one or more child
if (outputVisible)
{
if (outputContainer.hierarchy.parent != m_OutputContainerParent)
{
m_OutputContainerParent.hierarchy.Add(outputContainer);
outputContainer.BringToFront();
}
}
else
{
if (outputContainer.hierarchy.parent == m_OutputContainerParent)
{
outputContainer.RemoveFromHierarchy();
}
}
if (inputVisible)
{
if (inputContainer.hierarchy.parent != m_InputContainerParent)
{
m_InputContainerParent.hierarchy.Add(inputContainer);
inputContainer.SendToBack();
}
}
else
{
if (inputContainer.hierarchy.parent == m_InputContainerParent)
{
inputContainer.RemoveFromHierarchy();
}
}
if (divider != null)
{
SetElementVisible(divider, inputVisible && outputVisible);
}
return inputVisible || outputVisible;
}
private void OnPortConnectAction(Port port)
{
bool canCollapse = false;
var updatedInputs = inputContainer.Query<Port>().ToList();
var updatedOutputs = outputContainer.Query<Port>().ToList();
foreach (Port input in updatedInputs)
{
if (!input.connected)
{
canCollapse = true;
break;
}
}
if (!canCollapse)
{
foreach (Port output in updatedOutputs)
{
if (!output.connected)
{
canCollapse = true;
break;
}
}
}
if (m_CollapseButton != null)
{
if (canCollapse)
m_CollapseButton.pseudoStates &= ~PseudoStates.Disabled;
else
m_CollapseButton.pseudoStates |= PseudoStates.Disabled;
}
}
protected virtual void ToggleCollapse()
{
expanded = !expanded;
}
protected void UseDefaultStyling()
{
AddStyleSheetPath("StyleSheets/GraphView/Node.uss");
}
public Node() : this("UXML/GraphView/Node.uxml")
{
UseDefaultStyling();
}
public Node(string uiFile)
{
var tpl = EditorGUIUtility.Load(uiFile) as VisualTreeAsset;
tpl.CloneTree(this);
VisualElement main = this;
VisualElement borderContainer = main.Q(name: "node-border");
if (borderContainer != null)
{
borderContainer.style.overflow = Overflow.Hidden;
mainContainer = borderContainer;
var selection = main.Q(name: "selection-border");
if (selection != null)
{
selection.style.overflow = Overflow.Visible; //fixes issues with selection border being clipped when zooming out
}
}
else
{
mainContainer = main;
}
titleContainer = main.Q(name: "title");
inputContainer = main.Q(name: "input");
if (inputContainer != null)
{
m_InputContainerParent = inputContainer.hierarchy.parent;
}
m_CollapsibleArea = main.Q(name: "collapsible-area");
extensionContainer = main.Q("extension");
VisualElement output = main.Q(name: "output");
outputContainer = output;
if (outputContainer != null)
{
m_OutputContainerParent = outputContainer.hierarchy.parent;
topContainer = output.parent;
}
m_TitleLabel = main.Q<Label>(name: "title-label");
titleButtonContainer = main.Q(name: "title-button-container");
m_CollapseButton = main.Q(name: "collapse-button");
m_CollapseButton.AddManipulator(new Clickable(ToggleCollapse));
elementTypeColor = new Color(0.9f, 0.9f, 0.9f, 0.5f);
if (main != this)
{
Add(main);
}
AddToClassList("node");
capabilities |= Capabilities.Selectable | Capabilities.Movable | Capabilities.Deletable | Capabilities.Ascendable | Capabilities.Copiable | Capabilities.Snappable | Capabilities.Groupable;
usageHints = UsageHints.DynamicTransform;
m_Expanded = true;
UpdateExpandedButtonState();
UpdateCollapsibleAreaVisibility();
this.AddManipulator(new ContextualMenuManipulator(BuildContextualMenu));
style.position = Position.Absolute;
}
void AddConnectionsToDeleteSet(VisualElement container, ref HashSet<GraphElement> toDelete)
{
List<GraphElement> toDeleteList = new List<GraphElement>();
container.Query<Port>().ForEach(elem =>
{
if (elem.connected)
{
foreach (Edge c in elem.connections)
{
if ((c.capabilities & Capabilities.Deletable) == 0)
continue;
toDeleteList.Add(c);
}
}
});
toDelete.UnionWith(toDeleteList);
}
void DisconnectAll(DropdownMenuAction a)
{
HashSet<GraphElement> toDelete = new HashSet<GraphElement>();
AddConnectionsToDeleteSet(inputContainer, ref toDelete);
AddConnectionsToDeleteSet(outputContainer, ref toDelete);
toDelete.Remove(null);
if (graphView != null)
{
graphView.DeleteElements(toDelete);
}
else
{
Debug.Log("Disconnecting nodes that are not in a GraphView will not work.");
}
}
DropdownMenuAction.Status DisconnectAllStatus(DropdownMenuAction a)
{
VisualElement[] containers =
{
inputContainer, outputContainer
};
foreach (var container in containers)
{
var currentInputs = container.Query<Port>().ToList();
foreach (var elem in currentInputs)
{
if (elem.connected)
{
return DropdownMenuAction.Status.Normal;
}
}
}
return DropdownMenuAction.Status.Disabled;
}
public virtual void BuildContextualMenu(ContextualMenuPopulateEvent evt)
{
if (evt.target is Node)
{
evt.menu.AppendAction("Disconnect all", DisconnectAll, DisconnectAllStatus);
evt.menu.AppendSeparator();
}
}
void CollectConnectedEdges(HashSet<GraphElement> edgeSet)
{
edgeSet.UnionWith(inputContainer.Children().OfType<Port>().SelectMany(c => c.connections)
.Where(d => (d.capabilities & Capabilities.Deletable) != 0)
.Cast<GraphElement>());
edgeSet.UnionWith(outputContainer.Children().OfType<Port>().SelectMany(c => c.connections)
.Where(d => (d.capabilities & Capabilities.Deletable) != 0)
.Cast<GraphElement>());
}
public virtual void CollectElements(HashSet<GraphElement> collectedElementSet, Func<GraphElement, bool> conditionFunc)
{
CollectConnectedEdges(collectedElementSet);
}
}
}
| UnityCsReference/Modules/GraphViewEditor/Elements/Node.cs/0 | {
"file_path": "UnityCsReference/Modules/GraphViewEditor/Elements/Node.cs",
"repo_id": "UnityCsReference",
"token_count": 7894
} | 382 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.Experimental.GraphView
{
internal struct InsertInfo
{
public static readonly InsertInfo nil = new InsertInfo { target = null, index = -1, localPosition = Vector2.zero };
public VisualElement target;
public int index;
public Vector2 localPosition;
}
internal interface IInsertLocation
{
void GetInsertInfo(Vector2 worldPosition, out InsertInfo insertInfo);
}
}
| UnityCsReference/Modules/GraphViewEditor/IInsertLocation.cs/0 | {
"file_path": "UnityCsReference/Modules/GraphViewEditor/IInsertLocation.cs",
"repo_id": "UnityCsReference",
"token_count": 221
} | 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.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.Experimental.GraphView
{
// TODO: Should stay internal when GraphView becomes public
internal class DragAndDropDelay
{
const float k_StartDragTreshold = 4.0f;
Vector2 mouseDownPosition { get; set; }
public void Init(Vector2 mousePosition)
{
mouseDownPosition = mousePosition;
}
public bool CanStartDrag(Vector2 mousePosition)
{
return Vector2.Distance(mouseDownPosition, mousePosition) > k_StartDragTreshold;
}
}
// Manipulates movable objects, can also initiate a Drag and Drop operation
// FIXME: update this code once we have support for drag and drop events in UIElements.
public class SelectionDropper : Manipulator
{
readonly DragAndDropDelay m_DragAndDropDelay;
bool m_Active;
public Vector2 panSpeed { get; set; }
public MouseButton activateButton { get; set; }
public bool clampToParentEdges { get; set; }
// selectedElement is used to store a unique selection candidate for cases where user clicks on an item not to
// drag it but just to reset the selection -- we only know this after the manipulation has ended
GraphElement selectedElement { get; set; }
ISelection selectionContainer { get; set; }
public SelectionDropper()
{
m_Active = false;
m_DragAndDropDelay = new DragAndDropDelay();
activateButton = MouseButton.LeftMouse;
panSpeed = new Vector2(1, 1);
}
protected override void RegisterCallbacksOnTarget()
{
target.RegisterCallback<MouseDownEvent>(OnMouseDown);
target.RegisterCallback<MouseMoveEvent>(OnMouseMove);
target.RegisterCallback<MouseUpEvent>(OnMouseUp);
target.RegisterCallback<MouseCaptureOutEvent>(OnMouseCaptureOutEvent);
}
protected override void UnregisterCallbacksFromTarget()
{
target.UnregisterCallback<MouseDownEvent>(OnMouseDown);
target.UnregisterCallback<MouseMoveEvent>(OnMouseMove);
target.UnregisterCallback<MouseUpEvent>(OnMouseUp);
target.UnregisterCallback<MouseCaptureOutEvent>(OnMouseCaptureOutEvent);
}
bool m_AddedByMouseDown;
bool m_Dragging;
void Reset()
{
m_Active = false;
m_AddedByMouseDown = false;
m_Dragging = false;
}
void OnMouseCaptureOutEvent(MouseCaptureOutEvent e)
{
if (m_Active)
{
Reset();
}
}
protected void OnMouseDown(MouseDownEvent e)
{
if (m_Active)
{
e.StopImmediatePropagation();
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 = false;
m_Dragging = false;
m_AddedByMouseDown = false;
if (target == null)
return;
selectionContainer = target.GetFirstAncestorOfType<ISelection>();
if (selectionContainer == null)
{
// Keep for potential later use in OnMouseUp (where e.target might be different then)
selectionContainer = target.GetFirstOfType<ISelection>();
selectedElement = e.target as GraphElement;
return;
}
selectedElement = target.GetFirstOfType<GraphElement>();
if (selectedElement == null)
return;
// Since we didn't drag after all, update selection with current element only
if (!selectionContainer.selection.Contains(selectedElement) && selectedElement.IsSelectable() &&
!ClickSelector.WasSelectableDescendantHitByMouse(selectedElement, e))
{
if (!e.actionKey)
selectionContainer.ClearSelection();
selectionContainer.AddToSelection(selectedElement);
m_AddedByMouseDown = true;
}
if (e.button == (int)activateButton)
{
// avoid starting a manipulation on a non movable object
if (!selectedElement.IsDroppable())
return;
// Reset drag and drop
m_DragAndDropDelay.Init(e.localMousePosition);
m_Active = true;
target.CaptureMouse();
e.StopPropagation();
}
}
protected void OnMouseMove(MouseMoveEvent e)
{
if (m_Active && !m_Dragging && selectionContainer != null)
{
// Keep a copy of the selection
var selection = selectionContainer.selection.ToList();
if (selection.Count > 0)
{
var ce = selection[0] as GraphElement;
bool canStartDrag = ce != null && ce.IsDroppable();
if (canStartDrag && m_DragAndDropDelay.CanStartDrag(e.localMousePosition))
{
DragAndDrop.PrepareStartDrag();
DragAndDrop.SetGenericData("DragSelection", selection);
m_Dragging = true;
DragAndDrop.StartDrag("");
DragAndDrop.visualMode = e.actionKey ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Move;
target.ReleaseMouse();
}
e.StopPropagation();
}
}
}
protected void OnMouseUp(MouseUpEvent e)
{
if (!m_Active || selectionContainer == null)
{
if (selectedElement != null && selectionContainer != null && !m_Dragging)
{
if (selectedElement.IsSelected((VisualElement)selectionContainer) && !e.actionKey && e.button == (int)activateButton)
{
// Reset to single selection
selectionContainer.ClearSelection();
selectedElement.Select((VisualElement)selectionContainer, e.actionKey);
}
}
Reset();
return;
}
if (e.button == (int)activateButton)
{
// Since we didn't drag after all, update selection with current element only
if (!e.actionKey)
{
selectionContainer.ClearSelection();
selectionContainer.AddToSelection(selectedElement);
}
else if (m_AddedByMouseDown && !m_Dragging && selectionContainer.selection.Contains(selectedElement))
{
selectionContainer.RemoveFromSelection(selectedElement);
}
target.ReleaseMouse();
e.StopPropagation();
Reset();
}
}
}
}
| UnityCsReference/Modules/GraphViewEditor/Manipulators/SelectionDropper.cs/0 | {
"file_path": "UnityCsReference/Modules/GraphViewEditor/Manipulators/SelectionDropper.cs",
"repo_id": "UnityCsReference",
"token_count": 3614
} | 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.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine.Bindings;
namespace Unity.Hierarchy
{
[VisibleToOtherModules("UnityEditor.HierarchyModule")]
interface IHierarchySearchQueryParser
{
HierarchySearchQueryDescriptor ParseQuery(string query);
}
class DefaultHierarchySearchQueryParser : IHierarchySearchQueryParser
{
static readonly Regex s_Filter = new Regex(@"([#$\w\[\]]+)(<=|<|>=|>|<|=|:)(.*)", RegexOptions.Compiled);
static List<string> Tokenize(string s)
{
s = s.Trim();
var tokens = new List<string>();
var startToken = 0;
var cursor = 0;
while (cursor < s.Length)
{
if (char.IsWhiteSpace(s[cursor]))
{
var token = s.Substring(startToken, cursor - startToken);
tokens.Add(token);
++cursor;
while (cursor < s.Length && char.IsWhiteSpace(s[cursor]))
{
++cursor;
}
if (cursor < s.Length)
{
startToken = cursor;
}
}
else if (s[cursor] == '"')
{
++cursor;
while (cursor < s.Length && s[cursor] != '"')
{
++cursor;
}
if (cursor >= s.Length)
return null;
else
++cursor;
}
else
{
++cursor;
}
}
if (cursor != startToken)
{
var token = s.Substring(startToken, cursor - startToken);
tokens.Add(token);
}
return tokens;
}
public HierarchySearchQueryDescriptor ParseQuery(string query)
{
if (string.IsNullOrWhiteSpace(query))
return HierarchySearchQueryDescriptor.Empty;
var tokens = Tokenize(query);
if (tokens == null)
return HierarchySearchQueryDescriptor.InvalidQuery;
var textValues = new List<string>();
var filters = new List<HierarchySearchFilter>();
var valid = true;
foreach (var t in tokens)
{
var m = s_Filter.Match(t);
if (m.Success)
{
if (m.Groups.Count < 4 || string.IsNullOrEmpty(m.Groups[1].Value) || string.IsNullOrEmpty(m.Groups[2].Value) || string.IsNullOrEmpty(m.Groups[3].Value))
{
valid = false;
break;
}
filters.Add(HierarchySearchFilter.CreateFilter(m.Groups[1].Value, m.Groups[2].Value, m.Groups[3].Value));
}
else
{
textValues.Add(t);
}
}
if (!valid)
return HierarchySearchQueryDescriptor.InvalidQuery;
return new HierarchySearchQueryDescriptor(filters.ToArray(), textValues.ToArray());
}
}
}
| UnityCsReference/Modules/HierarchyCore/Managed/HierarchySearch.cs/0 | {
"file_path": "UnityCsReference/Modules/HierarchyCore/Managed/HierarchySearch.cs",
"repo_id": "UnityCsReference",
"token_count": 1993
} | 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;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using UnityEngine.Bindings;
using UnityEngine.Pool;
using UnityEngine.Scripting;
namespace Unity.Hierarchy
{
/// <summary>
/// A hierarchy view model is a read-only filtering view of a <see cref="HierarchyFlattened"/>.
/// </summary>
[NativeType(Header = "Modules/HierarchyCore/Public/HierarchyViewModel.h")]
[NativeHeader("Modules/HierarchyCore/HierarchyViewModelBindings.h")]
[RequiredByNativeCode(GenerateProxy = true), StructLayout(LayoutKind.Sequential)]
public sealed class HierarchyViewModel : IDisposable
{
internal static class BindingsMarshaller
{
public static IntPtr ConvertToNative(HierarchyViewModel viewModel) => viewModel.m_Ptr;
}
[RequiredByNativeCode] IntPtr m_Ptr;
[RequiredByNativeCode] readonly bool m_IsWrapper;
[RequiredByNativeCode] readonly HierarchyFlattened m_HierarchyFlattened;
[RequiredByNativeCode] readonly Hierarchy m_Hierarchy;
[RequiredByNativeCode] readonly IntPtr m_NodesPtr;
[RequiredByNativeCode] readonly int m_NodesCount;
[RequiredByNativeCode] readonly int m_Version;
[FreeFunction("HierarchyViewModelBindings::Create", IsThreadSafe = true)]
static extern IntPtr Internal_Create(HierarchyFlattened hierarchyFlattened, HierarchyNodeFlags defaultFlags);
[FreeFunction("HierarchyViewModelBindings::Destroy", IsThreadSafe = true)]
static extern void Internal_Destroy(IntPtr ptr);
[FreeFunction("HierarchyViewModelBindings::BindScriptingObject", HasExplicitThis = true, IsThreadSafe = true)]
extern void Internal_BindScriptingObject([Unmarshalled] HierarchyViewModel self);
/// <summary>
/// Whether this object is valid and uses memory.
/// </summary>
public bool IsCreated => m_Ptr != IntPtr.Zero;
/// <summary>
/// The total number of nodes.
/// </summary>
/// <remarks>
/// The total does not include the <see cref="Hierarchy.Root"/> node.
/// </remarks>
public int Count => m_NodesCount;
/// <summary>
/// Whether the hierarchy view model is currently updating.
/// </summary>
/// <remarks>
/// This happens when <see cref="UpdateIncremental"/> or <see cref="UpdateIncrementalTimed"/> is used.
/// </remarks>
public extern bool Updating { [NativeMethod("Updating", IsThreadSafe = true)] get; }
/// <summary>
/// Whether the hierarchy view model requires an update.
/// </summary>
/// <remarks>
/// This happens when the underlying hierarchy changes topology.
/// </remarks>
public extern bool UpdateNeeded { [NativeMethod("UpdateNeeded", IsThreadSafe = true)] get; }
/// <summary>
/// Accesses the <see cref="HierarchyFlattened"/>.
/// </summary>
public HierarchyFlattened HierarchyFlattened => m_HierarchyFlattened;
/// <summary>
/// Accesses the <see cref="Hierarchy"/>.
/// </summary>
public Hierarchy Hierarchy => m_Hierarchy;
internal int Version
{
[VisibleToOtherModules("UnityEngine.HierarchyModule")]
get => m_Version;
}
internal extern float UpdateProgress
{
[VisibleToOtherModules("UnityEngine.HierarchyModule")]
[NativeMethod("UpdateProgress", IsThreadSafe = true)]
get;
}
internal IHierarchySearchQueryParser QueryParser
{
[VisibleToOtherModules("UnityEditor.HierarchyModule")]
get;
[VisibleToOtherModules("UnityEditor.HierarchyModule")]
set;
}
internal extern HierarchySearchQueryDescriptor Query
{
[VisibleToOtherModules("UnityEngine.HierarchyModule")]
[NativeMethod(IsThreadSafe = true)]
get;
[VisibleToOtherModules("UnityEngine.HierarchyModule")]
[NativeMethod(IsThreadSafe = true)]
set;
}
/// <summary>
/// Creates a new HierarchyViewModel from a <see cref="HierarchyFlattened"/>.
/// </summary>
/// <param name="hierarchyFlattened">The flattened hierarchy that serves as the hierarchy model.</param>
/// <param name="defaultFlags">The default flags used to initialize new nodes.</param>
public HierarchyViewModel(HierarchyFlattened hierarchyFlattened, HierarchyNodeFlags defaultFlags = HierarchyNodeFlags.None)
{
m_Ptr = Internal_Create(hierarchyFlattened, defaultFlags);
m_HierarchyFlattened = hierarchyFlattened;
m_Hierarchy = hierarchyFlattened.Hierarchy;
QueryParser = new DefaultHierarchySearchQueryParser();
Internal_BindScriptingObject(this);
}
~HierarchyViewModel()
{
Dispose(false);
}
/// <summary>
/// Disposes this object and releases its memory.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
void Dispose(bool disposing)
{
if (m_Ptr != IntPtr.Zero)
{
if (!m_IsWrapper)
Internal_Destroy(m_Ptr);
m_Ptr = IntPtr.Zero;
}
}
/// <summary>
/// Gets the <see cref="HierarchyNode"/> at a specified index.
/// </summary>
/// <param name="index">The node index.</param>
/// <returns>A hierarchy node.</returns>
public ref readonly HierarchyNode this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (index < 0 || index >= m_NodesCount)
throw new ArgumentOutOfRangeException(nameof(index));
unsafe
{
return ref HierarchyFlattenedNode.GetNodeByRef(in m_HierarchyFlattened[((int*)m_NodesPtr)[index]]);
}
}
}
/// <summary>
/// Gets the zero-based index of a specified node.
/// </summary>
/// <param name="node">The hierarchy node.</param>
/// <returns>A zero-based index of the node if found, -1 otherwise.</returns>
[NativeMethod(IsThreadSafe = true, ThrowsException = true)]
public extern int IndexOf(in HierarchyNode node);
/// <summary>
/// Determines if a specified node is in the hierarchy view model.
/// </summary>
/// <param name="node">The hierarchy node.</param>
/// <returns><see langword="true"/> if the node is found, <see langword="false"/> otherwise.</returns>
[NativeMethod(IsThreadSafe = true, ThrowsException = true)]
public extern bool Contains(in HierarchyNode node);
/// <summary>
/// Gets the parent of a hierarchy node.
/// </summary>
/// <param name="node">The hierarchy node.</param>
/// <returns>A hierarchy node.</returns>
[NativeMethod(IsThreadSafe = true, ThrowsException = true)]
public extern HierarchyNode GetParent(in HierarchyNode node);
/// <summary>
/// Gets the next sibling of a node.
/// </summary>
/// <param name="node">The hierarchy node.</param>
/// <returns>A hierarchy node.</returns>
[NativeMethod(IsThreadSafe = true, ThrowsException = true)]
public extern HierarchyNode GetNextSibling(in HierarchyNode node);
/// <summary>
/// Gets the number of child nodes that a hierarchy node has.
/// </summary>
/// <param name="node">The hierarchy node.</param>
/// <returns>The number of children.</returns>
[NativeMethod(IsThreadSafe = true, ThrowsException = true)]
public extern int GetChildrenCount(in HierarchyNode node);
/// <summary>
/// Gets the number of child nodes that a hierarchy node has, including children of children.
/// </summary>
/// <param name="node">The hierarchy node.</param>
/// <returns>The number of child nodes, including children of children.</returns>
[NativeMethod(IsThreadSafe = true, ThrowsException = true)]
public extern int GetChildrenCountRecursive(in HierarchyNode node);
/// <summary>
/// Determines the depth of a node.
/// </summary>
/// <param name="node">The hierarchy node.</param>
/// <returns>The depth of the hierarchy node.</returns>
[NativeMethod(IsThreadSafe = true, ThrowsException = true)]
public extern int GetDepth(in HierarchyNode node);
/// <summary>
/// Gets all the flags set on a given hierarchy node.
/// </summary>
/// <param name="node">The hierarchy node.</param>
/// <returns>The flags set on the hierarchy node.</returns>
[NativeMethod(IsThreadSafe = true, ThrowsException = true)]
public extern HierarchyNodeFlags GetFlags(in HierarchyNode node);
/// <summary>
/// Sets the specified flags on all hierarchy nodes.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
public void SetFlags(HierarchyNodeFlags flags) => SetFlagsAll(flags);
/// <summary>
/// Sets the specified flags on the hierarchy node.
/// </summary>
/// <param name="node">The hierarchy node.</param>
/// <param name="flags">The hierarchy node flags.</param>
/// <param name="recurse">Whether or not to set the flags on all children recursively for that hierarchy node.</param>
public void SetFlags(in HierarchyNode node, HierarchyNodeFlags flags, bool recurse = false) => SetFlagsNode(in node, flags, recurse);
/// <summary>
/// Sets the specified flags on the hierarchy nodes.
/// </summary>
/// <remarks>
/// Null or invalid nodes are ignored.
/// </remarks>
/// <param name="nodes">The hierarchy nodes.</param>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns>The number of nodes that had their flags set.</returns>
public int SetFlags(ReadOnlySpan<HierarchyNode> nodes, HierarchyNodeFlags flags) => SetFlagsNodes(nodes, flags);
/// <summary>
/// Sets the specified flags on the hierarchy node indices.
/// </summary>
/// <remarks>
/// Invalid node indices are ignored.
/// </remarks>
/// <param name="indices">The hierarchy node indices.</param>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns>The number of nodes that had their flags set.</returns>
public int SetFlags(ReadOnlySpan<int> indices, HierarchyNodeFlags flags) => SetFlagsIndices(indices, flags);
/// <summary>
/// Gets whether or not all of the specified flags are set on any hierarchy node.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns><see langword="true"/> if any node have all of the flags set, <see langword="false"/> otherwise.</returns>
public bool HasAllFlags(HierarchyNodeFlags flags) => HasAllFlagsAny(flags);
/// <summary>
/// Gets whether or not any of the specified flags are set on any hierarchy node.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns><see langword="true"/> if any node have any of the flags set, <see langword="false"/> otherwise.</returns>
public bool HasAnyFlags(HierarchyNodeFlags flags) => HasAnyFlagsAny(flags);
/// <summary>
/// Gets whether or not all of the specified flags are set on the hierarchy node.
/// </summary>
/// <param name="node">The hierarchy node.</param>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns><see langword="true"/> if all of the flags are set, <see langword="false"/> otherwise.</returns>
public bool HasAllFlags(in HierarchyNode node, HierarchyNodeFlags flags) => HasAllFlagsNode(in node, flags);
/// <summary>
/// Gets whether or not any of the specified flags are set on the hierarchy node.
/// </summary>
/// <param name="node">The hierarchy node.</param>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns><see langword="true"/> if any of the flags are set, <see langword="false"/> otherwise.</returns>
public bool HasAnyFlags(in HierarchyNode node, HierarchyNodeFlags flags) => HasAnyFlagsNode(in node, flags);
/// <summary>
/// Gets the number of nodes that have all of the specified flags set.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns>The number of nodes that have all of the flags set.</returns>
[NativeMethod(IsThreadSafe = true, ThrowsException = true)]
public extern int HasAllFlagsCount(HierarchyNodeFlags flags);
/// <summary>
/// Gets the number of nodes that have any of the specified flags set.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns>The number of nodes that have any of the flags set.</returns>
[NativeMethod(IsThreadSafe = true, ThrowsException = true)]
public extern int HasAnyFlagsCount(HierarchyNodeFlags flags);
/// <summary>
/// Gets whether or not all of the specified flags are not set on any hierarchy node.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns><see langword="true"/> if none of the node have all of the flags set, <see langword="false"/> otherwise.</returns>
public bool DoesNotHaveAllFlags(HierarchyNodeFlags flags) => DoesNotHaveAllFlagsAny(flags);
/// <summary>
/// Gets whether or not any of the specified flags are not set on any hierarchy node.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns><see langword="true"/> if none of the node have any of the flags set, <see langword="false"/> otherwise.</returns>
public bool DoesNotHaveAnyFlags(HierarchyNodeFlags flags) => DoesNotHaveAnyFlagsAny(flags);
/// <summary>
/// Gets whether or not all of the specified flags are not set on the hierarchy node.
/// </summary>
/// <param name="node">The hierarchy node.</param>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns><see langword="true"/> if all of the flags are not set, <see langword="false"/> otherwise.</returns>
public bool DoesNotHaveAllFlags(in HierarchyNode node, HierarchyNodeFlags flags) => DoesNotHaveAllFlagsNode(in node, flags);
/// <summary>
/// Gets whether or not any of the specified flags are not set on the hierarchy node.
/// </summary>
/// <param name="node">The hierarchy node.</param>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns><see langword="true"/> if none of the flags are set, <see langword="false"/> otherwise.</returns>
public bool DoesNotHaveAnyFlags(in HierarchyNode node, HierarchyNodeFlags flags) => DoesNotHaveAnyFlagsNode(in node, flags);
/// <summary>
/// Gets the number of nodes that do not have all of the specified flags set.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns>The number of nodes that do not have all of the flags set.</returns>
[NativeMethod(IsThreadSafe = true, ThrowsException = true)]
public extern int DoesNotHaveAllFlagsCount(HierarchyNodeFlags flags);
/// <summary>
/// Gets the number of nodes that do not have any of the specified flags set.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns>The number of nodes that do not have any of the flags set.</returns>
[NativeMethod(IsThreadSafe = true, ThrowsException = true)]
public extern int DoesNotHaveAnyFlagsCount(HierarchyNodeFlags flags);
/// <summary>
/// Clears the specified flags on all hierarchy nodes.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
public void ClearFlags(HierarchyNodeFlags flags) => ClearFlagsAll(flags);
/// <summary>
/// Clears the specified flags on the hierarchy node.
/// </summary>
/// <param name="node">The hierarchy node.</param>
/// <param name="flags">The hierarchy node flags.</param>
/// <param name="recurse">Whether or not to clear the flags on all children recursively for that hierarchy node.</param>
public void ClearFlags(in HierarchyNode node, HierarchyNodeFlags flags, bool recurse = false) => ClearFlagsNode(in node, flags, recurse);
/// <summary>
/// Clears the specified flags on the hierarchy nodes.
/// </summary>
/// <remarks>
/// Null or invalid nodes are ignored.
/// </remarks>
/// <param name="nodes">The hierarchy nodes.</param>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns>The number of nodes that had their flags cleared.</returns>
public int ClearFlags(ReadOnlySpan<HierarchyNode> nodes, HierarchyNodeFlags flags) => ClearFlagsNodes(nodes, flags);
/// <summary>
/// Clears the specified flags on the hierarchy node indices.
/// </summary>
/// <remarks>
/// Invalid node indices are ignored.
/// </remarks>
/// <param name="indices">The hierarchy node indices.</param>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns>The number of nodes that had their flags cleared.</returns>
public int ClearFlags(ReadOnlySpan<int> indices, HierarchyNodeFlags flags) => ClearFlagsIndices(indices, flags);
/// <summary>
/// Toggles the specified flags on all hierarchy nodes.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
public void ToggleFlags(HierarchyNodeFlags flags) => ToggleFlagsAll(flags);
/// <summary>
/// Toggles the specified flags on the hierarchy node.
/// </summary>
/// <param name="node">The hierarchy node.</param>
/// <param name="flags">The hierarchy node flags.</param>
/// <param name="recurse">Whether or not to clear the flags on all children recursively for that hierarchy node.</param>
public void ToggleFlags(in HierarchyNode node, HierarchyNodeFlags flags, bool recurse = false) => ToggleFlagsNode(in node, flags, recurse);
/// <summary>
/// Toggles the specified flags on the hierarchy nodes.
/// </summary>
/// <remarks>
/// Null or invalid nodes are ignored.
/// </remarks>
/// <param name="nodes">The hierarchy nodes.</param>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns>The number of nodes that had their flags cleared.</returns>
public int ToggleFlags(ReadOnlySpan<HierarchyNode> nodes, HierarchyNodeFlags flags) => ToggleFlagsNodes(nodes, flags);
/// <summary>
/// Toggles the specified flags on the hierarchy node indices.
/// </summary>
/// <remarks>
/// Invalid node indices are ignored.
/// </remarks>
/// <param name="indices">The hierarchy node indices.</param>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns>The number of nodes that had their flags cleared.</returns>
public int ToggleFlags(ReadOnlySpan<int> indices, HierarchyNodeFlags flags) => ToggleFlagsIndices(indices, flags);
/// <summary>
/// Gets all hierarchy nodes that have all of the specified flags set.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <param name="outNodes">The hierarchy nodes.</param>
/// <returns>The number of nodes written in the <paramref name="outNodes"/> span.</returns>
public int GetNodesWithAllFlags(HierarchyNodeFlags flags, Span<HierarchyNode> outNodes) => GetNodesWithAllFlagsSpan(flags, outNodes);
/// <summary>
/// Gets all hierarchy nodes that have any of the specified flags set.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <param name="outNodes">The hierarchy nodes.</param>
/// <returns>The number of nodes written in the <paramref name="outNodes"/> span.</returns>
public int GetNodesWithAnyFlags(HierarchyNodeFlags flags, Span<HierarchyNode> outNodes) => GetNodesWithAnyFlagsSpan(flags, outNodes);
/// <summary>
/// Gets all hierarchy nodes that have all of the specified flags set.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns>The hierarchy nodes.</returns>
public HierarchyNode[] GetNodesWithAllFlags(HierarchyNodeFlags flags)
{
var count = HasAllFlagsCount(flags);
if (count == 0)
return Array.Empty<HierarchyNode>();
var nodes = new HierarchyNode[count];
GetNodesWithAllFlagsSpan(flags, nodes);
return nodes;
}
/// <summary>
/// Gets all hierarchy nodes that have any of the specified flags set.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns>The hierarchy nodes.</returns>
public HierarchyNode[] GetNodesWithAnyFlags(HierarchyNodeFlags flags)
{
var count = HasAnyFlagsCount(flags);
if (count == 0)
return Array.Empty<HierarchyNode>();
var nodes = new HierarchyNode[count];
GetNodesWithAnyFlagsSpan(flags, nodes);
return nodes;
}
/// <summary>
/// Gets an enumerable of all hierarchy nodes that have all of the specified flags set.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns>An enumerable of hierarchy node.</returns>
public HierarchyViewNodesEnumerable EnumerateNodesWithAllFlags(HierarchyNodeFlags flags) => new HierarchyViewNodesEnumerable(this, flags, HasAllFlags);
/// <summary>
/// Gets an enumerable of all hierarchy nodes that have any of the specified flags set.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns>An enumerable of hierarchy node.</returns>
public HierarchyViewNodesEnumerable EnumerateNodesWithAnyFlags(HierarchyNodeFlags flags) => new HierarchyViewNodesEnumerable(this, flags, HasAnyFlags);
/// <summary>
/// Gets the indices for all hierarchy nodes that have all of the specified flags set.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <param name="outIndices">The hierarchy node indices.</param>
/// <returns>The number of indices written in the <paramref name="outIndices"/> span.</returns>
public int GetIndicesWithAllFlags(HierarchyNodeFlags flags, Span<int> outIndices) => GetIndicesWithAllFlagsSpan(flags, outIndices);
/// <summary>
/// Gets the indices for all hierarchy nodes that have any of the specified flags set.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <param name="outIndices">The hierarchy node indices.</param>
/// <returns>The number of indices written in the <paramref name="outIndices"/> span.</returns>
public int GetIndicesWithAnyFlags(HierarchyNodeFlags flags, Span<int> outIndices) => GetIndicesWithAnyFlagsSpan(flags, outIndices);
/// <summary>
/// Gets the indices for all hierarchy nodes that have all of the specified flags set.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns>The hierarchy node indices.</returns>
public int[] GetIndicesWithAllFlags(HierarchyNodeFlags flags)
{
var count = HasAllFlagsCount(flags);
if (count == 0)
return Array.Empty<int>();
var indices = new int[count];
GetIndicesWithAllFlagsSpan(flags, indices);
return indices;
}
/// <summary>
/// Gets the indices for all hierarchy nodes that have any of the specified flags set.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns>The hierarchy node indices.</returns>
public int[] GetIndicesWithAnyFlags(HierarchyNodeFlags flags)
{
var count = HasAnyFlagsCount(flags);
if (count == 0)
return Array.Empty<int>();
var indices = new int[count];
GetIndicesWithAnyFlagsSpan(flags, indices);
return indices;
}
/// <summary>
/// Gets all hierarchy nodes that do not have all of the specified flags set.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <param name="outNodes">The hierarchy nodes.</param>
/// <returns>The number of nodes written in the <paramref name="outNodes"/> span.</returns>
public int GetNodesWithoutAllFlags(HierarchyNodeFlags flags, Span<HierarchyNode> outNodes) => GetNodesWithoutAllFlagsSpan(flags, outNodes);
/// <summary>
/// Gets all hierarchy nodes that do not have any of the specified flags set.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <param name="outNodes">The hierarchy nodes.</param>
/// <returns>The number of nodes written in the <paramref name="outNodes"/> span.</returns>
public int GetNodesWithoutAnyFlags(HierarchyNodeFlags flags, Span<HierarchyNode> outNodes) => GetNodesWithoutAnyFlagsSpan(flags, outNodes);
/// <summary>
/// Gets all hierarchy nodes that do not have all of the specified flags set.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns>The hierarchy nodes.</returns>
public HierarchyNode[] GetNodesWithoutAllFlags(HierarchyNodeFlags flags)
{
var count = DoesNotHaveAllFlagsCount(flags);
if (count == 0)
return Array.Empty<HierarchyNode>();
var nodes = new HierarchyNode[count];
GetNodesWithoutAllFlagsSpan(flags, nodes);
return nodes;
}
/// <summary>
/// Gets all hierarchy nodes that do not have any of the specified flags set.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns>The hierarchy nodes.</returns>
public HierarchyNode[] GetNodesWithoutAnyFlags(HierarchyNodeFlags flags)
{
var count = DoesNotHaveAnyFlagsCount(flags);
if (count == 0)
return Array.Empty<HierarchyNode>();
var nodes = new HierarchyNode[count];
GetNodesWithoutAnyFlagsSpan(flags, nodes);
return nodes;
}
/// <summary>
/// Gets an enumerable of all hierarchy nodes that do not have all of the specified flags set.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns>An enumerable of hierarchy node.</returns>
public HierarchyViewNodesEnumerable EnumerateNodesWithoutAllFlags(HierarchyNodeFlags flags) => new HierarchyViewNodesEnumerable(this, flags, DoesNotHaveAllFlags);
/// <summary>
/// Gets an enumerable of all hierarchy nodes that do not have any of the specified flags set.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns>An enumerable of hierarchy node.</returns>
public HierarchyViewNodesEnumerable EnumerateNodesWithoutAnyFlags(HierarchyNodeFlags flags) => new HierarchyViewNodesEnumerable(this, flags, DoesNotHaveAnyFlags);
/// <summary>
/// Gets the indices of all hierarchy nodes that do not have all of the specified flags set.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <param name="outIndices">The hierarchy node indices.</param>
/// <returns>The number of indices written in the <paramref name="outIndices"/> span.</returns>
public int GetIndicesWithoutAllFlags(HierarchyNodeFlags flags, Span<int> outIndices) => GetIndicesWithoutAllFlagsSpan(flags, outIndices);
/// <summary>
/// Gets the indices of all hierarchy nodes that do not have any of the specified flags set.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <param name="outIndices">The hierarchy node indices.</param>
/// <returns>The number of indices written in the <paramref name="outIndices"/> span.</returns>
public int GetIndicesWithoutAnyFlags(HierarchyNodeFlags flags, Span<int> outIndices) => GetIndicesWithoutAnyFlagsSpan(flags, outIndices);
/// <summary>
/// Gets the indices of all hierarchy nodes that do not have all of the specified flags set.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns>The hierarchy node indices.</returns>
public int[] GetIndicesWithoutAllFlags(HierarchyNodeFlags flags)
{
var count = DoesNotHaveAllFlagsCount(flags);
if (count == 0)
return Array.Empty<int>();
var indices = new int[count];
GetIndicesWithoutAllFlagsSpan(flags, indices);
return indices;
}
/// <summary>
/// Gets the indices of all hierarchy nodes that do not have any of the specified flags set.
/// </summary>
/// <param name="flags">The hierarchy node flags.</param>
/// <returns>The hierarchy node indices.</returns>
public int[] GetIndicesWithoutAnyFlags(HierarchyNodeFlags flags)
{
var count = DoesNotHaveAnyFlagsCount(flags);
if (count == 0)
return Array.Empty<int>();
var indices = new int[count];
GetIndicesWithoutAnyFlagsSpan(flags, indices);
return indices;
}
/// <summary>
/// Sets the search query.
/// </summary>
/// <param name="query">The search query.</param>
public void SetQuery(string query)
{
var newQuery = QueryParser.ParseQuery(query);
if (newQuery == Query)
return;
Query = newQuery;
}
/// <summary>
/// Updates the hierarchy view model and requests a rebuild of the list of <see cref="HierarchyNode"/> that filters the <see cref="HierarchyFlattened"/>.
/// </summary>
[NativeMethod(IsThreadSafe = true)]
public extern void Update();
/// <summary>
/// Updates the hierarchy view model incrementally.
/// </summary>
/// <returns><see langword="true"/> if additional invocations are needed to complete the update, <see langword="false"/> otherwise.</returns>
[NativeMethod(IsThreadSafe = true)]
public extern bool UpdateIncremental();
/// <summary>
/// Updates the hierarchy view model incrementally until a time limit is reached.
/// </summary>
/// <param name="milliseconds">The time period in milliseconds.</param>
/// <returns><see langword="true"/> if additional invocations are needed to complete the update, <see langword="false"/> otherwise.</returns>
[NativeMethod(IsThreadSafe = true)]
public extern bool UpdateIncrementalTimed(double milliseconds);
/// <summary>
/// Gets the <see cref="HierarchyNode"/> enumerator.
/// </summary>
/// <returns>An enumerator.</returns>
public Enumerator GetEnumerator() => new Enumerator(this);
/// <summary>
/// An enumerator of <see cref="HierarchyNode"/>. Enumerates and filters items at the same time.
/// </summary>
public unsafe struct Enumerator
{
readonly HierarchyFlattened m_HierarchyFlattened;
readonly HierarchyViewModel m_ViewModel;
readonly int* m_ViewModelNodesPtr;
readonly int m_Count;
readonly int m_Version;
int m_Index;
internal Enumerator(HierarchyViewModel hierarchyViewModel)
{
m_Count = hierarchyViewModel.Count;
m_HierarchyFlattened = hierarchyViewModel.HierarchyFlattened;
m_ViewModel = hierarchyViewModel;
m_ViewModelNodesPtr = (int*)hierarchyViewModel.m_NodesPtr;
m_Version = hierarchyViewModel.m_Version;
m_Index = -1;
}
/// <summary>
/// Get the current item being enumerated.
/// </summary>
public ref readonly HierarchyNode Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
ThrowIfVersionChanged();
return ref HierarchyFlattenedNode.GetNodeByRef(in m_HierarchyFlattened[m_ViewModelNodesPtr[m_Index]]);
}
}
/// <summary>
/// Move to next iterable value.
/// </summary>
/// <returns>Returns true if Current item is valid</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
ThrowIfVersionChanged();
int index = m_Index + 1;
if (index < m_Count)
{
m_Index = index;
return true;
}
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void ThrowIfVersionChanged()
{
if (m_Version != m_ViewModel.m_Version)
throw new InvalidOperationException("HierarchyViewModel was modified.");
}
}
// Note: called from native to avoid passing Query as a parameter
[RequiredByNativeCode]
internal void SearchBegin()
{
using var _ = ListPool<HierarchyNodeTypeHandlerBase>.Get(out var handlers);
m_Hierarchy.GetAllNodeTypeHandlersBase(handlers);
foreach (var handler in handlers)
handler.Internal_SearchBegin(Query);
}
[FreeFunction("HierarchyViewModelBindings::SetFlagsAll", HasExplicitThis = true, IsThreadSafe = true, ThrowsException = true)]
extern void SetFlagsAll(HierarchyNodeFlags flags);
[FreeFunction("HierarchyViewModelBindings::SetFlagsNode", HasExplicitThis = true, IsThreadSafe = true, ThrowsException = true)]
extern void SetFlagsNode(in HierarchyNode node, HierarchyNodeFlags flags, bool recurse = false);
[FreeFunction("HierarchyViewModelBindings::SetFlagsNodes", HasExplicitThis = true, IsThreadSafe = true)]
extern int SetFlagsNodes(ReadOnlySpan<HierarchyNode> nodes, HierarchyNodeFlags flags);
[FreeFunction("HierarchyViewModelBindings::SetFlagsIndices", HasExplicitThis = true, IsThreadSafe = true)]
extern int SetFlagsIndices(ReadOnlySpan<int> indices, HierarchyNodeFlags flags);
[FreeFunction("HierarchyViewModelBindings::HasAllFlagsAny", HasExplicitThis = true, IsThreadSafe = true, ThrowsException = true)]
extern bool HasAllFlagsAny(HierarchyNodeFlags flags);
[FreeFunction("HierarchyViewModelBindings::HasAnyFlagsAny", HasExplicitThis = true, IsThreadSafe = true, ThrowsException = true)]
extern bool HasAnyFlagsAny(HierarchyNodeFlags flags);
[FreeFunction("HierarchyViewModelBindings::HasAllFlagsNode", HasExplicitThis = true, IsThreadSafe = true, ThrowsException = true)]
extern bool HasAllFlagsNode(in HierarchyNode node, HierarchyNodeFlags flags);
[FreeFunction("HierarchyViewModelBindings::HasAnyFlagsNode", HasExplicitThis = true, IsThreadSafe = true, ThrowsException = true)]
extern bool HasAnyFlagsNode(in HierarchyNode node, HierarchyNodeFlags flags);
[FreeFunction("HierarchyViewModelBindings::DoesNotHaveAllFlagsAny", HasExplicitThis = true, IsThreadSafe = true, ThrowsException = true)]
extern bool DoesNotHaveAllFlagsAny(HierarchyNodeFlags flags);
[FreeFunction("HierarchyViewModelBindings::DoesNotHaveAnyFlagsAny", HasExplicitThis = true, IsThreadSafe = true, ThrowsException = true)]
extern bool DoesNotHaveAnyFlagsAny(HierarchyNodeFlags flags);
[FreeFunction("HierarchyViewModelBindings::DoesNotHaveAllFlagsNode", HasExplicitThis = true, IsThreadSafe = true, ThrowsException = true)]
extern bool DoesNotHaveAllFlagsNode(in HierarchyNode node, HierarchyNodeFlags flags);
[FreeFunction("HierarchyViewModelBindings::DoesNotHaveAnyFlagsNode", HasExplicitThis = true, IsThreadSafe = true, ThrowsException = true)]
extern bool DoesNotHaveAnyFlagsNode(in HierarchyNode node, HierarchyNodeFlags flags);
[FreeFunction("HierarchyViewModelBindings::ClearFlagsAll", HasExplicitThis = true, IsThreadSafe = true, ThrowsException = true)]
extern void ClearFlagsAll(HierarchyNodeFlags flags);
[FreeFunction("HierarchyViewModelBindings::ClearFlagsNode", HasExplicitThis = true, IsThreadSafe = true, ThrowsException = true)]
extern void ClearFlagsNode(in HierarchyNode node, HierarchyNodeFlags flags, bool recurse = false);
[FreeFunction("HierarchyViewModelBindings::ClearFlagsNodes", HasExplicitThis = true, IsThreadSafe = true)]
extern int ClearFlagsNodes(ReadOnlySpan<HierarchyNode> nodes, HierarchyNodeFlags flags);
[FreeFunction("HierarchyViewModelBindings::ClearFlagsIndices", HasExplicitThis = true, IsThreadSafe = true)]
extern int ClearFlagsIndices(ReadOnlySpan<int> indices, HierarchyNodeFlags flags);
[FreeFunction("HierarchyViewModelBindings::ToggleFlagsAll", HasExplicitThis = true, IsThreadSafe = true, ThrowsException = true)]
extern void ToggleFlagsAll(HierarchyNodeFlags flags);
[FreeFunction("HierarchyViewModelBindings::ToggleFlagsNode", HasExplicitThis = true, IsThreadSafe = true, ThrowsException = true)]
extern void ToggleFlagsNode(in HierarchyNode node, HierarchyNodeFlags flags, bool recurse = false);
[FreeFunction("HierarchyViewModelBindings::ToggleFlagsNodes", HasExplicitThis = true, IsThreadSafe = true)]
extern int ToggleFlagsNodes(ReadOnlySpan<HierarchyNode> nodes, HierarchyNodeFlags flags);
[FreeFunction("HierarchyViewModelBindings::ToggleFlagsIndices", HasExplicitThis = true, IsThreadSafe = true)]
extern int ToggleFlagsIndices(ReadOnlySpan<int> indices, HierarchyNodeFlags flags);
[FreeFunction("HierarchyViewModelBindings::GetNodesWithAllFlagsSpan", HasExplicitThis = true, IsThreadSafe = true, ThrowsException = true)]
extern int GetNodesWithAllFlagsSpan(HierarchyNodeFlags flags, Span<HierarchyNode> outNodes);
[FreeFunction("HierarchyViewModelBindings::GetNodesWithAnyFlagsSpan", HasExplicitThis = true, IsThreadSafe = true, ThrowsException = true)]
extern int GetNodesWithAnyFlagsSpan(HierarchyNodeFlags flags, Span<HierarchyNode> outNodes);
[FreeFunction("HierarchyViewModelBindings::GetIndicesWithAllFlagsSpan", HasExplicitThis = true, IsThreadSafe = true, ThrowsException = true)]
extern int GetIndicesWithAllFlagsSpan(HierarchyNodeFlags flags, Span<int> outIndices);
[FreeFunction("HierarchyViewModelBindings::GetIndicesWithAnyFlagsSpan", HasExplicitThis = true, IsThreadSafe = true, ThrowsException = true)]
extern int GetIndicesWithAnyFlagsSpan(HierarchyNodeFlags flags, Span<int> outIndices);
[FreeFunction("HierarchyViewModelBindings::GetNodesWithoutAllFlagsSpan", HasExplicitThis = true, IsThreadSafe = true, ThrowsException = true)]
extern int GetNodesWithoutAllFlagsSpan(HierarchyNodeFlags flags, Span<HierarchyNode> outNodes);
[FreeFunction("HierarchyViewModelBindings::GetNodesWithoutAnyFlagsSpan", HasExplicitThis = true, IsThreadSafe = true, ThrowsException = true)]
extern int GetNodesWithoutAnyFlagsSpan(HierarchyNodeFlags flags, Span<HierarchyNode> outNodes);
[FreeFunction("HierarchyViewModelBindings::GetIndicesWithoutAllFlagsSpan", HasExplicitThis = true, IsThreadSafe = true, ThrowsException = true)]
extern int GetIndicesWithoutAllFlagsSpan(HierarchyNodeFlags flags, Span<int> outIndices);
[FreeFunction("HierarchyViewModelBindings::GetIndicesWithoutAnyFlagsSpan", HasExplicitThis = true, IsThreadSafe = true, ThrowsException = true)]
extern int GetIndicesWithoutAnyFlagsSpan(HierarchyNodeFlags flags, Span<int> outIndices);
#region Obsolete public APIs to remove in 2024
[Obsolete("HasFlags is obsolete, please use HasAllFlags or HasAnyFlags instead", false)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public bool HasFlags(HierarchyNodeFlags flags) => HasAllFlagsAny(flags);
[Obsolete("HasFlags is obsolete, please use HasAllFlags or HasAnyFlags instead", false)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public bool HasFlags(in HierarchyNode node, HierarchyNodeFlags flags) => HasAllFlagsNode(in node, flags);
[Obsolete("HasFlagsCount is obsolete, please use HasAllFlagsCount or HasAnyFlagsCount instead", false)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public int HasFlagsCount(HierarchyNodeFlags flags) => HasAllFlagsCount(flags);
[Obsolete("DoesNotHaveFlags is obsolete, please use DoesNotHaveAllFlags or DoesNotHaveAnyFlags instead", false)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public bool DoesNotHaveFlags(HierarchyNodeFlags flags) => DoesNotHaveAllFlagsAny(flags);
[Obsolete("DoesNotHaveFlags is obsolete, please use DoesNotHaveAllFlags or DoesNotHaveAnyFlags instead", false)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public bool DoesNotHaveFlags(in HierarchyNode node, HierarchyNodeFlags flags) => DoesNotHaveAllFlagsNode(in node, flags);
[Obsolete("DoesNotHaveFlagsCount is obsolete, please use DoesNotHaveAllFlagsCount or DoesNotHaveAnyFlagsCount instead", false)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public int DoesNotHaveFlagsCount(HierarchyNodeFlags flags) => DoesNotHaveAllFlagsCount(flags);
[Obsolete("GetNodesWithFlags is obsolete, please use GetNodesWithAllFlags or GetNodesWithAnyFlags instead", false)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public int GetNodesWithFlags(HierarchyNodeFlags flags, Span<HierarchyNode> outNodes) => GetNodesWithAllFlagsSpan(flags, outNodes);
[Obsolete("GetNodesWithFlags is obsolete, please use GetNodesWithAllFlags or GetNodesWithAnyFlags instead", false)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public HierarchyNode[] GetNodesWithFlags(HierarchyNodeFlags flags) => GetNodesWithAllFlags(flags);
[Obsolete("EnumerateNodesWithFlags is obsolete, please use EnumerateNodesWithAllFlags or EnumerateNodesWithAnyFlags instead", false)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public HierarchyViewNodesEnumerable EnumerateNodesWithFlags(HierarchyNodeFlags flags) => EnumerateNodesWithAllFlags(flags);
[Obsolete("GetIndicesWithFlags is obsolete, please use GetIndicesWithAllFlags or GetIndicesWithAnyFlags instead", false)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public int GetIndicesWithFlags(HierarchyNodeFlags flags, Span<int> outIndices) => GetIndicesWithAllFlagsSpan(flags, outIndices);
[Obsolete("GetIndicesWithFlags is obsolete, please use GetIndicesWithAllFlags or GetIndicesWithAnyFlags instead", false)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public int[] GetIndicesWithFlags(HierarchyNodeFlags flags) => GetIndicesWithAllFlags(flags);
[Obsolete("GetNodesWithoutFlags is obsolete, please use GetNodesWithoutAllFlags or GetNodesWithoutAnyFlags instead", false)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public int GetNodesWithoutFlags(HierarchyNodeFlags flags, Span<HierarchyNode> outNodes) => GetNodesWithoutAllFlagsSpan(flags, outNodes);
[Obsolete("GetNodesWithoutFlags is obsolete, please use GetNodesWithoutAllFlags or GetNodesWithoutAnyFlags instead", false)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public HierarchyNode[] GetNodesWithoutFlags(HierarchyNodeFlags flags) => GetNodesWithoutAllFlags(flags);
[Obsolete("EnumerateNodesWithoutFlags is obsolete, please use EnumerateNodesWithoutAllFlags or EnumerateNodesWithoutAnyFlags instead", false)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public HierarchyViewNodesEnumerable EnumerateNodesWithoutFlags(HierarchyNodeFlags flags) => EnumerateNodesWithoutAllFlags(flags);
[Obsolete("GetIndicesWithoutFlags is obsolete, please use GetIndicesWithoutAllFlags or GetIndicesWithoutAnyFlags instead", false)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public int GetIndicesWithoutFlags(HierarchyNodeFlags flags, Span<int> outIndices) => GetIndicesWithoutAllFlagsSpan(flags, outIndices);
[Obsolete("GetIndicesWithoutFlags is obsolete, please use GetIndicesWithoutAllFlags or GetIndicesWithoutAnyFlags instead", false)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public int[] GetIndicesWithoutFlags(HierarchyNodeFlags flags) => GetIndicesWithoutAllFlags(flags);
#endregion
}
}
| UnityCsReference/Modules/HierarchyCore/ScriptBindings/HierarchyViewModel.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/HierarchyCore/ScriptBindings/HierarchyViewModel.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 17541
} | 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;
using UnityEngine;
using UnityEngine.Bindings;
namespace UnityEngine
{
[ExcludeFromPreset]
[ExcludeFromObjectFactory]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[Obsolete("GUILayer has been removed.", true)]
public sealed class GUILayer
{
[Obsolete("GUILayer has been removed.", true)]
public GUIElement HitTest(Vector3 screenPosition)
{
throw new Exception("GUILayer has been removed from Unity.");
}
}
}
| UnityCsReference/Modules/IMGUI/GUILayer.deprecated.cs/0 | {
"file_path": "UnityCsReference/Modules/IMGUI/GUILayer.deprecated.cs",
"repo_id": "UnityCsReference",
"token_count": 244
} | 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 UnityEngine.Scripting;
using UnityEngine.Bindings;
namespace UnityEngine
{
// *undocumented*
[VisibleToOtherModules("UnityEngine.UIElementsModule", "UnityEditor.CoreModule")]
internal class GUILayoutGroup : GUILayoutEntry
{
public List<GUILayoutEntry> entries = new List<GUILayoutEntry>();
public bool isVertical = true; // Is this group vertical
public bool resetCoords = false; // Reset coordinate for GetRect. Used for groups that are part of a window
public float spacing = 0; // Spacing between the elements contained within
public bool sameSize = true; // Are all subelements the same size
public bool isWindow = false; // Is this a window at all?
public int windowID = -1; // Optional window ID for toplevel windows. Used by Layout to tell GUI.Window of size changes...
int m_Cursor = 0;
protected int m_StretchableCountX = 100;
protected int m_StretchableCountY = 100;
protected bool m_UserSpecifiedWidth = false;
protected bool m_UserSpecifiedHeight = false;
// Should all elements be the same size?
// TODO: implement
// bool equalSize = false;
// The summed sizes of the children. This is used to determine whether or not the children should be stretched
protected float m_ChildMinWidth = 100;
protected float m_ChildMaxWidth = 100;
protected float m_ChildMinHeight = 100;
protected float m_ChildMaxHeight = 100;
// How are subelements justified along the minor direction?
// TODO: implement
// enum Align { start, middle, end, justify }
// Align align;
protected int m_MarginLeft;
protected int m_MarginRight;
protected int m_MarginTop;
protected int m_MarginBottom;
public override int marginLeft => m_MarginLeft;
public override int marginRight => m_MarginRight;
public override int marginTop => m_MarginTop;
public override int marginBottom => m_MarginBottom;
private static readonly GUILayoutEntry none = new GUILayoutEntry(0, 1, 0, 1, GUIStyle.none);
public GUILayoutGroup() : base(0, 0, 0, 0, GUIStyle.none) {}
public GUILayoutGroup(GUIStyle _style, GUILayoutOption[] options) : base(0, 0, 0, 0, _style)
{
if (options != null)
ApplyOptions(options);
m_MarginLeft = _style.margin.left;
m_MarginRight = _style.margin.right;
m_MarginTop = _style.margin.top;
m_MarginBottom = _style.margin.bottom;
}
public override void ApplyOptions(GUILayoutOption[] options)
{
if (options == null)
return;
base.ApplyOptions(options);
foreach (GUILayoutOption i in options)
{
switch (i.type)
{
case GUILayoutOption.Type.fixedWidth:
case GUILayoutOption.Type.minWidth:
case GUILayoutOption.Type.maxWidth:
m_UserSpecifiedHeight = true;
break;
case GUILayoutOption.Type.fixedHeight:
case GUILayoutOption.Type.minHeight:
case GUILayoutOption.Type.maxHeight:
m_UserSpecifiedWidth = true;
break;
// TODO:
// case GUILayoutOption.Type.alignStart: align = Align.start; break;
// case GUILayoutOption.Type.alignMiddle: align = Align.middle; break;
// case GUILayoutOption.Type.alignEnd: align = Align.end; break;
// case GUILayoutOption.Type.alignJustify: align = Align.justify; break;
// case GUILayoutOption.Type.equalSize: equalSize = true; break;
case GUILayoutOption.Type.spacing: spacing = (int)i.value; break;
}
}
}
protected override void ApplyStyleSettings(GUIStyle style)
{
base.ApplyStyleSettings(style);
RectOffset mar = style.margin;
m_MarginLeft = mar.left;
m_MarginRight = mar.right;
m_MarginTop = mar.top;
m_MarginBottom = mar.bottom;
}
public void ResetCursor() { m_Cursor = 0; }
public Rect PeekNext()
{
if (m_Cursor < entries.Count)
{
GUILayoutEntry e = (GUILayoutEntry)entries[m_Cursor];
return e.rect;
}
if (Event.current.type == EventType.Repaint)
throw new ArgumentException("Getting control " + m_Cursor + "'s position in a group with only " + entries.Count + " controls when doing " + Event.current.rawType + "\nAborting");
return kDummyRect;
}
public GUILayoutEntry GetNext()
{
if (m_Cursor < entries.Count)
{
GUILayoutEntry e = (GUILayoutEntry)entries[m_Cursor];
m_Cursor++;
return e;
}
if (Event.current.type == EventType.Repaint)
throw new ArgumentException("Getting control " + m_Cursor + "'s position in a group with only " + entries.Count + " controls when doing " + Event.current.rawType + "\nAborting");
return none;
}
//* undocumented
public Rect GetLast()
{
if (m_Cursor == 0)
{
if (Event.current.type == EventType.Repaint)
Debug.LogError("You cannot call GetLast immediately after beginning a group.");
return kDummyRect;
}
if (m_Cursor <= entries.Count)
{
GUILayoutEntry e = (GUILayoutEntry)entries[m_Cursor - 1];
return e.rect;
}
if (Event.current.type == EventType.Repaint)
Debug.LogError("Getting control " + m_Cursor + "'s position in a group with only " + entries.Count + " controls when doing " + Event.current.rawType);
return kDummyRect;
}
public void Add(GUILayoutEntry e)
{
entries.Add(e);
}
public override void CalcWidth()
{
if (entries.Count == 0)
{
maxWidth = minWidth = style.padding.horizontal;
return;
}
int leftMarginMin = 0;
int rightMarginMin = 0;
m_ChildMinWidth = 0;
m_ChildMaxWidth = 0;
m_StretchableCountX = 0;
bool first = true;
if (isVertical)
{
foreach (GUILayoutEntry i in entries)
{
i.CalcWidth();
if (i.consideredForMargin)
{
if (!first)
{
leftMarginMin = Mathf.Min(i.marginLeft, leftMarginMin);
rightMarginMin = Mathf.Min(i.marginRight, rightMarginMin);
}
else
{
leftMarginMin = i.marginLeft;
rightMarginMin = i.marginRight;
first = false;
}
m_ChildMinWidth = Mathf.Max(i.minWidth + i.marginHorizontal, m_ChildMinWidth);
m_ChildMaxWidth = Mathf.Max(i.maxWidth + i.marginHorizontal, m_ChildMaxWidth);
}
m_StretchableCountX += i.stretchWidth;
}
// Before, we added the margins to the width, now we want to suptract them again.
m_ChildMinWidth -= leftMarginMin + rightMarginMin;
m_ChildMaxWidth -= leftMarginMin + rightMarginMin;
}
else
{
int lastMargin = 0;
foreach (GUILayoutEntry i in entries)
{
i.CalcWidth();
int margin;
if (i.consideredForMargin)
{
if (!first)
margin = lastMargin > i.marginLeft ? lastMargin : i.marginLeft;
else
{
// the first element's margins are handles _leftMarginMin and should not be added to the children's sizes
margin = 0;
first = false;
}
m_ChildMinWidth += i.minWidth + spacing + margin;
m_ChildMaxWidth += i.maxWidth + spacing + margin;
lastMargin = i.marginRight;
m_StretchableCountX += i.stretchWidth;
}
else
{
m_ChildMinWidth += i.minWidth;
m_ChildMaxWidth += i.maxWidth;
m_StretchableCountX += i.stretchWidth;
}
}
m_ChildMinWidth -= spacing;
m_ChildMaxWidth -= spacing;
if (entries.Count != 0)
{
leftMarginMin = entries[0].marginLeft;
rightMarginMin = lastMargin;
}
else
{
leftMarginMin = rightMarginMin = 0;
}
}
// Catch the cases where we have ONLY space elements in a group
// calculated padding values.
float leftPadding = 0;
float rightPadding = 0;
// If we have a style, the margins are handled i.r.t. padding.
if (style != GUIStyle.none || m_UserSpecifiedWidth)
{
// Add the padding of this group to the total min & max widths
leftPadding = Mathf.Max(style.padding.left, leftMarginMin);
rightPadding = Mathf.Max(style.padding.right, rightMarginMin);
}
else
{
// If we don't have a GUIStyle, we pop the min of margins outward from children on to us.
m_MarginLeft = leftMarginMin;
m_MarginRight = rightMarginMin;
leftPadding = rightPadding = 0;
}
// If we have a specified minwidth, take that into account...
minWidth = Mathf.Max(minWidth, m_ChildMinWidth + leftPadding + rightPadding);
if (maxWidth == 0) // if we don't have a max width, take the one that was calculated
{
stretchWidth += m_StretchableCountX + (style.stretchWidth ? 1 : 0);
maxWidth = m_ChildMaxWidth + leftPadding + rightPadding;
}
else
{
// Since we have a maximum width, this element can't stretch width.
stretchWidth = 0;
}
// Finally, if our minimum width is greater than our maximum width, minWidth wins
maxWidth = Mathf.Max(maxWidth, minWidth);
// If the style sets us to be a fixed width that wins completely
if (style.fixedWidth != 0)
{
maxWidth = minWidth = style.fixedWidth;
stretchWidth = 0;
}
}
public override void SetHorizontal(float x, float width)
{
base.SetHorizontal(x, width);
if (resetCoords)
x = 0;
RectOffset padding = style.padding;
if (isVertical)
{
// If we have a GUIStyle here, spacing from our edges to children are max (our padding, their margins)
if (style != GUIStyle.none)
{
foreach (GUILayoutEntry i in entries)
{
// NOTE: we can't use .horizontal here (As that could make things like right button margin getting eaten by large left padding - so we need to split up in left and right
float leftMar = Mathf.Max(i.marginLeft, padding.left);
float thisX = x + leftMar;
float thisWidth = width - Mathf.Max(i.marginRight, padding.right) - leftMar;
if (i.stretchWidth != 0)
i.SetHorizontal(thisX, thisWidth);
else
i.SetHorizontal(thisX, Mathf.Clamp(thisWidth, i.minWidth, i.maxWidth));
}
}
else
{
// If not, PART of the subelements' margins have already been propagated upwards to this group, so we need to subtract that from what we apply
float thisX = x - marginLeft;
float thisWidth = width + marginHorizontal;
foreach (GUILayoutEntry i in entries)
{
if (i.stretchWidth != 0)
{
i.SetHorizontal(thisX + i.marginLeft, thisWidth - i.marginHorizontal);
}
else
i.SetHorizontal(thisX + i.marginLeft, Mathf.Clamp(thisWidth - i.marginHorizontal, i.minWidth, i.maxWidth));
}
}
}
else
{ // we're horizontally laid out:
// apply margins/padding here
// If we have a style, adjust the sizing to take care of padding (if we don't the horizontal margins have been propagated fully up the hierarchy)...
if (style != GUIStyle.none)
{
float leftMar = padding.left, rightMar = padding.right;
if (entries.Count != 0)
{
leftMar = Mathf.Max(leftMar, entries[0].marginLeft);
rightMar = Mathf.Max(rightMar, entries[entries.Count - 1].marginRight);
}
x += leftMar;
width -= rightMar + leftMar;
}
// Find out how much leftover width we should distribute.
float widthToDistribute = width - spacing * (entries.Count - 1);
// Where to place us in height between min and max
float minMaxScale = 0;
// How much height to add to stretchable elements
if (m_ChildMinWidth != m_ChildMaxWidth)
minMaxScale = Mathf.Clamp((widthToDistribute - m_ChildMinWidth) / (m_ChildMaxWidth - m_ChildMinWidth), 0, 1);
// Handle stretching
float perItemStretch = 0;
if (widthToDistribute > m_ChildMaxWidth) // If we have too much space, we need to distribute it.
{
if (m_StretchableCountX > 0)
{
perItemStretch = (widthToDistribute - m_ChildMaxWidth) / (float)m_StretchableCountX;
}
}
// Set the positions
int lastMargin = 0;
bool firstMargin = true;
// Debug.Log ("" + x + ", " + width + " perItemStretch:" + perItemStretch);
// Debug.Log ("MinMaxScale"+ minMaxScale);
foreach (GUILayoutEntry i in entries)
{
float thisWidth = Mathf.Lerp(i.minWidth, i.maxWidth, minMaxScale);
// Debug.Log (i.minWidth);
thisWidth += perItemStretch * i.stretchWidth;
if (i.consideredForMargin) // Skip margins on spaces.
{
int leftMargin = i.marginLeft;
if (firstMargin)
{
leftMargin = 0;
firstMargin = false;
}
int margin = lastMargin > leftMargin ? lastMargin : leftMargin;
x += margin;
lastMargin = i.marginRight;
}
i.SetHorizontal(Mathf.Round(x), Mathf.Round(thisWidth));
x += thisWidth + spacing;
}
}
}
public override void CalcHeight()
{
if (entries.Count == 0)
{
maxHeight = minHeight = style.padding.vertical;
return;
}
int topMarginMin = 0;
int bottomMarginMin = 0;
m_ChildMinHeight = 0;
m_ChildMaxHeight = 0;
m_StretchableCountY = 0;
if (isVertical)
{
int lastMargin = 0;
bool first = true;
foreach (GUILayoutEntry i in entries)
{
i.CalcHeight();
int margin;
if (i.consideredForMargin)
{
if (!first)
margin = Mathf.Max(lastMargin, i.marginTop);
else
{
margin = 0;
first = false;
}
m_ChildMinHeight += i.minHeight + spacing + margin;
m_ChildMaxHeight += i.maxHeight + spacing + margin;
lastMargin = i.marginBottom;
m_StretchableCountY += i.stretchHeight;
}
else
{
m_ChildMinHeight += i.minHeight;
m_ChildMaxHeight += i.maxHeight;
m_StretchableCountY += i.stretchHeight;
}
}
m_ChildMinHeight -= spacing;
m_ChildMaxHeight -= spacing;
if (entries.Count != 0)
{
topMarginMin = entries[0].marginTop;
bottomMarginMin = lastMargin;
}
else
{
bottomMarginMin = topMarginMin = 0;
}
}
else
{
bool first = true;
foreach (GUILayoutEntry i in entries)
{
i.CalcHeight();
if (i.consideredForMargin)
{
if (!first)
{
topMarginMin = Mathf.Min(i.marginTop, topMarginMin);
bottomMarginMin = Mathf.Min(i.marginBottom, bottomMarginMin);
}
else
{
topMarginMin = i.marginTop;
bottomMarginMin = i.marginBottom;
first = false;
}
m_ChildMinHeight = Mathf.Max(i.minHeight, m_ChildMinHeight);
m_ChildMaxHeight = Mathf.Max(i.maxHeight, m_ChildMaxHeight);
}
m_StretchableCountY += i.stretchHeight;
}
}
float firstPadding = 0;
float lastPadding = 0;
// If we have a style, the margins are handled i.r.t. padding.
if (style != GUIStyle.none || m_UserSpecifiedHeight)
{
// Add the padding of this group to the total min & max widths
firstPadding = Mathf.Max(style.padding.top, topMarginMin);
lastPadding = Mathf.Max(style.padding.bottom, bottomMarginMin);
}
else
{
// If we don't have a GUIStyle, we bubble the margins outward from children on to us.
m_MarginTop = topMarginMin;
m_MarginBottom = bottomMarginMin;
firstPadding = lastPadding = 0;
}
//Debug.Log ("Margins: " + _topMarginMin + ", " + _bottomMarginMin + " childHeights:" + childMinHeight + ", " + childMaxHeight);
// If we have a specified minheight, take that into account...
minHeight = Mathf.Max(minHeight, m_ChildMinHeight + firstPadding + lastPadding);
if (maxHeight == 0) // if we don't have a max height, take the one that was calculated
{
stretchHeight += m_StretchableCountY + (style.stretchHeight ? 1 : 0);
maxHeight = m_ChildMaxHeight + firstPadding + lastPadding;
}
else
{
// Since we have a maximum height, this element can't stretch height.
stretchHeight = 0;
}
// Finally, if out minimum height is greater than our maximum height, minHeight wins
maxHeight = Mathf.Max(maxHeight, minHeight);
// If the style sets us to be a fixed height
if (style.fixedHeight != 0)
{
maxHeight = minHeight = style.fixedHeight;
stretchHeight = 0;
}
}
public override void SetVertical(float y, float height)
{
base.SetVertical(y, height);
if (entries.Count == 0)
return;
RectOffset padding = style.padding;
if (resetCoords)
y = 0;
if (isVertical)
{
// If we have a skin, adjust the sizing to take care of padding (if we don't have a skin the vertical margins have been propagated fully up the hierarchy)...
if (style != GUIStyle.none)
{
float topMar = padding.top, bottomMar = padding.bottom;
if (entries.Count != 0)
{
topMar = Mathf.Max(topMar, entries[0].marginTop);
bottomMar = Mathf.Max(bottomMar, entries[entries.Count - 1].marginBottom);
}
y += topMar;
height -= bottomMar + topMar;
}
// Find out how much leftover height we should distribute.
float heightToDistribute = height - spacing * (entries.Count - 1);
// Where to place us in height between min and max
float minMaxScale = 0;
// How much height to add to stretchable elements
if (m_ChildMinHeight != m_ChildMaxHeight)
minMaxScale = Mathf.Clamp((heightToDistribute - m_ChildMinHeight) / (m_ChildMaxHeight - m_ChildMinHeight), 0, 1);
// Handle stretching
float perItemStretch = 0;
if (heightToDistribute > m_ChildMaxHeight) // If we have too much space - stretch any stretchable children
{
if (m_StretchableCountY > 0)
perItemStretch = (heightToDistribute - m_ChildMaxHeight) / (float)m_StretchableCountY;
}
// Set the positions
int lastMargin = 0;
bool firstMargin = true;
foreach (GUILayoutEntry i in entries)
{
float thisHeight = Mathf.Lerp(i.minHeight, i.maxHeight, minMaxScale);
thisHeight += perItemStretch * i.stretchHeight;
if (i.consideredForMargin)
{ // Skip margins on spaces.
int topMargin = i.marginTop;
if (firstMargin)
{
topMargin = 0;
firstMargin = false;
}
int margin = lastMargin > topMargin ? lastMargin : topMargin;
y += margin;
lastMargin = i.marginBottom;
}
i.SetVertical(Mathf.Round(y), Mathf.Round(thisHeight));
y += thisHeight + spacing;
}
}
else
{
// If we have a GUIStyle here, we need to respect the subelements' margins
if (style != GUIStyle.none)
{
foreach (GUILayoutEntry i in entries)
{
float topMar = Mathf.Max(i.marginTop, padding.top);
float thisY = y + topMar;
float thisHeight = height - Mathf.Max(i.marginBottom, padding.bottom) - topMar;
if (i.stretchHeight != 0)
i.SetVertical(thisY, thisHeight);
else
i.SetVertical(thisY, Mathf.Clamp(thisHeight, i.minHeight, i.maxHeight));
}
}
else
{
// If not, the subelements' margins have already been propagated upwards to this group, so we can safely ignore them
float thisY = y - marginTop;
float thisHeight = height + marginVertical;
foreach (GUILayoutEntry i in entries)
{
if (i.stretchHeight != 0)
i.SetVertical(thisY + i.marginTop, thisHeight - i.marginVertical);
else
i.SetVertical(thisY + i.marginTop, Mathf.Clamp(thisHeight - i.marginVertical, i.minHeight, i.maxHeight));
}
}
}
}
public override string ToString()
{
string str = "", space = "";
for (int i = 0; i < indent; i++)
space += " ";
str += /* space + */ base.ToString() + " Margins: " + m_ChildMinHeight + " {\n";
indent += 4;
foreach (GUILayoutEntry i in entries)
{
str += i + "\n";
}
str += space + "}";
indent -= 4;
return str;
}
}
// Layout controller for content inside scroll views
internal sealed class GUIScrollGroup : GUILayoutGroup
{
public float calcMinWidth, calcMaxWidth, calcMinHeight, calcMaxHeight;
public float clientWidth, clientHeight;
public bool allowHorizontalScroll = true;
public bool allowVerticalScroll = true;
public bool needsHorizontalScrollbar, needsVerticalScrollbar;
public GUIStyle horizontalScrollbar, verticalScrollbar;
[RequiredByNativeCode] // Created by reflection from GUILayout.BeginScrollView
public GUIScrollGroup() {}
public override void CalcWidth()
{
// Save the size values & reset so we calc the sizes of children without any contraints
float _minWidth = minWidth;
float _maxWidth = maxWidth;
if (allowHorizontalScroll)
{
minWidth = 0;
maxWidth = 0;
}
base.CalcWidth();
calcMinWidth = minWidth;
calcMaxWidth = maxWidth;
// restore the stored constraints for our parent's sizing
if (allowHorizontalScroll)
{
// Set an explicit small minWidth so it will correctly scroll when place inside horizontal groups
if (minWidth > 32)
minWidth = 32;
if (_minWidth != 0)
minWidth = _minWidth;
if (_maxWidth != 0)
{
maxWidth = _maxWidth;
stretchWidth = 0;
}
}
}
public override void SetHorizontal(float x, float width)
{
float _cWidth = needsVerticalScrollbar ? width - verticalScrollbar.fixedWidth - verticalScrollbar.margin.left : width;
//if (allowVerticalScroll == false)
// Debug.Log ("width " + width);
// If we get a vertical scrollbar, the width changes, so we need to do a recalculation with the new width.
if (allowHorizontalScroll && _cWidth < calcMinWidth)
{
// We're too small horizontally, so we need a horizontal scrollbar.
needsHorizontalScrollbar = true;
// set the min and max width we calculated for the children so SetHorizontal works correctly
minWidth = calcMinWidth;
maxWidth = calcMaxWidth;
base.SetHorizontal(x, calcMinWidth);
// SetHorizontal also sets our width, but we know better
rect.width = width;
clientWidth = calcMinWidth;
}
else
{
// Got enough space.
needsHorizontalScrollbar = false;
// set the min and max width we calculated for the children so SetHorizontal works correctly
if (allowHorizontalScroll)
{
minWidth = calcMinWidth;
maxWidth = calcMaxWidth;
}
base.SetHorizontal(x, _cWidth);
rect.width = width;
// Store the client width
clientWidth = _cWidth;
}
}
public override void CalcHeight()
{
// Save the values & reset so we calc the sizes of children without any contraints
float _minHeight = minHeight;
float _maxHeight = maxHeight;
if (allowVerticalScroll)
{
minHeight = 0;
maxHeight = 0;
}
base.CalcHeight();
calcMinHeight = minHeight;
calcMaxHeight = maxHeight;
// if we KNOW we need a horizontal scrollbar, claim space for it now
// otherwise we get a vertical scrollbar and leftover space beneath the scrollview.
if (needsHorizontalScrollbar)
{
float scrollerSize = horizontalScrollbar.fixedHeight + horizontalScrollbar.margin.top;
minHeight += scrollerSize;
maxHeight += scrollerSize;
}
// restore the stored constraints from user SetHeight calls.
if (allowVerticalScroll)
{
if (minHeight > 32)
minHeight = 32;
if (_minHeight != 0)
minHeight = _minHeight;
if (_maxHeight != 0)
{
maxHeight = _maxHeight;
stretchHeight = 0;
}
}
}
public override void SetVertical(float y, float height)
{
// if we have a horizontal scrollbar, we have less space than we thought
float availableHeight = height;
if (needsHorizontalScrollbar)
availableHeight -= horizontalScrollbar.fixedHeight + horizontalScrollbar.margin.top;
// Now we know how much height we have, and hence how much vertical space to distribute.
// If we get a vertical scrollbar, the width changes, so we need to do a recalculation with the new width.
if (allowVerticalScroll && availableHeight < calcMinHeight)
{
// We're too small vertically, so we need a vertical scrollbar.
// This means that we have less horizontal space, which can change the vertical size.
if (!needsHorizontalScrollbar && !needsVerticalScrollbar)
{
// Subtract scrollbar width from the size...
clientWidth = rect.width - verticalScrollbar.fixedWidth - verticalScrollbar.margin.left;
// ...But make sure we never get too small.
if (clientWidth < calcMinWidth)
clientWidth = calcMinWidth;
// Set the new (smaller) size.
float outsideWidth = rect.width; // store a backup of our own width
SetHorizontal(rect.x, clientWidth);
// This can have caused a reflow, so we need to recalclate from here on down
// (we already know we need a vertical scrollbar, so this size change cannot bubble upwards.
CalcHeight();
rect.width = outsideWidth;
}
// set the min and max height we calculated for the children so SetVertical works correctly
float origMinHeight = minHeight, origMaxHeight = maxHeight;
minHeight = calcMinHeight;
maxHeight = calcMaxHeight;
base.SetVertical(y, calcMinHeight);
minHeight = origMinHeight;
maxHeight = origMaxHeight;
rect.height = height;
clientHeight = calcMinHeight;
}
else
{
// set the min and max height we calculated for the children so SetVertical works correctly
if (allowVerticalScroll)
{
minHeight = calcMinHeight;
maxHeight = calcMaxHeight;
}
base.SetVertical(y, availableHeight);
rect.height = height;
clientHeight = availableHeight;
}
}
}
}
| UnityCsReference/Modules/IMGUI/LayoutGroup.cs/0 | {
"file_path": "UnityCsReference/Modules/IMGUI/LayoutGroup.cs",
"repo_id": "UnityCsReference",
"token_count": 18261
} | 388 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using Unity.IntegerTime;
namespace UnityEngine.InputForUI
{
/// <summary>
/// Common properties that should be implemented by all events
/// </summary>
internal interface IEventProperties
{
/// <summary>
/// Timestamp when the event happened
/// </summary>
public DiscreteTime timestamp { get; }
/// <summary>
/// Event source for the current event.
/// Could be used in various ways,
/// one use case in UITK is to ignore navigation events coming from keyboard when we're focused on text field.
/// </summary>
public EventSource eventSource { get; }
/// <summary>
/// Player Id for split-screen multiplayer scenario. Events associated with specific player will be marked with player id.
/// From [0, EventProvider.playerCount)
/// </summary>
public uint playerId { get; }
/// <summary>
/// State of keyboard modifiers when the event happened.
/// </summary>
public EventModifiers eventModifiers { get; }
}
}
| UnityCsReference/Modules/InputForUI/Events/IEventProperties.cs/0 | {
"file_path": "UnityCsReference/Modules/InputForUI/Events/IEventProperties.cs",
"repo_id": "UnityCsReference",
"token_count": 427
} | 389 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine.Bindings;
namespace UnityEngine
{
[NativeHeader("Modules/JSONSerialize/Public/JsonUtility.bindings.h")]
public static class JsonUtility
{
[FreeFunction("ToJsonInternal", true)]
[ThreadSafe]
private static extern string ToJsonInternal([NotNull] object obj, bool prettyPrint);
[FreeFunction("FromJsonInternal", true, ThrowsException = true)]
[ThreadSafe]
private static extern object FromJsonInternal(string json, object objectToOverwrite, Type type);
public static string ToJson(object obj) { return ToJson(obj, false); }
public static string ToJson(object obj, bool prettyPrint)
{
if (obj == null)
return "";
if (obj is UnityEngine.Object && !(obj is MonoBehaviour || obj is ScriptableObject))
throw new ArgumentException("JsonUtility.ToJson does not support engine types.");
return ToJsonInternal(obj, prettyPrint);
}
public static T FromJson<T>(string json) { return (T)FromJson(json, typeof(T)); }
public static object FromJson(string json, Type type)
{
if (string.IsNullOrEmpty(json))
return null;
if (type == null)
throw new ArgumentNullException("type");
if (type.IsAbstract || type.IsSubclassOf(typeof(UnityEngine.Object)))
throw new ArgumentException("Cannot deserialize JSON to new instances of type '" + type.Name + ".'");
return FromJsonInternal(json, null, type);
}
public static void FromJsonOverwrite(string json, object objectToOverwrite)
{
if (string.IsNullOrEmpty(json))
return;
if (objectToOverwrite == null)
throw new ArgumentNullException("objectToOverwrite");
if (objectToOverwrite is UnityEngine.Object && !(objectToOverwrite is MonoBehaviour || objectToOverwrite is ScriptableObject))
throw new ArgumentException("Engine types cannot be overwritten from JSON outside of the Editor.");
FromJsonInternal(json, objectToOverwrite, objectToOverwrite.GetType());
}
}
}
| UnityCsReference/Modules/JSONSerialize/Public/JsonUtility.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/JSONSerialize/Public/JsonUtility.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 946
} | 390 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEditor.Licensing.UI.Events.Text;
namespace UnityEditor.Licensing.UI.Events.Buttons;
sealed class OkButton : TemplateEventsButton
{
INativeApiWrapper m_NativeApiWrapper;
Action m_CloseAction;
public OkButton(Action closeAction, Action additionalClickAction, INativeApiWrapper nativeApiWrapper)
: base(LicenseTrStrings.BtnOk, additionalClickAction)
{
m_NativeApiWrapper = nativeApiWrapper;
m_CloseAction = closeAction;
}
protected override void Click()
{
m_CloseAction?.Invoke();
m_NativeApiWrapper.InvokeLicenseUpdateCallbacks();
}
}
| UnityCsReference/Modules/Licensing/UI/Events/Buttons/OkButton.cs/0 | {
"file_path": "UnityCsReference/Modules/Licensing/UI/Events/Buttons/OkButton.cs",
"repo_id": "UnityCsReference",
"token_count": 283
} | 391 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEditor.Licensing.UI.Data.Events;
using UnityEditor.Licensing.UI.Events.Buttons;
using UnityEditor.Licensing.UI.Events.Text;
using UnityEditor.Licensing.UI.Helper;
using UnityEngine;
namespace UnityEditor.Licensing.UI.Events.Windows;
class LicenseExpiredWindow : TemplateLicenseEventWindow
{
public static void ShowWindow(INativeApiWrapper nativeApiWrapper, ILicenseLogger licenseLogger, object notification)
{
s_NativeApiWrapper = nativeApiWrapper;
s_Notification = notification as LicenseExpiredNotification;
s_LicenseLogger = licenseLogger;
TemplateLicenseEventWindow.ShowWindow<LicenseExpiredWindow>(LicenseTrStrings.ExpiredWindowTitle, true);
}
public void CreateGUI()
{
s_Root = new LicenseExpiredWindowContents(s_NativeApiWrapper.HasUiEntitlement(),
(LicenseExpiredNotification)s_Notification,
new EventsButtonFactory(s_NativeApiWrapper, Close),
s_LicenseLogger);
rootVisualElement.Add(s_Root);
}
}
| UnityCsReference/Modules/Licensing/UI/Events/Windows/LicenseExpiredWindow.cs/0 | {
"file_path": "UnityCsReference/Modules/Licensing/UI/Events/Windows/LicenseExpiredWindow.cs",
"repo_id": "UnityCsReference",
"token_count": 415
} | 392 |
// 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.Helper;
using UnityEngine;
namespace UnityEditor.Licensing.UI;
class LicenseLogger : ILicenseLogger
{
const string k_Tag = "License";
const string k_TagFormat = "{0}: {1}";
public void DebugLogNoStackTrace(string message, LogType logType, string tag = k_Tag)
{
Debug.LogFormat(logType, LogOption.NoStacktrace, null, k_TagFormat, tag, message);
}
public void LogError(string message)
{
Debug.LogError(message);
}
}
| UnityCsReference/Modules/Licensing/UI/Helper/LicenseLogger.cs/0 | {
"file_path": "UnityCsReference/Modules/Licensing/UI/Helper/LicenseLogger.cs",
"repo_id": "UnityCsReference",
"token_count": 230
} | 393 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute;
namespace UnityEditor.PackageManager
{
public static class Events
{
public static event Action<PackageRegistrationEventArgs> registeringPackages;
public static event Action<PackageRegistrationEventArgs> registeredPackages;
[RequiredByNativeCode]
internal static void InvokeRegisteringPackages(PackageRegistrationEventArgs eventArgs)
{
registeringPackages?.Invoke(eventArgs);
}
[RequiredByNativeCode]
internal static void InvokeRegisteredPackages(PackageRegistrationEventArgs eventArgs)
{
registeredPackages?.Invoke(eventArgs);
}
}
}
| UnityCsReference/Modules/PackageManager/Editor/Managed/Events.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManager/Editor/Managed/Events.cs",
"repo_id": "UnityCsReference",
"token_count": 303
} | 394 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine;
namespace UnityEditor.PackageManager.Requests
{
[Serializable]
internal sealed partial class PerformSearchRequest : Request<SearchResults>
{
/// <summary>
/// Constructor to support serialization
/// </summary>
private PerformSearchRequest()
{
}
internal PerformSearchRequest(long operationId, NativeStatusCode initialStatus)
: base(operationId, initialStatus)
{
}
protected override SearchResults GetResult()
{
return GetOperationData(Id);
}
}
}
| UnityCsReference/Modules/PackageManager/Editor/Managed/Requests/PerformSearchRequest.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManager/Editor/Managed/Requests/PerformSearchRequest.cs",
"repo_id": "UnityCsReference",
"token_count": 289
} | 395 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.Bindings;
using UnityEngine.Scripting;
namespace UnityEditor.PackageManager
{
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[RequiredByNativeCode]
[NativeAsStruct]
internal class SignatureInfo
{
[SerializeField]
[NativeName("status")]
private SignatureStatus m_Status;
[SerializeField]
[NativeName("reason")]
private string m_Reason;
public SignatureStatus status => m_Status;
public string reason => m_Reason;
internal SignatureInfo() : this(SignatureStatus.Unchecked, "") {}
internal SignatureInfo(SignatureStatus status, string reason)
{
m_Status = status;
m_Reason = reason;
}
}
}
| UnityCsReference/Modules/PackageManager/Editor/Managed/SignatureInfo.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManager/Editor/Managed/SignatureInfo.cs",
"repo_id": "UnityCsReference",
"token_count": 369
} | 396 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine.Analytics;
namespace UnityEditor.PackageManager.UI.Internal
{
[AnalyticInfo(eventName: k_EventName, vendorKey: k_VendorKey)]
internal class PackageManagerDialogAnalytics : IAnalytic
{
private const string k_EventName = "packageManagerDialogs";
private const string k_VendorKey = "unity.package-manager-ui";
[Serializable]
private class Data : IAnalytic.IData
{
public string id;
public string title;
public string message;
public string user_response;
}
private Data m_Data;
private PackageManagerDialogAnalytics(string id, string title, string message, string userResponse)
{
m_Data = new Data
{
id = id,
title = title,
message = message,
user_response = userResponse
};
}
public bool TryGatherData(out IAnalytic.IData data, out Exception error)
{
data = m_Data;
error = null;
return m_Data != null;
}
public static void SendEvent(string id, string title, string message, string userResponse)
{
var editorAnalyticsProxy = ServicesContainer.instance.Resolve<IEditorAnalyticsProxy>();
editorAnalyticsProxy.SendAnalytic(new PackageManagerDialogAnalytics(id, title, message, userResponse));
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Analytics/PackageManagerDialogAnalytics.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Analytics/PackageManagerDialogAnalytics.cs",
"repo_id": "UnityCsReference",
"token_count": 687
} | 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.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace UnityEditor.PackageManager.UI.Internal
{
internal interface IAssetStorePackageInstaller : IService
{
void Install(long productId, bool interactiveInstall = false);
void Uninstall(long productId, bool interactiveUninstall = false);
void Uninstall(IEnumerable<long> productIds);
}
internal class AssetStorePackageInstaller : BaseService<IAssetStorePackageInstaller>, IAssetStorePackageInstaller
{
private readonly IIOProxy m_IOProxy;
private readonly IAssetStoreCache m_AssetStoreCache;
private readonly IAssetDatabaseProxy m_AssetDatabase;
private readonly IAssetSelectionHandler m_AssetSelectionHandler;
private readonly IApplicationProxy m_Application;
public AssetStorePackageInstaller(IIOProxy ioProxy,
IAssetStoreCache assetStoreCache,
IAssetDatabaseProxy assetDatabaseProxy,
IAssetSelectionHandler assetSelectionHandler,
IApplicationProxy applicationProxy)
{
m_IOProxy = RegisterDependency(ioProxy);
m_AssetStoreCache = RegisterDependency(assetStoreCache);
m_AssetDatabase = RegisterDependency(assetDatabaseProxy);
m_AssetSelectionHandler = RegisterDependency(assetSelectionHandler);
m_Application = RegisterDependency(applicationProxy);
}
public override void OnEnable()
{
m_AssetSelectionHandler.onRemoveSelectionDone += OnRemoveSelectionDone;
}
public override void OnDisable()
{
m_AssetSelectionHandler.onRemoveSelectionDone -= OnRemoveSelectionDone;
}
public void Install(long productId, bool interactiveInstall = false)
{
var localInfo = m_AssetStoreCache.GetLocalInfo(productId);
try
{
if (string.IsNullOrEmpty(localInfo?.packagePath) || !m_IOProxy.FileExists(localInfo.packagePath))
return;
var assetOrigin = new AssetOrigin((int)localInfo.productId, localInfo.title, localInfo.versionString, (int)localInfo.uploadId);
m_AssetDatabase.ImportPackage(localInfo.packagePath, assetOrigin, interactiveInstall);
}
catch (System.IO.IOException e)
{
Debug.Log($"[Package Manager Window] Cannot import package {localInfo?.title}: {e.Message}");
}
}
private void RemoveAssetsAndCleanUpEmptyFolders(IEnumerable<Asset> assets)
{
const string assetsPath = "Assets";
var foldersToRemove = new HashSet<string>();
foreach (var asset in assets)
{
var path = m_IOProxy.GetParentDirectory(asset.importedPath);
// We want to add an asset's parent folders all the way up to the `Assets` folder, because we don't want to leave behind
// empty folders after the assets are removed process.
while (!foldersToRemove.Contains(path) && path.StartsWith(assetsPath) && path.Length > assetsPath.Length)
{
foldersToRemove.Add(path);
path = m_IOProxy.GetParentDirectory(path);
}
}
var searchInFoldersFilter = new SearchFilter
{
folders = foldersToRemove.ToArray(),
searchArea = SearchFilter.SearchArea.SelectedFolders
};
var leftOverAssetsGuids = m_AssetDatabase.FindAssets(searchInFoldersFilter).ToHashSet();
foreach (var guid in assets.Select(i => i.guid).Concat(foldersToRemove.Select(i => m_AssetDatabase.AssetPathToGUID(i))))
leftOverAssetsGuids.Remove(guid);
foreach (var assetPath in leftOverAssetsGuids.Select(i => m_AssetDatabase.GUIDToAssetPath(i)))
{
var path = m_IOProxy.GetParentDirectory(assetPath);
// If after the removal process, there will still be some assets left behind, we want to make sure the folders containing
// left over assets are not removed
while (foldersToRemove.Contains(path))
{
foldersToRemove.Remove(path);
path = m_IOProxy.GetParentDirectory(path);
}
}
// We order the folders to be removed so that child folders always come before their parent folders
// This way m_AssetDatabase.DeleteAssets call won't try to remove parent folders first and fail to remove child folders
var orderedFoldersToRemove = foldersToRemove.OrderByDescending(i => i);
var assetAndFoldersToRemove = assets.Select(i => i.importedPath).Concat(orderedFoldersToRemove).ToArray();
var pathsFailedToRemove = new List<string>();
m_AssetDatabase.DeleteAssets(assetAndFoldersToRemove, pathsFailedToRemove);
if (pathsFailedToRemove.Any())
{
var errorMessage = L10n.Tr("[Package Manager Window] Failed to remove the following asset(s) and/or folder(s):");
foreach (var path in pathsFailedToRemove)
errorMessage += "\n" + path;
Debug.LogError(errorMessage);
m_Application.DisplayDialog("cannotRemoveAsset",
L10n.Tr("Cannot Remove"),
L10n.Tr("Some assets could not be deleted.\nMake sure nothing is keeping a hook on them, like a loaded DLL for example."),
L10n.Tr("Ok"));
}
}
public void Uninstall(long productId, bool interactiveUninstall = false)
{
if (interactiveUninstall)
{
var importedPackage = m_AssetStoreCache.GetImportedPackage(productId);
m_AssetSelectionHandler.Remove(importedPackage, importedPackage.displayName, importedPackage.versionString);
}
else
{
var importedPackage = m_AssetStoreCache.GetImportedPackage(productId);
if (importedPackage != null)
RemoveAssetsAndCleanUpEmptyFolders(importedPackage);
}
}
public void Uninstall(IEnumerable<long> productIds)
{
var assetsToRemove = new List<Asset>();
foreach (var productId in productIds ?? Enumerable.Empty<long>())
{
var importedPackage = m_AssetStoreCache.GetImportedPackage(productId);
if (importedPackage != null)
assetsToRemove.AddRange(importedPackage);
}
if (assetsToRemove.Any())
RemoveAssetsAndCleanUpEmptyFolders(assetsToRemove);
}
private void OnRemoveSelectionDone(IEnumerable<Asset> selections)
{
if (selections.Any())
RemoveAssetsAndCleanUpEmptyFolders(selections);
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/AssetStore/AssetStorePackageInstaller.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/AssetStore/AssetStorePackageInstaller.cs",
"repo_id": "UnityCsReference",
"token_count": 3124
} | 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;
namespace UnityEditor.PackageManager.UI.Internal
{
internal interface IFetchStatusTracker : IService
{
event Action<FetchStatus> onFetchStatusChanged;
IEnumerable<FetchStatus> fetchStatuses { get; }
FetchStatus GetOrCreateFetchStatus(long productId);
void SetFetchInProgress(long productId, FetchType fetchType);
void SetFetchSuccess(long productId, FetchType fetchType);
void SetFetchError(long productId, FetchType fetchType, UIError error);
void ClearCache();
}
[Flags]
internal enum FetchType
{
None = 0,
ProductInfo = 1 << 0,
ProductSearchInfo = 1 << 1,
}
[Serializable]
internal class FetchError
{
public FetchType fetchType;
public UIError error;
}
[Serializable]
internal class FetchStatus
{
public long productId;
public FetchType fetchingInProgress;
public FetchType fetchingFinished;
public List<FetchError> errors;
public FetchStatus(long productId)
{
this.productId = productId;
fetchingInProgress = FetchType.None;
fetchingFinished = FetchType.None;
errors = new List<FetchError>();
}
public bool IsFetchInProgress(FetchType fetchType) => (fetchingInProgress & fetchType) != 0;
public FetchError GetFetchError(FetchType fetchType) => errors.FirstOrDefault(error => (error.fetchType & fetchType) != 0);
}
[Serializable]
internal class FetchStatusTracker : BaseService<IFetchStatusTracker>, IFetchStatusTracker, ISerializationCallbackReceiver
{
private Dictionary<long, FetchStatus> m_FetchStatuses = new Dictionary<long, FetchStatus>();
public IEnumerable<FetchStatus> fetchStatuses => m_FetchStatuses.Values;
public event Action<FetchStatus> onFetchStatusChanged;
[SerializeField]
private FetchStatus[] m_SerializedFetchStatuses = new FetchStatus[0];
public FetchStatus GetOrCreateFetchStatus(long productId)
{
var status = m_FetchStatuses.Get(productId);
if (status == null)
{
status = new FetchStatus(productId);
m_FetchStatuses[productId] = status;
}
return status;
}
public void SetFetchInProgress(long productId, FetchType fetchType)
{
var status = GetOrCreateFetchStatus(productId);
status.fetchingInProgress |= fetchType;
onFetchStatusChanged?.Invoke(status);
}
public void SetFetchSuccess(long productId, FetchType fetchType)
{
var status = GetOrCreateFetchStatus(productId);
status.fetchingInProgress &= ~fetchType;
status.fetchingFinished |= fetchType;
status.errors.RemoveAll(e => e.fetchType == fetchType);
onFetchStatusChanged?.Invoke(status);
}
public void SetFetchError(long productId, FetchType fetchType, UIError error)
{
var status = GetOrCreateFetchStatus(productId);
status.fetchingInProgress &= ~fetchType;
status.fetchingFinished |= fetchType;
status.errors.Add(new FetchError { fetchType = fetchType, error = error });
onFetchStatusChanged?.Invoke(status);
}
public void ClearCache()
{
m_FetchStatuses.Clear();
}
public void OnBeforeSerialize()
{
m_SerializedFetchStatuses = m_FetchStatuses.Values.ToArray();
}
public void OnAfterDeserialize()
{
m_FetchStatuses = m_SerializedFetchStatuses.ToDictionary(status => status.productId, status => status);
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Common/FetchStatusTracker.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Common/FetchStatusTracker.cs",
"repo_id": "UnityCsReference",
"token_count": 1744
} | 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;
namespace UnityEditor.PackageManager.UI.Internal
{
internal interface IOperation
{
event Action<IOperation, UIError> onOperationError;
event Action<IOperation> onOperationSuccess;
event Action<IOperation> onOperationFinalized;
// `onOperationProgress` will only be triggered if `isProgressTrackable` is true
event Action<IOperation> onOperationProgress;
string packageUniqueId { get; }
long productId { get; }
// a timestamp is added to keep track of how `fresh` the result is
// in the case of an online operation, it is the time when the operation starts
// in the case of an offline operation, it is set to the timestamp of the last online operation
long timestamp { get; }
long lastSuccessTimestamp { get; }
bool isOfflineMode { get; }
bool isInProgress { get; }
bool isInPause { get; }
bool isProgressVisible { get; }
bool isProgressTrackable { get; }
// returns a value in the range of [0, 1]
// if the operation's progress is not trackable, 0 will be returned
float progressPercentage { get; }
RefreshOptions refreshOptions { get; }
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Interfaces/IOperation.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Interfaces/IOperation.cs",
"repo_id": "UnityCsReference",
"token_count": 488
} | 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 ImportNewAction : ImportActionBase
{
public ImportNewAction(IPackageOperationDispatcher operationDispatcher, IAssetStoreDownloadManager assetStoreDownloadManager, IApplicationProxy application, IUnityConnectProxy unityConnect)
: base(operationDispatcher, assetStoreDownloadManager, application, unityConnect)
{
}
protected override string analyticEventName => "importNew";
public override bool isRecommended => true;
public override Icon icon => Icon.Import;
protected override bool TriggerActionImplementation(IPackageVersion version)
{
m_OperationDispatcher.Import(version.package);
PackageManagerWindowAnalytics.SendEvent("importNew", version);
return true;
}
public override bool IsVisible(IPackageVersion version)
{
return base.IsVisible(version) && version.package.versions.imported == null;
}
public override string GetTooltip(IPackageVersion version, bool isInProgress)
{
return string.Format(L10n.Tr("Click to import assets from the {0} into your project."), version.GetDescriptor());
}
public override string GetText(IPackageVersion version, bool isInProgress)
{
return !string.IsNullOrEmpty(version?.versionString) ? string.Format(L10n.Tr("Import {0} to project"), version.versionString) : L10n.Tr("Import");
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/Actions/ImportNewAction.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/Actions/ImportNewAction.cs",
"repo_id": "UnityCsReference",
"token_count": 488
} | 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;
namespace UnityEditor.PackageManager.UI.Internal
{
[Serializable]
internal class PackageImage
{
public enum ImageType
{
Main,
Screenshot,
Sketchfab,
Youtube,
Vimeo
}
public ImageType type;
public string thumbnailUrl;
public string url;
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/PackageImage.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/PackageImage.cs",
"repo_id": "UnityCsReference",
"token_count": 232
} | 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;
using System.Diagnostics.CodeAnalysis;
using UnityEngine;
namespace UnityEditor.PackageManager.UI.Internal
{
internal interface IPageFactory : IService
{
IPage CreatePageFromId(string pageId);
IPage CreateExtensionPage(ExtensionPageArgs args);
IPage CreateScopedRegistryPage(RegistryInfo registryInfo);
void ResolveDependenciesForPage(IPage page);
}
internal class PageFactory : BaseService<IPageFactory>, IPageFactory
{
private readonly IUnityConnectProxy m_UnityConnect;
private readonly IPackageManagerPrefs m_PackageManagerPrefs;
private readonly IAssetStoreClient m_AssetStoreClient;
private readonly IPackageDatabase m_PackageDatabase;
private readonly IUpmCache m_UpmCache;
[ExcludeFromCodeCoverage]
public PageFactory(IUnityConnectProxy unityConnect,
IPackageManagerPrefs packageManagerPrefs,
IAssetStoreClient assetStoreClient,
IPackageDatabase packageDatabase,
IUpmCache upmCache)
{
m_UnityConnect = RegisterDependency(unityConnect);
m_PackageManagerPrefs = RegisterDependency(packageManagerPrefs);
m_AssetStoreClient = RegisterDependency(assetStoreClient);
m_PackageDatabase = RegisterDependency(packageDatabase);
m_UpmCache = RegisterDependency(upmCache);
}
public IPage CreatePageFromId(string pageId)
{
return pageId switch
{
UnityRegistryPage.k_Id => new UnityRegistryPage(m_PackageDatabase),
InProjectPage.k_Id => new InProjectPage(m_PackageDatabase),
InProjectUpdatesPage.k_Id => new InProjectUpdatesPage(m_PackageDatabase),
BuiltInPage.k_Id => new BuiltInPage(m_PackageDatabase),
MyRegistriesPage.k_Id => new MyRegistriesPage(m_PackageDatabase),
MyAssetsPage.k_Id => new MyAssetsPage(m_PackageDatabase, m_PackageManagerPrefs, m_UnityConnect, m_AssetStoreClient),
_ => null
};
}
public IPage CreateExtensionPage(ExtensionPageArgs args)
{
return new ExtensionPage(m_PackageDatabase, args);
}
public IPage CreateScopedRegistryPage(RegistryInfo registryInfo)
{
return new ScopedRegistryPage(m_PackageDatabase, m_UpmCache, registryInfo);
}
[ExcludeFromCodeCoverage]
public void ResolveDependenciesForPage(IPage page)
{
switch (page)
{
case MyAssetsPage myAssetsPage:
myAssetsPage.ResolveDependencies(m_PackageDatabase, m_PackageManagerPrefs, m_UnityConnect, m_AssetStoreClient);
break;
case ScopedRegistryPage scopedRegistryPage:
scopedRegistryPage.ResolveDependencies(m_PackageDatabase, m_UpmCache);
break;
case SimplePage simplePage:
simplePage.ResolveDependencies(m_PackageDatabase);
break;
}
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Pages/PageFactory.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Pages/PageFactory.cs",
"repo_id": "UnityCsReference",
"token_count": 1493
} | 403 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace UnityEditor.PackageManager.UI.Internal
{
[Serializable]
internal abstract class SimplePage : BasePage
{
public static readonly PageSortOption[] k_DefaultSupportedSortOptions = { PageSortOption.NameAsc, PageSortOption.NameDesc, PageSortOption.PublishedDateDesc };
public static readonly PageFilters.Status[] k_DefaultSupportedStatusFilters = { PageFilters.Status.UpdateAvailable };
public override IEnumerable<PageFilters.Status> supportedStatusFilters => k_DefaultSupportedStatusFilters;
public override IEnumerable<PageSortOption> supportedSortOptions => k_DefaultSupportedSortOptions;
[SerializeField]
private VisualStateList m_VisualStateList = new();
public override IVisualStateList visualStates => m_VisualStateList;
public override PageCapability capability => PageCapability.SupportLocalReordering;
public SimplePage(IPackageDatabase packageDatabase) : base(packageDatabase) {}
public override bool UpdateFilters(PageFilters newFilters)
{
if (!base.UpdateFilters(newFilters))
return false;
RebuildVisualStatesAndUpdateVisibilityWithSearchText();
return true;
}
protected override void RefreshListOnSearchTextChange()
{
RebuildVisualStatesAndUpdateVisibilityWithSearchText();
}
public override void SetPackagesUserUnlockedState(IEnumerable<string> packageUniqueIds, bool unlocked)
{
var changedVisualStates = new HashSet<VisualState>();
foreach (var packageUniqueId in packageUniqueIds)
{
var visualState = m_VisualStateList.Get(packageUniqueId);
if (visualState == null || visualState.userUnlocked == unlocked)
continue;
visualState.userUnlocked = unlocked;
changedVisualStates.Add(visualState);
}
TriggerOnVisualStateChange(changedVisualStates);
}
public override void ResetUserUnlockedState()
{
var unlockedVisualStates = visualStates.Where(v => v.userUnlocked).ToArray();
foreach (var visualState in unlockedVisualStates)
visualState.userUnlocked = false;
TriggerOnVisualStateChange(unlockedVisualStates);
}
public void RebuildVisualStatesAndUpdateVisibilityWithSearchText()
{
RebuildAndReorderVisualStates();
RefreshSupportedStatusFiltersOnEntitlementPackageChange();
TriggerListRebuild();
UpdateVisualStateVisibilityWithSearchText();
}
public override void OnActivated()
{
base.OnActivated();
ResetUserUnlockedState();
RebuildVisualStatesAndUpdateVisibilityWithSearchText();
TriggerOnSelectionChanged();
}
public override void OnDeactivated()
{
base.OnDeactivated();
var selectedVisualStates = GetSelectedVisualStates();
var selectedGroups = new HashSet<string>(selectedVisualStates.Select(v => v.groupName).Where(groupName => !string.IsNullOrEmpty(groupName)));
foreach (var group in selectedGroups)
SetGroupExpanded(group, true);
}
public override void RebuildAndReorderVisualStates()
{
var filterByStatus = filters.status;
var packages = m_PackageDatabase.allPackages.Where(
p => ShouldInclude(p)
&& (filterByStatus != PageFilters.Status.UpdateAvailable || p.state == PackageState.UpdateAvailable)
&& (filterByStatus != PageFilters.Status.SubscriptionBased || p.hasEntitlements));
var orderedVisualStates = packages.OrderBy(p => p, new PackageComparer(filters.sortOption)).Select(p =>
{
var visualState = m_VisualStateList.Get(p.uniqueId) ?? new VisualState(p.uniqueId);
visualState.groupName = GetGroupName(p);
visualState.lockedByDefault = GetDefaultLockState(p);
return visualState;
}).ToList();
var orderedGroups = orderedVisualStates.Select(v => v.groupName).Distinct().Where(i => !string.IsNullOrEmpty(i)).ToList();
if (orderedGroups.Count > 1)
SortGroupNames(orderedGroups);
m_VisualStateList.Rebuild(orderedVisualStates, orderedGroups);
}
protected virtual void SortGroupNames(List<string> groupNames)
{
groupNames.Sort((x, y) => string.Compare(x, y, StringComparison.OrdinalIgnoreCase));
}
public override bool GetDefaultLockState(IPackage package)
{
return package.versions.installed?.isDirectDependency != true &&
m_PackageDatabase.GetFeaturesThatUseThisPackage(package.versions.installed)?.Any() == true;
}
// All the following load functions do nothing, because for a SimplePage we already know the complete list and there's no more to load
public override void LoadMore(long numberOfPackages) {}
public override void Load(string packageUniqueId) {}
public override void LoadExtraItems(IEnumerable<IPackage> packages) {}
private class PackageComparer : IComparer<IPackage>
{
private PageSortOption m_SortOption;
public PackageComparer(PageSortOption sortOption)
{
m_SortOption = sortOption;
}
private static int CompareByDisplayName(IPackageVersion x, IPackageVersion y)
{
return string.Compare(x.displayName, y.displayName, StringComparison.CurrentCultureIgnoreCase);
}
public int Compare(IPackage packageX, IPackage packageY)
{
var x = packageX?.versions.primary;
var y = packageY?.versions.primary;
if (x == null || y == null)
return 0;
var result = 0;
switch (m_SortOption)
{
case PageSortOption.NameAsc:
return CompareByDisplayName(x, y);
case PageSortOption.NameDesc:
return -CompareByDisplayName(x, y);
case PageSortOption.PublishedDateDesc:
result = -(x.publishedDate ?? DateTime.MinValue).CompareTo(y.publishedDate ?? DateTime.MinValue);
break;
// Sorting by Update date and Purchase date is only available through the Asset Store backend API
// So we will resort to default sorting (by display name) in this case.
case PageSortOption.UpdateDateDesc:
case PageSortOption.PurchasedDateDesc:
default:
break;
}
// We want to use display name as the secondary sort option if the primary sort option returns 0
// If sort option is set to anything sort option that's not supported, we'll sort by display name
return result != 0 ? result : CompareByDisplayName(x, y);
}
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Pages/SimplePage.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Pages/SimplePage.cs",
"repo_id": "UnityCsReference",
"token_count": 3175
} | 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.Diagnostics.CodeAnalysis;
namespace UnityEditor.PackageManager.UI.Internal
{
internal interface IProjectSettingsProxy : IService
{
event Action<bool> onEnablePreReleasePackagesChanged;
event Action<bool> onAdvancedSettingsFoldoutChanged;
event Action<bool> onScopedRegistriesSettingsFoldoutChanged;
event Action<bool> onSeeAllVersionsChanged;
event Action<long> onLoadAssetsChanged;
event Action onInitializationFinished;
bool dismissPreviewPackagesInUse { get; set; }
bool enablePreReleasePackages { get; set; }
bool advancedSettingsExpanded { get; set; }
bool scopedRegistriesSettingsExpanded { get; set; }
bool seeAllPackageVersions { get; set; }
long loadAssets { get; set; }
bool oneTimeWarningShown { get; set; }
bool oneTimeDeprecatedPopUpShown { get; set; }
bool isUserAddingNewScopedRegistry { get; set; }
IList<RegistryInfo> registries { get; }
IEnumerable<RegistryInfo> scopedRegistries { get; }
RegistryInfoDraft registryInfoDraft { get; }
void SetRegistries(RegistryInfo[] registries);
bool AddRegistry(RegistryInfo registry);
bool UpdateRegistry(string oldName, RegistryInfo newRegistry);
bool RemoveRegistry(string name);
void SelectRegistry(string name);
void Save();
}
[ExcludeFromCodeCoverage]
internal class PackageManagerProjectSettingsProxy : BaseService<IProjectSettingsProxy>, IProjectSettingsProxy
{
public event Action<bool> onEnablePreReleasePackagesChanged = delegate {};
public event Action<bool> onAdvancedSettingsFoldoutChanged = delegate {};
public event Action<bool> onScopedRegistriesSettingsFoldoutChanged = delegate {};
public event Action<bool> onSeeAllVersionsChanged = delegate {};
public event Action<long> onLoadAssetsChanged = delegate {};
public event Action onInitializationFinished = delegate {};
public bool dismissPreviewPackagesInUse
{
get => PackageManagerProjectSettings.instance.dismissPreviewPackagesInUse;
set => PackageManagerProjectSettings.instance.dismissPreviewPackagesInUse = value;
}
public bool enablePreReleasePackages
{
get => PackageManagerProjectSettings.instance.enablePreReleasePackages;
set => PackageManagerProjectSettings.instance.enablePreReleasePackages = value;
}
public bool advancedSettingsExpanded
{
get => PackageManagerProjectSettings.instance.advancedSettingsExpanded;
set => PackageManagerProjectSettings.instance.advancedSettingsExpanded = value;
}
public bool scopedRegistriesSettingsExpanded
{
get => PackageManagerProjectSettings.instance.scopedRegistriesSettingsExpanded;
set => PackageManagerProjectSettings.instance.scopedRegistriesSettingsExpanded = value;
}
public bool seeAllPackageVersions
{
get => PackageManagerProjectSettings.instance.seeAllPackageVersions;
set => PackageManagerProjectSettings.instance.seeAllPackageVersions = value;
}
public long loadAssets
{
get => PackageManagerProjectSettings.instance.loadAssets;
set => PackageManagerProjectSettings.instance.loadAssets = value;
}
public bool oneTimeWarningShown
{
get => PackageManagerProjectSettings.instance.oneTimeWarningShown;
set => PackageManagerProjectSettings.instance.oneTimeWarningShown = value;
}
public bool oneTimeDeprecatedPopUpShown
{
get => PackageManagerProjectSettings.instance.oneTimeDeprecatedPopUpShown;
set => PackageManagerProjectSettings.instance.oneTimeDeprecatedPopUpShown = value;
}
public bool isUserAddingNewScopedRegistry
{
get => PackageManagerProjectSettings.instance.isUserAddingNewScopedRegistry;
set => PackageManagerProjectSettings.instance.isUserAddingNewScopedRegistry = value;
}
public IList<RegistryInfo> registries => PackageManagerProjectSettings.instance.registries;
public void SetRegistries(RegistryInfo[] registries)
{
PackageManagerProjectSettings.instance.SetRegistries(registries);
}
public bool AddRegistry(RegistryInfo registry)
{
return PackageManagerProjectSettings.instance.AddRegistry(registry);
}
public bool UpdateRegistry(string oldName, RegistryInfo newRegistry)
{
return PackageManagerProjectSettings.instance.UpdateRegistry(oldName, newRegistry);
}
public bool RemoveRegistry(string name)
{
return PackageManagerProjectSettings.instance.RemoveRegistry(name);
}
public void SelectRegistry(string name)
{
PackageManagerProjectSettings.instance.SelectRegistry(name);
}
public IEnumerable<RegistryInfo> scopedRegistries => PackageManagerProjectSettings.instance.scopedRegistries;
public RegistryInfoDraft registryInfoDraft => PackageManagerProjectSettings.instance.registryInfoDraft;
public override void OnEnable()
{
PackageManagerProjectSettings.instance.onEnablePreReleasePackagesChanged += OnEnablePreReleasePackagesChanged;
PackageManagerProjectSettings.instance.onAdvancedSettingsFoldoutChanged += OnAdvancedSettingsFoldoutChanged;
PackageManagerProjectSettings.instance.onScopedRegistriesSettingsFoldoutChanged += OnScopedRegistriesSettingsFoldoutChanged;
PackageManagerProjectSettings.instance.onSeeAllVersionsChanged += OnSeeAllPackageVersionsChanged;
PackageManagerProjectSettings.instance.onLoadAssetsChanged += OnLoadAssetsChanged;
PackageManagerProjectSettings.instance.onInitializationFinished += OnInitializationFinished;
}
public override void OnDisable()
{
PackageManagerProjectSettings.instance.onEnablePreReleasePackagesChanged -= OnEnablePreReleasePackagesChanged;
PackageManagerProjectSettings.instance.onAdvancedSettingsFoldoutChanged -= OnAdvancedSettingsFoldoutChanged;
PackageManagerProjectSettings.instance.onScopedRegistriesSettingsFoldoutChanged -= OnScopedRegistriesSettingsFoldoutChanged;
PackageManagerProjectSettings.instance.onSeeAllVersionsChanged -= OnSeeAllPackageVersionsChanged;
PackageManagerProjectSettings.instance.onLoadAssetsChanged -= OnLoadAssetsChanged;
PackageManagerProjectSettings.instance.onInitializationFinished -= OnInitializationFinished;
}
public void Save()
{
PackageManagerProjectSettings.instance.Save();
}
private void OnInitializationFinished()
{
onInitializationFinished.Invoke();
}
private void OnEnablePreReleasePackagesChanged(bool enablePreReleasePackages)
{
onEnablePreReleasePackagesChanged?.Invoke(enablePreReleasePackages);
}
private void OnAdvancedSettingsFoldoutChanged(bool advancedSettingsExpanded)
{
onAdvancedSettingsFoldoutChanged?.Invoke(advancedSettingsExpanded);
}
private void OnScopedRegistriesSettingsFoldoutChanged(bool scopedRegistriesSettingsExpanded)
{
onScopedRegistriesSettingsFoldoutChanged?.Invoke(scopedRegistriesSettingsExpanded);
}
private void OnSeeAllPackageVersionsChanged(bool seeAllPackageVersions)
{
onSeeAllVersionsChanged?.Invoke(seeAllPackageVersions);
}
private void OnLoadAssetsChanged(long loadAssets)
{
onLoadAssetsChanged?.Invoke(loadAssets);
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Proxies/PackageManagerProjectSettingsProxy.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Proxies/PackageManagerProjectSettingsProxy.cs",
"repo_id": "UnityCsReference",
"token_count": 2949
} | 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.Collections.Generic;
using System.Linq;
namespace UnityEditor.PackageManager.UI.Internal
{
internal class UpmPackageFactory : Package.Factory
{
private readonly IUniqueIdMapper m_UniqueIdMapper;
private readonly IUpmCache m_UpmCache;
private readonly IUpmClient m_UpmClient;
private readonly IBackgroundFetchHandler m_BackgroundFetchHandler;
private readonly IPackageDatabase m_PackageDatabase;
private readonly IProjectSettingsProxy m_SettingsProxy;
public UpmPackageFactory(IUniqueIdMapper uniqueIdMapper,
IUpmCache upmCache,
IUpmClient upmClient,
IBackgroundFetchHandler backgroundFetchHandler,
IPackageDatabase packageDatabase,
IProjectSettingsProxy settingsProxy)
{
m_UniqueIdMapper = RegisterDependency(uniqueIdMapper);
m_UpmCache = RegisterDependency(upmCache);
m_UpmClient = RegisterDependency(upmClient);
m_BackgroundFetchHandler = RegisterDependency(backgroundFetchHandler);
m_PackageDatabase = RegisterDependency(packageDatabase);
m_SettingsProxy = RegisterDependency(settingsProxy);
}
public override void OnEnable()
{
m_SettingsProxy.onEnablePreReleasePackagesChanged += OnShowPreReleasePackagesesOrSeeAllVersionsChanged;
m_SettingsProxy.onSeeAllVersionsChanged += OnShowPreReleasePackagesesOrSeeAllVersionsChanged;
m_UpmCache.onPackageInfosUpdated += OnPackageInfosUpdated;
m_UpmCache.onExtraPackageInfoFetched += OnExtraPackageInfoFetched;
m_UpmCache.onLoadAllVersionsChanged += OnLoadAllVersionsChanged;
m_UpmClient.onPackagesProgressChange += OnPackagesProgressChange;
m_UpmClient.onPackageOperationError += OnPackageOperationError;
}
public override void OnDisable()
{
m_SettingsProxy.onEnablePreReleasePackagesChanged -= OnShowPreReleasePackagesesOrSeeAllVersionsChanged;
m_SettingsProxy.onSeeAllVersionsChanged -= OnShowPreReleasePackagesesOrSeeAllVersionsChanged;
m_UpmCache.onPackageInfosUpdated -= OnPackageInfosUpdated;
m_UpmCache.onExtraPackageInfoFetched -= OnExtraPackageInfoFetched;
m_UpmCache.onLoadAllVersionsChanged -= OnLoadAllVersionsChanged;
m_UpmClient.onPackagesProgressChange += OnPackagesProgressChange;
m_UpmClient.onPackageOperationError += OnPackageOperationError;
}
private void OnPackageOperationError(string packageIdOrName, UIError error)
{
var package = m_PackageDatabase.GetPackageByIdOrName(packageIdOrName) as Package;
if (package == null)
return;
if (package.versions.primary.HasTag(PackageTag.SpecialInstall))
{
m_PackageDatabase.UpdatePackages(toRemove: new[] { package.uniqueId });
if (!error.HasAttribute(UIError.Attribute.DetailInConsole))
{
UnityEngine.Debug.Log(error.message);
error.attribute |= UIError.Attribute.DetailInConsole;
}
return;
}
AddError(package, error);
m_PackageDatabase.OnPackagesModified(new[] { package });
}
private void OnPackagesProgressChange(IEnumerable<(string packageIdOrName, PackageProgress progress)> progressUpdates)
{
var packagesUpdated = new List<IPackage>();
foreach (var item in progressUpdates)
{
var package = m_PackageDatabase.GetPackageByIdOrName(item.packageIdOrName) as Package;
// Special handling for installing a package that's not already in the database. This case is most likely to happen
// when a user adds a git or local package through the special add package UI.
if (package == null && item.progress == PackageProgress.Installing)
{
var version = new PlaceholderPackageVersion(item.packageIdOrName, L10n.Tr("Installing a new package"), tag: PackageTag.UpmFormat | PackageTag.SpecialInstall);
var placeholderPackage = CreatePackage(item.packageIdOrName, new PlaceholderVersionList(version));
SetProgress(placeholderPackage, PackageProgress.Installing);
m_PackageDatabase.UpdatePackages(new[] { placeholderPackage });
continue;
}
if (package == null || package.progress == item.progress)
continue;
// For special installations, we don't want to modify the progress here because we want to keep the
// installing package in the `In Project` this. The special installation package will be replaced
// by the actual package in PackageDatabase when we detect uniqueId changes through uniqueIdMapper
if (package.versions.primary.HasTag(PackageTag.SpecialInstall))
continue;
SetProgress(package, item.progress);
packagesUpdated.Add(package);
}
if (packagesUpdated.Any())
m_PackageDatabase.OnPackagesModified(packagesUpdated, true);
}
private void OnExtraPackageInfoFetched(PackageInfo packageInfo)
{
// only trigger the call when the package is not installed, as installed version always have the most up-to-date package info
var productId = packageInfo.assetStore?.productId;
if (string.IsNullOrEmpty(productId) && m_UpmCache.GetInstalledPackageInfo(packageInfo.name)?.packageId != packageInfo.packageId)
GeneratePackagesAndTriggerChangeEvent(new[] { packageInfo.name });
}
private void OnPackageInfosUpdated(IEnumerable<PackageInfo> packageInfos)
{
GeneratePackagesAndTriggerChangeEvent(packageInfos.Select(p => p.name));
}
private void OnLoadAllVersionsChanged(string packageUniqueId, bool _)
{
if (!long.TryParse(packageUniqueId, out var _))
GeneratePackagesAndTriggerChangeEvent(new[] { packageUniqueId });
}
private void OnShowPreReleasePackagesesOrSeeAllVersionsChanged(bool _)
{
var allPackageNames = m_UpmCache.installedPackageInfos.Concat(m_UpmCache.searchPackageInfos).Select(p => p.name).ToHashSet();
GeneratePackagesAndTriggerChangeEvent(allPackageNames);
}
public void GeneratePackagesAndTriggerChangeEvent(IEnumerable<string> packageNames)
{
if (packageNames?.Any() != true)
return;
var updatedPackages = new List<IPackage>();
var packagesToRemove = new List<string>();
var showPreRelease = m_SettingsProxy.enablePreReleasePackages;
var seeAllVersions = m_SettingsProxy.seeAllPackageVersions;
foreach (var packageName in packageNames)
{
// Upm packages with product ids are handled in UpmOnAssetStorePackageFactory, we don't want to worry about it here.
if (m_UniqueIdMapper.GetProductIdByName(packageName) != 0)
continue;
var installedInfo = m_UpmCache.GetInstalledPackageInfo(packageName);
var searchInfo = m_UpmCache.GetSearchPackageInfo(packageName);
var isDeprecated = searchInfo?.unityLifecycle?.isDeprecated ?? installedInfo?.unityLifecycle?.isDeprecated ?? false;
var deprecationMessage = isDeprecated ?
searchInfo?.unityLifecycle?.deprecationMessage ?? installedInfo?.unityLifecycle?.deprecationMessage
: null;
if (installedInfo == null && searchInfo == null)
packagesToRemove.Add(packageName);
else
{
var availableRegistry = m_UpmClient.GetAvailableRegistryType(searchInfo ?? installedInfo);
var extraVersions = m_UpmCache.GetExtraPackageInfos(packageName);
var versionList = new UpmVersionList(searchInfo, installedInfo, availableRegistry, extraVersions);
versionList = VersionsFilter.GetFilteredVersionList(versionList, seeAllVersions, showPreRelease);
versionList = VersionsFilter.UnloadVersionsIfNeeded(versionList, m_UpmCache.IsLoadAllVersions(packageName));
if (!versionList.Any())
{
packagesToRemove.Add(packageName);
continue;
}
var package = CreatePackage(packageName, versionList, isDiscoverable: searchInfo != null, isDeprecated: isDeprecated, deprecationMessage: deprecationMessage);
updatedPackages.Add(package);
// if the primary version is not fully fetched, trigger an extra fetch automatically right away to get results early
// since the primary version's display name is used in the package list
var primaryVersion = package.versions.primary;
if (primaryVersion?.isFullyFetched == false)
m_BackgroundFetchHandler.AddToExtraFetchPackageInfoQueue(primaryVersion.packageId);
}
}
if (updatedPackages.Any() || packagesToRemove.Any())
m_PackageDatabase.UpdatePackages(toAddOrUpdate: updatedPackages, toRemove: packagesToRemove);
}
}
internal class UpmOnAssetStorePackageFactory : Package.Factory
{
private readonly IUniqueIdMapper m_UniqueIdMapper;
private readonly IUnityConnectProxy m_UnityConnect;
private readonly IAssetStoreCache m_AssetStoreCache;
private readonly IBackgroundFetchHandler m_BackgroundFetchHandler;
private readonly IPackageDatabase m_PackageDatabase;
private readonly IFetchStatusTracker m_FetchStatusTracker;
private readonly IUpmCache m_UpmCache;
private readonly IUpmClient m_UpmClient;
public UpmOnAssetStorePackageFactory(IUniqueIdMapper uniqueIdMapper,
IUnityConnectProxy unityConnect,
IAssetStoreCache assetStoreCache,
IBackgroundFetchHandler backgroundFetchHandler,
IPackageDatabase packageDatabase,
IFetchStatusTracker fetchStatusTracker,
IUpmCache upmCache,
IUpmClient upmClient)
{
m_UniqueIdMapper = RegisterDependency(uniqueIdMapper);
m_UnityConnect = RegisterDependency(unityConnect);
m_AssetStoreCache = RegisterDependency(assetStoreCache);
m_BackgroundFetchHandler = RegisterDependency(backgroundFetchHandler);
m_PackageDatabase = RegisterDependency(packageDatabase);
m_FetchStatusTracker = RegisterDependency(fetchStatusTracker);
m_UpmCache = RegisterDependency(upmCache);
m_UpmClient = RegisterDependency(upmClient);
}
public override void OnEnable()
{
m_UnityConnect.onUserLoginStateChange += OnUserLoginStateChange;
m_UpmCache.onPackageInfosUpdated += OnPackageInfosUpdated;
m_UpmCache.onExtraPackageInfoFetched += OnExtraPackageInfoFetched;
m_UpmCache.onLoadAllVersionsChanged += OnLoadAllVersionsChanged;
m_AssetStoreCache.onPurchaseInfosChanged += OnPurchaseInfosChanged;
m_AssetStoreCache.onProductInfoChanged += OnProductInfoChanged;
m_FetchStatusTracker.onFetchStatusChanged += OnFetchStatusChanged;
}
public override void OnDisable()
{
m_UnityConnect.onUserLoginStateChange += OnUserLoginStateChange;
m_UpmCache.onPackageInfosUpdated -= OnPackageInfosUpdated;
m_UpmCache.onExtraPackageInfoFetched -= OnExtraPackageInfoFetched;
m_UpmCache.onLoadAllVersionsChanged -= OnLoadAllVersionsChanged;
m_AssetStoreCache.onPurchaseInfosChanged -= OnPurchaseInfosChanged;
m_AssetStoreCache.onProductInfoChanged -= OnProductInfoChanged;
m_FetchStatusTracker.onFetchStatusChanged -= OnFetchStatusChanged;
}
public void GeneratePackagesAndTriggerChangeEvent(IEnumerable<long> productIds)
{
if (productIds?.Any() != true)
return;
var packagesChanged = new List<IPackage>();
foreach (var productId in productIds)
{
var purchaseInfo = m_AssetStoreCache.GetPurchaseInfo(productId);
var productInfo = m_AssetStoreCache.GetProductInfo(productId);
var packageName = string.IsNullOrEmpty(productInfo?.packageName) ? m_UniqueIdMapper.GetNameByProductId(productId) : productInfo.packageName;
// Unlike AssetStorePackageFactory or UpmPackageFactory, UpmOnAssetStorePackageFactory is specifically created to handle packages
// with both productId and packageName, so we skip all other cases here.
if (string.IsNullOrEmpty(packageName))
continue;
var productSearchInfo = m_UpmCache.GetProductSearchPackageInfo(packageName);
var installedPackageInfo = m_UpmCache.GetInstalledPackageInfo(packageName);
var fetchStatus = m_FetchStatusTracker.GetOrCreateFetchStatus(productId);
var isDeprecated = productSearchInfo?.unityLifecycle?.isDeprecated ?? installedPackageInfo?.unityLifecycle?.isDeprecated ?? false;
var deprecationMessage = isDeprecated ?
productSearchInfo?.unityLifecycle?.deprecationMessage ?? installedPackageInfo?.unityLifecycle?.deprecationMessage
: null;
Package package = null;
if (productSearchInfo != null || installedPackageInfo != null)
{
var productInfoFetchError = fetchStatus?.GetFetchError(FetchType.ProductInfo);
if (productInfo == null && productInfoFetchError == null && !fetchStatus.IsFetchInProgress(FetchType.ProductInfo))
{
m_BackgroundFetchHandler.AddToFetchProductInfoQueue(productId);
m_BackgroundFetchHandler.AddToFetchPurchaseInfoQueue(productId);
continue;
}
if (productSearchInfo == null)
m_BackgroundFetchHandler.AddToExtraFetchPackageInfoQueue(packageName, productId);
var extraVersions = m_UpmCache.GetExtraPackageInfos(packageName);
var availableRegistry = m_UpmClient.GetAvailableRegistryType(productSearchInfo ?? installedPackageInfo);
var versionList = new UpmVersionList(productSearchInfo, installedPackageInfo, availableRegistry, extraVersions);
versionList = VersionsFilter.UnloadVersionsIfNeeded(versionList, m_UpmCache.IsLoadAllVersions(productId.ToString()));
package = CreatePackage(packageName, versionList, new Product(productId, purchaseInfo, productInfo), isDeprecated: isDeprecated, deprecationMessage: deprecationMessage);
if (productInfoFetchError != null)
AddError(package, productInfoFetchError.error);
else if (productInfo == null && fetchStatus.IsFetchInProgress(FetchType.ProductInfo))
SetProgress(package, PackageProgress.Refreshing);
}
else if (productInfo != null)
{
var productSearchInfoFetchError = fetchStatus.GetFetchError(FetchType.ProductSearchInfo);
if (productSearchInfoFetchError != null)
{
var version = new PlaceholderPackageVersion($"{packageName}@{productInfo.versionString}", productInfo.displayName, productInfo.versionString, PackageTag.UpmFormat, productSearchInfoFetchError.error);
package = CreatePackage(packageName, new PlaceholderVersionList(version), new Product(productId, purchaseInfo, productInfo), isDeprecated: isDeprecated, deprecationMessage: deprecationMessage);
}
else
{
var version = new PlaceholderPackageVersion($"{packageName}@{productInfo.versionString}", productInfo.displayName, productInfo.versionString, PackageTag.UpmFormat);
package = CreatePackage(packageName, new PlaceholderVersionList(version), new Product(productId, purchaseInfo, productInfo), isDeprecated: isDeprecated, deprecationMessage: deprecationMessage);
SetProgress(package, PackageProgress.Refreshing);
if (!fetchStatus.IsFetchInProgress(FetchType.ProductSearchInfo))
m_BackgroundFetchHandler.AddToExtraFetchPackageInfoQueue(packageName, productId);
}
}
if (package == null)
continue;
// if the primary version is not fully fetched, trigger an extra fetch automatically right away to get results early
// since the primary version's display name is used in the package list
var primaryVersion = package.versions.primary;
if (primaryVersion?.isFullyFetched == false)
m_BackgroundFetchHandler.AddToExtraFetchPackageInfoQueue(primaryVersion.packageId);
packagesChanged.Add(package);
}
if (packagesChanged.Any())
m_PackageDatabase.UpdatePackages(packagesChanged);
}
private void OnProductInfoChanged(AssetStoreProductInfo productInfo)
{
GeneratePackagesAndTriggerChangeEvent(new[] { productInfo.productId });
}
private void OnPurchaseInfosChanged(IEnumerable<AssetStorePurchaseInfo> purchaseInfos)
{
GeneratePackagesAndTriggerChangeEvent(purchaseInfos.Select(info => info.productId));
}
private void OnPackageInfosUpdated(IEnumerable<PackageInfo> packageInfos)
{
GeneratePackagesAndTriggerChangeEvent(packageInfos.Select(p => m_UniqueIdMapper.GetProductIdByName(p.name)).Where(id => id != 0));
}
private void OnExtraPackageInfoFetched(PackageInfo packageInfo)
{
// only trigger the call when the package is not installed, as installed version always have the most up-to-date package info
if (long.TryParse(packageInfo.assetStore?.productId, out var productId) && m_UpmCache.GetInstalledPackageInfo(packageInfo.name)?.packageId != packageInfo.packageId)
GeneratePackagesAndTriggerChangeEvent(new[] { productId });
}
private void OnLoadAllVersionsChanged(string packageUniqueId, bool _)
{
if (long.TryParse(packageUniqueId, out var productId))
GeneratePackagesAndTriggerChangeEvent(new[] { productId });
}
private void OnFetchStatusChanged(FetchStatus fetchStatus)
{
GeneratePackagesAndTriggerChangeEvent(new[] { fetchStatus.productId });
}
private void OnUserLoginStateChange(bool _, bool loggedIn)
{
if (loggedIn)
return;
m_UpmCache.ClearProductCache();
// We only remove packages from the Asset Store that are of UPM format. We handle the Legacy format in AssetStorePackageFactory.
// Also, we use `ToArray` here as m_PackageDatabase.UpdatePackages will modify the enumerable and throw an error if we don't.
var packagesToRemove = m_PackageDatabase.allPackages
.Where(p => p.product != null && p.versions.Any(v => v.HasTag(PackageTag.UpmFormat)) &&
p.versions.installed == null).Select(p => p.uniqueId).ToArray();
if (packagesToRemove.Any())
m_PackageDatabase.UpdatePackages(toRemove: packagesToRemove);
var productIds = m_UpmCache.installedPackageInfos.Select(info =>
{
long.TryParse(info.assetStore?.productId, out var productId);
return productId;
}).Where(id => id > 0);
GeneratePackagesAndTriggerChangeEvent(productIds);
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Upm/UpmPackageFactory.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Upm/UpmPackageFactory.cs",
"repo_id": "UnityCsReference",
"token_count": 8698
} | 406 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.PackageManager.UI.Internal
{
internal class LoadingSpinner : VisualElement
{
[Serializable]
public new class UxmlSerializedData : VisualElement.UxmlSerializedData
{
public override object CreateInstance() => new LoadingSpinner();
}
public bool started { get; private set; }
private const int k_RotationSpeed = 360; // Euler degrees per second
private const double k_PaintInterval = 0.125f; // Time interval to repaint
static private int s_Rotation;
static private double s_LastRotationTime;
private static readonly List<LoadingSpinner> s_CurrentSpinners = new List<LoadingSpinner>();
public LoadingSpinner()
{
started = false;
UIUtils.SetElementDisplay(this, false);
// add child elements to set up centered spinner rotation
var innerElement = new VisualElement();
innerElement.AddToClassList("image");
Add(innerElement);
style.transformOrigin = new TransformOrigin(0, 0, 0);
}
private static void UpdateProgress()
{
var currentTime = EditorApplication.timeSinceStartup;
var deltaTime = currentTime - s_LastRotationTime;
if (deltaTime >= k_PaintInterval)
{
var q = Quaternion.Euler(0, 0, s_Rotation);
foreach (var spinner in s_CurrentSpinners)
spinner.transform.rotation = q;
s_Rotation += (int)(k_RotationSpeed * deltaTime);
s_Rotation %= 360;
if (s_Rotation < 0) s_Rotation += 360;
s_LastRotationTime = currentTime;
}
}
public void Start()
{
if (started)
return;
s_Rotation = 0;
// we remove k_PaintInterval from timeSinceStartup to make sure we start the animation the first time
s_LastRotationTime = EditorApplication.timeSinceStartup - k_PaintInterval;
started = true;
UIUtils.SetElementDisplay(this, true);
if (!s_CurrentSpinners.Any())
EditorApplication.update += UpdateProgress;
s_CurrentSpinners.Add(this);
}
public void Stop()
{
if (!started)
return;
started = false;
UIUtils.SetElementDisplay(this, false);
s_CurrentSpinners.Remove(this);
if (!s_CurrentSpinners.Any())
EditorApplication.update -= UpdateProgress;
}
public static void ClearAllSpinners()
{
if (!s_CurrentSpinners.Any())
return;
s_CurrentSpinners.Clear();
EditorApplication.update -= UpdateProgress;
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/UI/Common/LoadingSpinner.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/Common/LoadingSpinner.cs",
"repo_id": "UnityCsReference",
"token_count": 1413
} | 407 |
// Unity 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 AssetStoreFiltersWindow : PackageManagerFiltersWindow
{
[NonSerialized]
private List<string> m_Categories;
[NonSerialized]
private List<string> m_Labels;
private IAssetStoreRestAPI m_AssetStoreRestAPI;
private IBackgroundFetchHandler m_BackgroundFetchHandler;
protected override void ResolveDependencies()
{
base.ResolveDependencies();
var container = ServicesContainer.instance;
m_AssetStoreRestAPI = container.Resolve<IAssetStoreRestAPI>();
m_BackgroundFetchHandler = container.Resolve<IBackgroundFetchHandler>();
}
protected override Vector2 GetSize(IPage page)
{
var height = k_FoldOutHeight + page.supportedStatusFilters.Count() * k_ToggleHeight;
var categories = m_CategoriesFoldOut?.Children().OfType<Toggle>() ?? Enumerable.Empty<Toggle>();
var numCategories = categories.Count();
height += (numCategories > 0 ? k_FoldOutHeight : 0) + numCategories * k_ToggleHeight;
return new Vector2(k_Width, Math.Min(height, k_MaxHeight));
}
private float GetLabelsHeight()
{
var labels = m_LabelsFoldOut?.Children().OfType<Toggle>() ?? Enumerable.Empty<Toggle>();
var firstLabels = labels.Take(k_MaxDisplayLabels);
var height = (labels.Any() ? k_FoldOutHeight : 0) + firstLabels.Count() * k_ToggleHeight;
var selectedLabels = labels.Skip(k_MaxDisplayLabels).Where(t => t.value);
height += selectedLabels.Count() * k_ToggleHeight;
if (labels.Count() > firstLabels.Count() + selectedLabels.Count())
height += k_ToggleHeight; // Show all button height
return height;
}
protected override void Init(Rect rect, IPage page)
{
// We want to show categories right way since the information is always available
m_Categories = m_AssetStoreRestAPI.GetCategories().ToList();
base.Init(rect, page);
// Defer display of labels
m_AssetStoreRestAPI.ListLabels(labels =>
{
// If window was closed during fetch of labels, ignore display
if (instance == null)
return;
m_Labels = labels ?? new List<string>();
if (m_Labels.Any())
{
DoLabelsDisplay();
ApplyFilters();
// Update window height if necessary
var labelsHeight = GetLabelsHeight();
var newHeight = Math.Min(position.height + labelsHeight, k_MaxHeight);
if (newHeight != position.height)
{
position = new Rect(position) { height = newHeight };
RepaintImmediately();
}
}
},
error => Debug.LogWarning(string.Format(L10n.Tr("[Package Manager Window] Error while fetching labels: {0}"), error.message)));
}
protected override void ApplyFilters()
{
foreach (var toggle in m_StatusFoldOut.Children().OfType<Toggle>())
toggle.SetValueWithoutNotify(toggle.name == m_Filters.status.ToString());
foreach (var toggle in m_CategoriesFoldOut?.Children().OfType<Toggle>() ?? Enumerable.Empty<Toggle>())
toggle.SetValueWithoutNotify(m_Filters.categories?.Contains(toggle.name.ToLower()) ?? false);
var selectedLabels = 0;
var labels = m_LabelsFoldOut?.Children().OfType<Toggle>() ?? Enumerable.Empty<Toggle>();
foreach (var toggle in labels)
{
if (m_Filters?.labels?.Contains(toggle.name) ?? false)
{
toggle.SetValueWithoutNotify(true);
UIUtils.SetElementDisplay(toggle, true);
selectedLabels++;
}
}
if (labels.Count() > Math.Max(k_MaxDisplayLabels, selectedLabels))
{
m_ShowAllButton = new Button {text = L10n.Tr("Show all"), name = k_ShowAllButtonName};
m_ShowAllButton.clickable.clicked += () =>
{
m_LabelsFoldOut.Remove(m_ShowAllButton);
foreach (var toggle in m_LabelsFoldOut.Children())
UIUtils.SetElementDisplay(toggle, true);
};
m_LabelsFoldOut.Add(m_ShowAllButton);
}
}
protected override void DoDisplay(IPage page)
{
m_StatusFoldOut = new Foldout {text = L10n.Tr("Status"), name = k_StatusFoldOutName, classList = {k_FoldoutClass}};
foreach (var status in page.supportedStatusFilters)
{
var toggle = new Toggle(status.GetDisplayName()) {name = status.ToString(), classList = {k_ToggleClass}};
toggle.RegisterValueChangedCallback(evt =>
{
if (evt.newValue)
{
foreach (var t in m_StatusFoldOut.Children().OfType<Toggle>())
{
if (t == toggle)
continue;
t.SetValueWithoutNotify(false);
}
if (status == PageFilters.Status.Unlabeled && m_LabelsFoldOut != null)
foreach (var t in m_LabelsFoldOut.Children().OfType<Toggle>())
t.value = false;
if (status == PageFilters.Status.UpdateAvailable)
{
m_BackgroundFetchHandler.CheckUpdateForUncheckedLocalInfos();
}
}
UpdateFiltersIfNeeded();
});
m_StatusFoldOut.Add(toggle);
}
m_Container.Add(m_StatusFoldOut);
if (m_Categories.Any())
{
m_CategoriesFoldOut = new Foldout {text = L10n.Tr("Categories"), name = k_CategoriesFoldOutName, classList = {k_FoldoutClass}};
foreach (var category in m_Categories)
{
var toggle = new Toggle(L10n.Tr(category)) {name = category.ToLower(), classList = {k_ToggleClass}};
toggle.RegisterValueChangedCallback(evt => UpdateFiltersIfNeeded());
m_CategoriesFoldOut.Add(toggle);
}
m_CategoriesFoldOut.Query<Label>().ForEach(UIUtils.TextTooltipOnSizeChange);
m_Container.Add(m_CategoriesFoldOut);
}
}
private void DoLabelsDisplay()
{
m_LabelsFoldOut = new Foldout {text = L10n.Tr("Labels"), name = k_LabelsFoldOutName, classList = {k_FoldoutClass}};
var i = 0;
foreach (var label in m_Labels)
{
var toggle = new Toggle(L10n.Tr(label)) {name = label, classList = {k_ToggleClass}};
toggle.RegisterValueChangedCallback(evt =>
{
if (evt.newValue)
{
// Uncheck Unlabeled if checked
m_StatusFoldOut.Q<Toggle>(PageFilters.Status.Unlabeled.ToString()).value = false;
}
UpdateFiltersIfNeeded();
});
m_LabelsFoldOut.Add(toggle);
if (++i > k_MaxDisplayLabels)
UIUtils.SetElementDisplay(toggle, false);
}
m_LabelsFoldOut.Query<Label>().ForEach(UIUtils.TextTooltipOnSizeChange);
m_Container.Add(m_LabelsFoldOut);
}
private void UpdateFiltersIfNeeded()
{
var filters = m_Filters.Clone();
var selectedStatus = m_StatusFoldOut.Children().OfType<Toggle>().Where(toggle => toggle.value).Select(toggle => toggle.name).FirstOrDefault();
filters.status = !string.IsNullOrEmpty(selectedStatus) && Enum.TryParse(selectedStatus, out PageFilters.Status status) ? status : PageFilters.Status.None;
if (m_CategoriesFoldOut != null)
{
var selectedCategories = m_CategoriesFoldOut.Children().OfType<Toggle>().Where(toggle => toggle.value).Select(toggle => toggle.name.ToLower());
filters.categories = selectedCategories.ToList();
}
if (m_LabelsFoldOut != null)
{
var selectedLabels = m_LabelsFoldOut.Children().OfType<Toggle>().Where(toggle => toggle.value).Select(toggle => toggle.name);
filters.labels = selectedLabels.ToList();
}
if (!filters.Equals(m_Filters))
{
m_Filters = filters;
UpdatePageFilters();
}
}
internal Foldout m_StatusFoldOut;
internal Foldout m_CategoriesFoldOut;
internal Foldout m_LabelsFoldOut;
internal Button m_ShowAllButton;
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/UI/Filters/AssetStoreFiltersWindow.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/Filters/AssetStoreFiltersWindow.cs",
"repo_id": "UnityCsReference",
"token_count": 4747
} | 408 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine.UIElements;
namespace UnityEditor.PackageManager.UI.Internal
{
internal class MultiSelectItem : VisualElement
{
private IPackageVersion m_Version;
private string m_RightInfoText;
public MultiSelectItem(IPackageVersion version, string rightInfoText = "")
{
m_Version = version;
m_RightInfoText = rightInfoText;
m_MainContainer = new VisualElement { name = "mainContainer" };
Add(m_MainContainer);
m_LeftContainer = new VisualElement { name = "leftContainer" };
m_MainContainer.Add(m_LeftContainer);
m_TypeIcon = new VisualElement { name = "typeIcon" };
m_LeftContainer.Add(m_TypeIcon);
m_NameLabel = new Label { name = "nameLabel" };
m_LeftContainer.Add(m_NameLabel);
if (m_Version?.HasTag(PackageTag.Feature | PackageTag.LegacyFormat | PackageTag.BuiltIn) == false)
{
m_VersionLabel = new Label { name = "versionLabel" };
m_LeftContainer.Add(m_VersionLabel);
}
m_RightContainer = new VisualElement { name = "rightContainer" };
m_MainContainer.Add(m_RightContainer);
m_RightInfoLabel = new Label { name = "rightInfoLabel" };
m_RightContainer.Add(m_RightInfoLabel);
m_Spinner = null;
Refresh();
}
public void Refresh()
{
m_TypeIcon.EnableClassToggle("featureIcon", "packageIcon", m_Version?.HasTag(PackageTag.Feature) == true);
m_NameLabel.text = m_Version.displayName;
if (m_VersionLabel != null)
m_VersionLabel.text = m_Version.versionString;
m_RightInfoLabel.text = m_RightInfoText;
if (m_Version.HasTag(PackageTag.LegacyFormat))
return;
if (m_Version.package.progress != PackageProgress.None)
StartSpinner();
else
StopSpinner();
}
private void StartSpinner()
{
if (m_Spinner == null)
{
m_Spinner = new LoadingSpinner { name = "packageSpinner" };
m_RightContainer.Insert(0, m_Spinner);
}
m_Spinner.Start();
m_Spinner.tooltip = "Operation in progress...";
UIUtils.SetElementDisplay(m_RightInfoLabel, false);
}
private void StopSpinner()
{
m_Spinner?.Stop();
UIUtils.SetElementDisplay(m_RightInfoLabel, true);
}
private VisualElement m_MainContainer;
private VisualElement m_LeftContainer;
private VisualElement m_TypeIcon;
private Label m_NameLabel;
private Label m_VersionLabel;
private VisualElement m_RightContainer;
private Label m_RightInfoLabel;
private LoadingSpinner m_Spinner;
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/UI/MultiSelect/MultiSelectItem.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/MultiSelect/MultiSelectItem.cs",
"repo_id": "UnityCsReference",
"token_count": 1406
} | 409 |
// 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 PackageDetailsOverviewTab : PackageDetailsTabElement
{
public const string k_Id = "overview";
private readonly PackageDetailsOverviewTabContent m_Content;
protected override bool requiresUserSignIn => true;
public PackageDetailsOverviewTab(IUnityConnectProxy unityConnect, IResourceLoader resourceLoader) : base(unityConnect)
{
m_Id = k_Id;
m_DisplayName = L10n.Tr("Overview");
m_Content = new PackageDetailsOverviewTabContent(resourceLoader);
m_ContentContainer.Add(m_Content);
}
public override bool IsValid(IPackageVersion version)
{
return version != null && version.package.product != null && !version.HasTag(PackageTag.UpmFormat);
}
protected override void RefreshContent(IPackageVersion version)
{
m_Content.Refresh(version);
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageDetailsTabs/PackageDetailsOverviewTab.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageDetailsTabs/PackageDetailsOverviewTab.cs",
"repo_id": "UnityCsReference",
"token_count": 423
} | 410 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.PackageManager.UI.Internal
{
internal class PackageListScrollView : ScrollView, IPackageListView
{
[Serializable]
public new class UxmlSerializedData : ScrollView.UxmlSerializedData
{
public override object CreateInstance() => new PackageListScrollView();
}
private Dictionary<string, PackageItem> m_PackageItemsLookup;
private IResourceLoader m_ResourceLoader;
private IPackageDatabase m_PackageDatabase;
private IPageManager m_PageManager;
private IPageRefreshHandler m_PageRefreshHandler;
private void ResolveDependencies()
{
var container = ServicesContainer.instance;
m_ResourceLoader = container.Resolve<IResourceLoader>();
m_PackageDatabase = container.Resolve<IPackageDatabase>();
m_PageManager = container.Resolve<IPageManager>();
m_PageRefreshHandler = container.Resolve<IPageRefreshHandler>();
}
internal IEnumerable<PackageItem> packageItems => packageGroups.SelectMany(group => group.packageItems);
internal IEnumerable<PackageGroup> packageGroups => m_ItemsList.Children().OfType<PackageGroup>();
private VisualElement m_ItemsList;
private VisualElement m_ScrollToTarget;
public PackageListScrollView()
{
ResolveDependencies();
m_ItemsList = new VisualElement();
Add(m_ItemsList);
viewDataKey = "package-list-scrollview-key";
horizontalScrollerVisibility = ScrollerVisibility.Hidden;
m_PackageItemsLookup = new Dictionary<string, PackageItem>();
focusable = true;
contentContainer.RegisterCallback<AttachToPanelEvent>(OnAttachToPanel);
contentContainer.RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel);
}
private void OnAttachToPanel(AttachToPanelEvent evt)
{
if (evt.destinationPanel == null)
return;
contentContainer.RegisterCallback<MouseDownEvent>(OnMouseDown);
}
private void OnDetachFromPanel(DetachFromPanelEvent evt)
{
if (evt.originPanel == null)
return;
contentContainer.UnregisterCallback<MouseDownEvent>(OnMouseDown);
}
public PackageItem GetPackageItem(string packageUniqueId)
{
return string.IsNullOrEmpty(packageUniqueId) ? null : m_PackageItemsLookup.Get(packageUniqueId);
}
private ISelectableItem GetFirstSelectedItem()
{
m_PackageDatabase.GetPackageAndVersion(m_PageManager.activePage.GetSelection().firstSelection, out var package, out var version);
var selectedVersion = version ?? package?.versions.primary;
return GetPackageItem(selectedVersion?.package.uniqueId);
}
public void ScrollToSelection()
{
// For now we want to just scroll to any of the selections, this behaviour might change in the future depending on how users react
ScrollIfNeeded(GetFirstSelectedItem()?.element);
}
private void ScrollIfNeeded()
{
if (m_ScrollToTarget == null)
return;
EditorApplication.delayCall -= ScrollIfNeeded;
if (float.IsNaN(layout.height) || layout.height == 0 || float.IsNaN(m_ScrollToTarget.layout.height))
{
EditorApplication.delayCall += ScrollIfNeeded;
return;
}
var scrollViews = UIUtils.GetParentsOfType<ScrollView>(m_ScrollToTarget);
foreach (var scrollview in scrollViews)
UIUtils.ScrollIfNeeded(scrollview, m_ScrollToTarget);
m_ScrollToTarget = null;
}
private void ScrollIfNeeded(VisualElement target)
{
m_ScrollToTarget = target;
ScrollIfNeeded();
}
private void AddOrUpdatePackageItem(VisualState state, IPackage package = null)
{
package ??= m_PackageDatabase.GetPackage(state?.packageUniqueId);
if (package == null)
return;
var item = GetPackageItem(state.packageUniqueId);
if (item != null)
{
item.SetPackage(package);
// Check if group has changed
var page = m_PageManager.activePage;
var groupName = page.GetGroupName(package);
if (item.packageGroup.name != groupName)
{
var oldGroup = GetOrCreateGroup(item.packageGroup.name);
var newGroup = GetOrCreateGroup(groupName);
state.groupName = groupName;
// Replace PackageItem
m_PackageItemsLookup[package.uniqueId] = newGroup.AddPackageItem(package, state);
oldGroup.RemovePackageItem(item);
if (!oldGroup.packageItems.Any())
m_ItemsList.Remove(oldGroup);
ReorderGroups(page.visualStates.orderedGroups);
}
item.UpdateVisualState(state);
}
else
{
var group = GetOrCreateGroup(state.groupName);
item = group.AddPackageItem(package, state);
m_PackageItemsLookup[package.uniqueId] = item;
}
}
private PackageGroup GetOrCreateGroup(string groupName)
{
var group = packageGroups.FirstOrDefault(g => string.Compare(g.name, groupName, StringComparison.InvariantCultureIgnoreCase) == 0);
if (group != null)
return group;
var hidden = string.IsNullOrEmpty(groupName);
var expanded = m_PageManager.activePage.IsGroupExpanded(groupName);
group = new PackageGroup(m_ResourceLoader, m_PageManager, m_PackageDatabase, groupName, expanded, hidden);
if (!hidden)
{
group.onGroupToggle += value =>
{
var s = GetFirstSelectedItem();
if (value && s != null && group.Contains(s))
EditorApplication.delayCall += ScrollToSelection;
};
}
m_ItemsList.Add(group);
return group;
}
private void RemovePackageItem(string packageUniqueId)
{
var item = GetPackageItem(packageUniqueId);
if (item != null)
{
item.packageGroup.RemovePackageItem(item);
m_PackageItemsLookup.Remove(packageUniqueId);
}
}
public void OnVisualStateChange(IEnumerable<VisualState> visualStates)
{
if (!visualStates.Any())
return;
foreach (var state in visualStates)
GetPackageItem(state.packageUniqueId)?.UpdateVisualState(state);
var page = m_PageManager.activePage;
ReorderGroups(page.visualStates.orderedGroups);
foreach (var group in packageGroups)
group.RefreshHeaderVisibility();
if (page.UpdateSelectionIfCurrentSelectionIsInvalid())
ScrollToSelection();
}
private void ReorderGroups(IList<string> orderedGroups)
{
if (orderedGroups.Count <= 1)
return;
m_ItemsList.Sort((x, y) => orderedGroups.IndexOf(x.name).CompareTo(orderedGroups.IndexOf(y.name)));
}
public void OnListRebuild(IPage page)
{
m_ItemsList.Clear();
m_PackageItemsLookup.Clear();
foreach (var visualState in page.visualStates)
AddOrUpdatePackageItem(visualState);
ReorderGroups(page.visualStates.orderedGroups);
foreach (var group in packageGroups)
group.RefreshHeaderVisibility();
m_PageManager.activePage.UpdateSelectionIfCurrentSelectionIsInvalid();
ScrollToSelection();
}
public void OnListUpdate(ListUpdateArgs args)
{
var page = args.page;
var numItems = m_PackageItemsLookup.Count;
foreach (var package in args.removed)
RemovePackageItem(package?.uniqueId);
var itemsRemoved = numItems != m_PackageItemsLookup.Count;
numItems = m_PackageItemsLookup.Count;
foreach (var package in args.added.Concat(args.updated))
{
var visualState = page.visualStates.Get(package.uniqueId) ?? new VisualState(package.uniqueId, string.Empty, page.GetDefaultLockState(package));
AddOrUpdatePackageItem(visualState, package);
}
var itemsAdded = numItems != m_PackageItemsLookup.Count;
if (args.reorder)
{
if (packageGroups.Any(group => !group.isHidden))
{
// re-order if there are any added or updated items
foreach (var group in packageGroups)
group.ClearPackageItems();
foreach (var state in page.visualStates)
{
var packageItem = GetPackageItem(state.packageUniqueId);
// For when user switch account and packageList gets refreshed
packageItem?.packageGroup.AddPackageItem(packageItem);
}
m_PackageItemsLookup = packageItems.ToDictionary(item => item.package.uniqueId, item => item);
}
}
if (itemsRemoved || itemsAdded)
{
ReorderGroups(page.visualStates.orderedGroups);
foreach (var group in packageGroups)
group.RefreshHeaderVisibility();
if (m_PageManager.activePage.UpdateSelectionIfCurrentSelectionIsInvalid())
ScrollToSelection();
}
else
{
ReorderGroups(page.visualStates.orderedGroups);
}
}
private PackageItem GetPackageItemFromMouseEvent(MouseDownEvent evt)
{
var target = evt.elementTarget;
while (target != null && target != this)
{
if (target is PackageItem packageItem)
return packageItem;
target = target.parent;
}
return null;
}
private void SelectAllBetween(string firstPackageUniqueId, string secondPackageUniqueId)
{
var newSelections = new List<PackageAndVersionIdPair>();
var inBetweenTwoPackages = false;
if (firstPackageUniqueId == secondPackageUniqueId)
{
newSelections.Add(new PackageAndVersionIdPair(firstPackageUniqueId));
}
else
{
foreach (var item in packageItems)
{
if (!UIUtils.IsElementVisible(item))
continue;
var packageUniqueId = item.package?.uniqueId;
if (string.IsNullOrEmpty(packageUniqueId))
continue;
var matchFirstPackage = packageUniqueId == firstPackageUniqueId;
var matchSecondPackage = packageUniqueId == secondPackageUniqueId;
if (matchFirstPackage || matchSecondPackage || inBetweenTwoPackages)
newSelections.Add(new PackageAndVersionIdPair(packageUniqueId));
if (matchFirstPackage || matchSecondPackage)
{
inBetweenTwoPackages = !inBetweenTwoPackages;
if (!inBetweenTwoPackages)
{
// If we match the second package before we matched the first package then we want to reverse the order
// to first sure that the first selected is in front. Otherwise Shift selections might have weird behaviours.
if (matchFirstPackage)
newSelections.Reverse();
break;
}
}
}
}
m_PageManager.activePage.SetNewSelection(newSelections, true);
}
private void SelectAllVisible()
{
var validItems = packageItems.Where(p => !string.IsNullOrEmpty(p.package?.uniqueId) && UIUtils.IsElementVisible(p));
m_PageManager.activePage.SetNewSelection(validItems.Select(item => new PackageAndVersionIdPair(item.package.uniqueId)), true);
}
private void OnMouseDown(MouseDownEvent evt)
{
if (evt.button != 0)
return;
var packageItem = GetPackageItemFromMouseEvent(evt);
if (packageItem == null)
return;
if (evt.shiftKey)
{
var firstItem = m_PageManager.activePage.GetSelection().firstSelection?.packageUniqueId;
SelectAllBetween(firstItem, packageItem.package.uniqueId);
return;
}
if (evt.actionKey)
packageItem.ToggleSelectMainItem();
else
packageItem.SelectMainItem();
}
private bool HandleShiftSelection(NavigationMoveEvent evt)
{
if (!evt.shiftKey)
return false;
if (evt.direction == NavigationMoveEvent.Direction.Up || evt.direction == NavigationMoveEvent.Direction.Down)
{
var selection = m_PageManager.activePage.GetSelection();
var firstItem = selection.firstSelection?.packageUniqueId;
var lastItem = selection.lastSelection?.packageUniqueId;
var nextItem = FindNextVisiblePackageItem(GetPackageItem(lastItem), evt.direction == NavigationMoveEvent.Direction.Up);
SelectAllBetween(firstItem, nextItem?.package.uniqueId ?? lastItem);
return true;
}
return false;
}
public void OnKeyDownShortcut(KeyDownEvent evt)
{
if (!UIUtils.IsElementVisible(this))
return;
switch (evt.keyCode)
{
case KeyCode.A when evt.actionKey:
SelectAllVisible();
evt.StopPropagation();
break;
// On mac moving up and down will trigger the sound of an incorrect key being pressed
// This should be fixed in UUM-26264 by the UIToolkit team
case KeyCode.DownArrow:
case KeyCode.UpArrow:
evt.StopPropagation();
break;
}
}
public void OnNavigationMoveShortcut(NavigationMoveEvent evt)
{
if (!UIUtils.IsElementVisible(this))
return;
if (HandleShiftSelection(evt))
{
evt.StopPropagation();
return;
}
if (evt.direction == NavigationMoveEvent.Direction.Up)
{
if (SelectNext(true))
evt.StopPropagation();
}
else if (evt.direction == NavigationMoveEvent.Direction.Down)
{
if (SelectNext(false))
evt.StopPropagation();
}
}
internal bool SelectNext(bool reverseOrder)
{
var nextElement = FindNextVisibleSelectableItem(reverseOrder);
if (nextElement != null)
{
m_PageManager.activePage.SetNewSelection(nextElement.package, nextElement.targetVersion);
ScrollIfNeeded(nextElement.element);
return true;
}
return false;
}
private ISelectableItem FindNextVisibleSelectableItem(bool reverseOrder)
{
// We use the `lastSelection` here as that is the one the user interacted last and it feels more natural that way when navigating with keyboard
var lastSelection = m_PageManager.activePage.GetSelection().lastSelection;
var packageItem = GetPackageItem(lastSelection?.packageUniqueId);
if (packageItem == null)
return null;
return FindNextVisiblePackageItem(packageItem, reverseOrder);
}
public void OnActivePageChanged(IPage page)
{
// Check if groups have changed only for InProject page
if (page.id != InProjectPage.k_Id || !m_PageRefreshHandler.IsInitialFetchingDone(page))
return;
var needGroupsReordering = false;
var currentPackageItems = packageItems.ToList();
foreach (var packageItem in currentPackageItems)
{
// Check if group has changed
var package = packageItem.package;
var groupName = page.GetGroupName(package);
if (packageItem.packageGroup.name != groupName)
{
var oldGroup = GetOrCreateGroup(packageItem.packageGroup.name);
var newGroup = GetOrCreateGroup(groupName);
var state = page.visualStates.Get(package?.uniqueId);
if (state != null)
state.groupName = groupName;
// Move PackageItem from old group to new group
oldGroup.RemovePackageItem(packageItem);
newGroup.AddPackageItem(packageItem);
needGroupsReordering = true;
if (!oldGroup.packageItems.Any())
m_ItemsList.Remove(oldGroup);
}
}
if (needGroupsReordering)
ReorderGroups(page.visualStates.orderedGroups);
}
private static PackageItem FindNextVisiblePackageItem(PackageItem packageItem, bool reverseOrder)
{
var nextVisibleItem = UIUtils.FindNextSibling(packageItem, reverseOrder, UIUtils.IsElementVisible) as PackageItem;
if (nextVisibleItem == null)
{
Func<VisualElement, bool> nonEmptyGroup = (element) =>
{
var group = element as PackageGroup;
return group.packageItems.Any(p => UIUtils.IsElementVisible(p));
};
var nextGroup = UIUtils.FindNextSibling(packageItem.packageGroup, reverseOrder, nonEmptyGroup) as PackageGroup;
if (nextGroup != null)
nextVisibleItem = reverseOrder ? nextGroup.packageItems.LastOrDefault(p => UIUtils.IsElementVisible(p))
: nextGroup.packageItems.FirstOrDefault(p => UIUtils.IsElementVisible(p));
}
return nextVisibleItem;
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageListScrollView.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageListScrollView.cs",
"repo_id": "UnityCsReference",
"token_count": 9282
} | 411 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Globalization;
using UnityEngine.UIElements;
namespace UnityEditor.PackageManager.UI.Internal
{
internal class PackageStatusBar : VisualElement
{
[Serializable]
public new class UxmlSerializedData : VisualElement.UxmlSerializedData
{
public override object CreateInstance() => new PackageStatusBar();
}
internal static readonly string k_OfflineErrorMessage = L10n.Tr("You seem to be offline");
private enum StatusType { Normal, Loading, Error }
private IResourceLoader m_ResourceLoader;
private IApplicationProxy m_Application;
private IBackgroundFetchHandler m_BackgroundFetchHandler;
private IPageRefreshHandler m_PageRefreshHandler;
private IPageManager m_PageManager;
private IUnityConnectProxy m_UnityConnect;
private void ResolveDependencies()
{
var container = ServicesContainer.instance;
m_ResourceLoader = container.Resolve<IResourceLoader>();
m_Application = container.Resolve<IApplicationProxy>();
m_BackgroundFetchHandler = container.Resolve<IBackgroundFetchHandler>();
m_PageRefreshHandler = container.Resolve<IPageRefreshHandler>();
m_PageManager = container.Resolve<IPageManager>();
m_UnityConnect = container.Resolve<IUnityConnectProxy>();
}
public PackageStatusBar()
{
ResolveDependencies();
var root = m_ResourceLoader.GetTemplate("PackageStatusBar.uxml");
Add(root);
cache = new VisualElementCache(root);
var dropdownButton = new DropdownButton();
dropdownButton.name = "refreshButton";
refreshButtonContainer.Add(dropdownButton);
statusLabel.ShowTextTooltipOnSizeChange();
}
public void OnEnable()
{
m_PageRefreshHandler.onRefreshOperationStart += UpdateStatusMessage;
m_PageRefreshHandler.onRefreshOperationFinish += UpdateStatusMessage;
m_PageRefreshHandler.onRefreshOperationError += OnRefreshOperationError;
m_PageManager.onActivePageChanged += OnActivePageChanged;
m_Application.onInternetReachabilityChange += OnInternetReachabilityChange;
m_UnityConnect.onUserLoginStateChange += OnUserLoginStateChange;
m_BackgroundFetchHandler.onCheckUpdateProgress += OnCheckUpdateProgress;
refreshButton.SetIcon(Icon.Refresh);
refreshButton.mainButton.tooltip = L10n.Tr("Refresh list");
refreshButton.clicked += () =>
{
m_PageRefreshHandler.Refresh(m_PageManager.activePage);
PackageManagerWindowAnalytics.SendEvent("refreshList");
};
refreshButton.SetEnabled(true);
Refresh(m_PageManager.activePage, m_UnityConnect.isUserLoggedIn);
}
public void OnDisable()
{
m_PageRefreshHandler.onRefreshOperationStart -= UpdateStatusMessage;
m_PageRefreshHandler.onRefreshOperationFinish -= UpdateStatusMessage;
m_PageRefreshHandler.onRefreshOperationError -= OnRefreshOperationError;
m_PageManager.onActivePageChanged -= OnActivePageChanged;
m_Application.onInternetReachabilityChange -= OnInternetReachabilityChange;
m_UnityConnect.onUserLoginStateChange -= OnUserLoginStateChange;
m_BackgroundFetchHandler.onCheckUpdateProgress -= OnCheckUpdateProgress;
}
public void DisableRefresh()
{
refreshButton.SetEnabled(false);
}
private void OnInternetReachabilityChange(bool value)
{
UpdateStatusMessage();
}
private void OnActivePageChanged(IPage page)
{
Refresh(page, m_UnityConnect.isUserLoggedIn);
}
private void OnUserLoginStateChange(bool isUserInfoReady, bool isUserLoggedIn)
{
Refresh(m_PageManager.activePage, isUserLoggedIn);
}
private void OnRefreshOperationError(UIError error)
{
UpdateStatusMessage();
}
private bool IsVisible(IPage page, bool isUserLoggedIn)
{
return page.id != MyAssetsPage.k_Id || isUserLoggedIn;
}
private void Refresh(IPage page, bool isUserLoggedIn)
{
var visibility = IsVisible(page, isUserLoggedIn);
UIUtils.SetElementDisplay(this, visibility);
if (!visibility)
return;
RefreshCheckUpdateMenuOption(page);
UpdateStatusMessage();
}
private void UpdateStatusMessage()
{
var page = m_PageManager.activePage;
if (m_PageRefreshHandler.IsRefreshInProgress(page))
{
SetStatusMessage(StatusType.Loading, L10n.Tr("Refreshing list..."));
return;
}
if (page.id == MyAssetsPage.k_Id && m_BackgroundFetchHandler.isCheckUpdateInProgress)
{
SetStatusMessage(StatusType.Loading, L10n.Tr("Checking for updates..."));
return;
}
var errorMessage = string.Empty;
var refreshError = m_PageRefreshHandler.GetRefreshError(page);
if (!m_Application.isInternetReachable)
errorMessage = k_OfflineErrorMessage;
else if (refreshError != null)
{
var seeDetailInConsole = (UIError.Attribute.DetailInConsole & refreshError.attribute) != 0;
errorMessage = seeDetailInConsole
? L10n.Tr("Refresh error, see Console window")
: L10n.Tr("Refresh error");
}
if (!string.IsNullOrEmpty(errorMessage))
{
SetStatusMessage(StatusType.Error, errorMessage);
return;
}
SetLastUpdateStatusMessage();
}
private void SetStatusMessage(StatusType status, string message)
{
if (status == StatusType.Loading)
{
loadingSpinner.Start();
UIUtils.SetElementDisplay(refreshButton, false);
}
else
{
loadingSpinner.Stop();
UIUtils.SetElementDisplay(refreshButton, true);
}
UIUtils.SetElementDisplay(errorIcon, status == StatusType.Error);
statusLabel.text = message;
}
private void SetLastUpdateStatusMessage()
{
var page = m_PageManager.activePage;
var timestamp = m_PageRefreshHandler.GetRefreshTimestamp(page);
var dt = new DateTime(timestamp);
var dateAndTime = dt.ToString("MMM d, HH:mm", CultureInfo.CreateSpecificCulture("en-US"));
var label = timestamp == 0 ? string.Empty : string.Format(L10n.Tr("Last update {0}"), dateAndTime);
SetStatusMessage(StatusType.Normal, label);
}
internal void OnCheckUpdateProgress()
{
if (m_PageManager.activePage.id != MyAssetsPage.k_Id)
return;
UpdateStatusMessage();
}
private void RefreshCheckUpdateMenuOption(IPage page)
{
if (page.id == MyAssetsPage.k_Id)
{
var menu = new DropdownMenu();
menu.AppendAction(L10n.Tr("Check for updates"),
_ =>
{
m_BackgroundFetchHandler.ForceCheckUpdateAllCachedAndImportedPackages();
PackageManagerWindowAnalytics.SendEvent("checkForUpdates");
},
_ => m_BackgroundFetchHandler.isCheckUpdateInProgress ? DropdownMenuAction.Status.Disabled : DropdownMenuAction.Status.Normal);
refreshButton.menu = menu;
}
else
refreshButton.menu = null;
}
private VisualElementCache cache { get; set; }
private LoadingSpinner loadingSpinner => cache.Get<LoadingSpinner>("loadingSpinner");
private Label errorIcon => cache.Get<Label>("errorIcon");
private Label statusLabel => cache.Get<Label>("statusLabel");
private VisualElement refreshButtonContainer => cache.Get<VisualElement>("refreshButtonContainer");
private DropdownButton refreshButton => cache.Get<DropdownButton>("refreshButton");
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageStatusBar.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageStatusBar.cs",
"repo_id": "UnityCsReference",
"token_count": 3828
} | 412 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Linq;
using UnityEditor.Experimental;
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.PackageManager.UI.Internal;
internal class SelectionWindowRow : VisualElement
{
private static Texture2D s_FolderIcon;
internal static Texture2D folderIcon => s_FolderIcon ??= EditorGUIUtility.FindTexture(EditorResources.folderIconName);
private static readonly string k_RemoveIconTooltip = L10n.Tr("Remove");
internal static readonly string k_InfoLabel = L10n.Tr("moved");
internal static readonly string k_InfoLabelTooltip = L10n.Tr("This asset was moved. The original location is {0}.");
private readonly Label m_RemoveIcon;
private readonly Label m_InfoLabel;
private readonly Label m_NameLabel;
private readonly VisualElement m_FileIcon;
private readonly Toggle m_Toggle;
public Toggle toggle => m_Toggle;
public SelectionWindowRow()
{
var rowContainer = new VisualElement { classList = { "row-container" } };
Add(rowContainer);
var toggleRow = new VisualElement { classList = { "toggle-row" } };
rowContainer.Add(toggleRow);
m_Toggle = new Toggle { name = "toggle", classList = { "toggle" }, label = "Toggle" };
toggleRow.Add(m_Toggle);
m_NameLabel = m_Toggle.Q<Label>();
m_NameLabel.name = "name";
m_InfoLabel = new Label { name = "info", classList = { "text", "label" } };
m_Toggle.hierarchy.Insert(0, m_InfoLabel);
m_FileIcon = new VisualElement { name = "icon" };
m_Toggle.hierarchy.Insert(2, m_FileIcon);
var labels = new VisualElement { classList = { "labels" } };
rowContainer.Add(labels);
m_RemoveIcon = new Label { name = "remove", classList = { "icon", "label" }, tooltip = k_RemoveIconTooltip, displayTooltipWhenElided = true};
labels.Add(m_RemoveIcon);
}
public void SetData(SelectionWindowData windowData, SelectionWindowData.Node node, bool isExpanded)
{
userData = node;
var selected = windowData.IsSelected(node.index);
m_NameLabel.text = node.name;
m_Toggle.SetValueWithoutNotify(selected);
RefreshFileIcon(node);
RefreshInfoLabel(node);
var removeIconVisible = (!node.isFolder && selected) || (node.isFolder && !isExpanded &&
windowData.GetChildren(node, true).Any(n => !n.isFolder && windowData.IsSelected(n.index)));
UIUtils.SetElementDisplay(m_RemoveIcon, removeIconVisible);
}
private void RefreshFileIcon(SelectionWindowData.Node node)
{
var icon = node.isFolder
? folderIcon
: InternalEditorUtility.GetIconForFile(!string.IsNullOrEmpty(node.path)
? node.path
: "unknown.txt");
m_FileIcon.style.backgroundImage = new StyleBackground(icon);
}
private void RefreshInfoLabel(SelectionWindowData.Node node)
{
if (node?.isMoved == true)
{
m_InfoLabel.text = k_InfoLabel;
m_InfoLabel.tooltip = string.Format(k_InfoLabelTooltip, node.asset.origin.assetPath);
}
else
{
m_InfoLabel.text = string.Empty;
m_InfoLabel.tooltip = string.Empty;
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/UI/SelectionWindow/SelectionWindowRow.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/SelectionWindow/SelectionWindowRow.cs",
"repo_id": "UnityCsReference",
"token_count": 1339
} | 413 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.