Ejemplo n.º 1
0
 public static void Load()
 {
     using (ProfilingUtility.SampleBlock("Load Icons"))
     {
         Language.Load();
     }
 }
Ejemplo n.º 2
0
        public static void Dump(TimeSpan threshold)
        {
            if (ProfilingUtility.allRootSegments.Count == 0)
            {
                return;
            }

            var sb = new StringBuilder();

            foreach (var rootSegmentPair in ProfilingUtility.allRootSegments)
            {
                var thread      = rootSegmentPair.Key;
                var rootSegment = rootSegmentPair.Value;

                if (rootSegment.children.Count == 0)
                {
                    return;
                }

                sb.Append($"Thread {thread.Name ?? "#" + thread.ManagedThreadId}: ");
                Append(sb, 0, rootSegment, threshold);
                sb.AppendLine();
            }

            ProfilingUtility.Clear();

            Debug.Log(sb);
        }
        /// <remarks>This may return an open-constructed method as well.</remarks>
        public static MethodInfo MakeGenericMethodVia(this MethodInfo openConstructedMethod, params Type[] closedConstructedParameterTypes)
        {
            using (ProfilingUtility.SampleBlock(nameof(MakeGenericMethodVia)))
            {
                Ensure.That(nameof(openConstructedMethod)).IsNotNull(openConstructedMethod);
                Ensure.That(nameof(closedConstructedParameterTypes)).IsNotNull(closedConstructedParameterTypes);

                if (!openConstructedMethod.ContainsGenericParameters)
                {
                    // The method contains no generic parameters,
                    // it is by definition already resolved.
                    return(openConstructedMethod);
                }

                var openConstructedParameterTypes = openConstructedMethod.GetParameters().Select(p => p.ParameterType).ToArray();

                if (openConstructedParameterTypes.Length != closedConstructedParameterTypes.Length)
                {
                    throw new ArgumentOutOfRangeException(nameof(closedConstructedParameterTypes));
                }

                var resolvedGenericParameters = new Dictionary <Type, Type>();

                for (var i = 0; i < openConstructedParameterTypes.Length; i++)
                {
                    // Resolve each open-constructed parameter type via the equivalent
                    // closed-constructed parameter type.

                    var openConstructedParameterType   = openConstructedParameterTypes[i];
                    var closedConstructedParameterType = closedConstructedParameterTypes[i];

                    openConstructedParameterType.MakeGenericTypeVia(closedConstructedParameterType, resolvedGenericParameters);
                }

                // Construct the final closed-constructed method from the resolved arguments

                var openConstructedGenericArguments   = openConstructedMethod.GetGenericArguments();
                var closedConstructedGenericArguments = openConstructedGenericArguments.Select(openConstructedGenericArgument =>
                {
                    // If the generic argument has been successfully resolved, use it;
                    // otherwise, leave the open-constructed argument in place.

                    if (resolvedGenericParameters.ContainsKey(openConstructedGenericArgument))
                    {
                        return(resolvedGenericParameters[openConstructedGenericArgument]);
                    }
                    else
                    {
                        return(openConstructedGenericArgument);
                    }
                }).ToArray();

                return(openConstructedMethod.MakeGenericMethod(closedConstructedGenericArguments));
            }
        }
Ejemplo n.º 4
0
        public static EditorTexture Load(IResourceProvider resources, string path, CreateTextureOptions options, bool required)
        {
            using (ProfilingUtility.SampleBlock("Load Editor Texture"))
            {
                Ensure.That(nameof(resources)).IsNotNull(resources);
                Ensure.That(nameof(path)).IsNotNull(path);

                var set       = new EditorTexture();
                var name      = Path.GetFileNameWithoutExtension(path).PartBefore('@');
                var extension = Path.GetExtension(path);
                var directory = Path.GetDirectoryName(path);

                var personalPath     = Path.Combine(directory, $"{name}{extension}");
                var professionalPath = Path.Combine(directory, $"{name}@Pro{extension}");

                if (resources.FileExists(personalPath))
                {
                    var personalTexture = resources.LoadTexture(personalPath, options);

                    if (personalTexture != null)
                    {
                        set.personal.Add(personalTexture.width, personalTexture);
                    }
                }

                if (resources.FileExists(professionalPath))
                {
                    var professionalTexture = resources.LoadTexture(professionalPath, options);

                    if (professionalTexture != null)
                    {
                        set.professional.Add(professionalTexture.width, professionalTexture);
                    }
                }

                if (set.personal.Count == 0)
                {
                    if (required)
                    {
                        Debug.LogWarning($"Missing editor texture: {name}\n{resources.DebugPath(path)}");
                    }

                    // Never return an empty set; the codebase assumes this guarantee

                    return(null);
                }

                return(set);
            }
        }
Ejemplo n.º 5
0
        public static void DumpThisThread(TimeSpan threshold)
        {
            var sb = new StringBuilder();

            var rootSegment = ProfilingUtility.rootSegment;

            if (rootSegment.children.Count == 0)
            {
                return;
            }

            Append(sb, 0, rootSegment, threshold);

            ProfilingUtility.ClearThisThread();

            Debug.Log(sb);
        }
        private static void FullDeserializeJson(fsSerializer serializer, string json, ref object instance, bool forceReflected)
        {
            using (ProfilingUtility.SampleBlock("DeserializeJson"))
            {
                var fsData = fsJsonParser.Parse(json);

                fsResult result;

                if (forceReflected)
                {
                    result = serializer.TryDeserialize(fsData, instance.GetType(), typeof(fsReflectedConverter), ref instance);
                }
                else
                {
                    result = serializer.TryDeserialize(fsData, ref instance);
                }

                HandleFullResult("Deserialization", result, instance as UnityObject);
            }
        }
        private static string FullSerializeJson(fsSerializer serializer, object instance, bool forceReflected)
        {
            using (ProfilingUtility.SampleBlock("SerializeJson"))
            {
                fsData data;

                fsResult result;

                if (forceReflected)
                {
                    result = serializer.TrySerialize(instance.GetType(), typeof(fsReflectedConverter), instance, out data);
                }
                else
                {
                    result = serializer.TrySerialize(instance, out data);
                }

                HandleFullResult("Serialization", result, instance as UnityObject);

                return(fsJsonPrinter.CompressedJson(data));
            }
        }
Ejemplo n.º 8
0
 public void End()
 {
     stopwatch.Stop();
     cancellation.Dispose();
     ProfilingUtility.EndSample();
 }
Ejemplo n.º 9
0
 public void Begin()
 {
     stopwatch = Stopwatch.StartNew();
     ProfilingUtility.BeginSample(title);
 }
Ejemplo n.º 10
0
        private static void Initialize()
        {
            using (ProfilingUtility.SampleBlock("Plugin Container Initialization"))
            {
                if (initialized || initializing)
                {
                    Debug.LogWarning("Attempting to re-initialize plugin container, ignoring.\n");
                    return;
                }

                if (!isAssetDatabaseReliable)
                {
                    Debug.LogWarning("Initializing plugin container while asset database is not initialized.\nLoading assets might fail!");
                }

                initializing = true;

                pluginTypesById = Codebase.GetTypeRegistrations <RegisterPluginAttribute>()
                                  .ToDictionary(r => r.id, r => r.type);

                pluginDependencies = new Dictionary <string, HashSet <string> >();

                foreach (var pluginId in pluginTypesById.Keys)
                {
                    pluginDependencies.Add(pluginId, new HashSet <string>());
                }

                foreach (var pluginDependencyRegistration in Codebase.GetAssemblyAttributes <RegisterPluginDependencyAttribute>())
                {
                    if (!pluginDependencies.TryGetValue(pluginDependencyRegistration.dependerId, out var dependencies))
                    {
                        dependencies = new HashSet <string>();
                        pluginDependencies.Add(pluginDependencyRegistration.dependerId, dependencies);
                    }

                    dependencies.Add(pluginDependencyRegistration.dependencyId);
                }

                var moduleTypeRegistrations = Codebase.GetTypeRegistrations <RegisterPluginModuleTypeAttribute>();

                pluginsById = new Dictionary <string, Plugin>();

                var allModules = new List <IPluginModule>();

                foreach (var pluginId in pluginTypesById.Keys.OrderByDependencies(pluginId => pluginDependencies[pluginId]))
                {
                    var pluginType = pluginTypesById[pluginId];

                    Plugin plugin;

                    try
                    {
                        using (ProfilingUtility.SampleBlock($"{pluginType.Name} (Instantiation)"))
                        {
                            plugin = (Plugin)pluginType.Instantiate();
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new TargetInvocationException($"Could not instantiate plugin '{pluginId}' ('{pluginType}').", ex);
                    }

                    var modules = new List <IPluginModule>();

                    foreach (var moduleTypeRegistration in moduleTypeRegistrations)
                    {
                        var moduleType = moduleTypeRegistration.type;
                        var required   = moduleTypeRegistration.required;

                        try
                        {
                            var moduleProperty = pluginType.GetProperties().FirstOrDefault(p => p.PropertyType.IsAssignableFrom(moduleType));

                            if (moduleProperty == null)
                            {
                                continue;
                            }

                            IPluginModule module = null;

                            var moduleOverrideType = Codebase.GetTypeRegistrations <MapToPluginAttribute>()
                                                     .FirstOrDefault(r => r.pluginId == pluginId &&
                                                                     moduleType.IsAssignableFrom(r.type) &&
                                                                     r.type.IsConcrete())?.type;

                            if (moduleOverrideType != null)
                            {
                                try
                                {
                                    using (ProfilingUtility.SampleBlock($"{moduleOverrideType.Name} (Instantiation)"))
                                    {
                                        module = (IPluginModule)InstantiateMappedType(moduleOverrideType, plugin);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    throw new TargetInvocationException($"Failed to instantiate user-defined plugin module '{moduleOverrideType}' for '{pluginId}'.", ex);
                                }
                            }
                            else if (moduleType.IsConcrete())
                            {
                                try
                                {
                                    using (ProfilingUtility.SampleBlock($"{moduleType.Name} (Instantiation)"))
                                    {
                                        module = (IPluginModule)InstantiateMappedType(moduleType, plugin);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    throw new TargetInvocationException($"Failed to instantiate built-in plugin module '{moduleType}' for '{pluginId}'.", ex);
                                }
                            }
                            else if (required)
                            {
                                throw new InvalidImplementationException($"Missing implementation of plugin module '{moduleType}' for '{pluginId}'.");
                            }

                            if (module != null)
                            {
                                moduleProperty.SetValue(plugin, module, null);

                                modules.Add(module);
                                allModules.Add(module);
                            }
                        }
                        catch (Exception ex)
                        {
                            Debug.LogException(ex);
                        }
                    }

                    pluginsById.Add(plugin.id, plugin);

                    foreach (var module in modules)
                    {
                        try
                        {
                            using (ProfilingUtility.SampleBlock($"{module.GetType().Name} (Initialization)"))
                            {
                                module.Initialize();
                            }
                        }
                        catch (Exception ex)
                        {
                            Debug.LogException(new Exception($"Failed to initialize plugin module '{plugin.id}.{module.GetType()}'.", ex));
                        }
                    }

                    if (plugin.manifest.versionMismatch)
                    {
                        anyVersionMismatch = true;
                    }
                }

                initializing = false;

                initialized = true;

                using (ProfilingUtility.SampleBlock($"Product Container Initialization"))
                {
                    ProductContainer.Initialize();
                }

                foreach (var module in allModules)
                {
                    try
                    {
                        using (ProfilingUtility.SampleBlock($"{module.GetType().Name} (Late Initialization)"))
                        {
                            module.LateInitialize();
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.LogException(new Exception($"Failed to late initialize plugin module '{module.plugin.id}.{module.GetType()}'.", ex));
                    }
                }

                var afterPluginTypes = Codebase.GetRegisteredTypes <InitializeAfterPluginsAttribute>();

                using (ProfilingUtility.SampleBlock($"BeforeInitializeAfterPlugins"))
                {
                    EditorApplicationUtility.BeforeInitializeAfterPlugins();
                }

                foreach (var afterPluginType in afterPluginTypes)
                {
                    using (ProfilingUtility.SampleBlock($"{afterPluginType.Name} (Static Initializer)"))
                    {
                        RuntimeHelpers.RunClassConstructor(afterPluginType.TypeHandle);
                    }
                }

                using (ProfilingUtility.SampleBlock($"AfterInitializeAfterPlugins"))
                {
                    EditorApplicationUtility.AfterInitializeAfterPlugins();
                }

                using (ProfilingUtility.SampleBlock($"Launch Setup Wizards"))
                {
                    // Automatically show setup wizards

                    if (!EditorApplication.isPlayingOrWillChangePlaymode)
                    {
                        var productsRequiringSetup    = ProductContainer.products.Where(product => product.requiresSetup).ToHashSet();
                        var productsHandlingAllSetups = productsRequiringSetup.ToHashSet();

                        // Do not show product setups if another product already
                        // includes all the same plugins or more. For example,
                        // if both Bolt and Ludiq require setup, but Bolt requires
                        // all of the Ludiq plugins, then only the Bolt setup wizard
                        // should be shown.
                        foreach (var product in productsRequiringSetup)
                        {
                            foreach (var otherProduct in productsRequiringSetup)
                            {
                                if (product == otherProduct)
                                {
                                    continue;
                                }

                                var productPlugins      = product.plugins.ResolveDependencies().ToHashSet();
                                var otherProductPlugins = otherProduct.plugins.ResolveDependencies().ToHashSet();

                                if (productPlugins.IsSubsetOf(otherProductPlugins))
                                {
                                    productsHandlingAllSetups.Remove(product);
                                }
                            }
                        }

                        foreach (var product in productsHandlingAllSetups)
                        {
                            // Delay call is used here to avoid showing multiple wizards during an import
                            EditorApplication.delayCall += () => SetupWizard.Show(product);
                        }
                    }
                }

                using (ProfilingUtility.SampleBlock($"Launch Update Wizard"))
                {
                    // Automatically show update wizard

                    if (!EditorApplication.isPlayingOrWillChangePlaymode && plugins.Any(plugin => plugin.manifest.versionMismatch))
                    {
                        // Delay call seems to be needed here to avoid arcane exceptions...
                        // Too lazy to debug why, it works that way.
                        EditorApplication.delayCall += UpdateWizard.Show;
                    }
                }

                using (ProfilingUtility.SampleBlock($"Delayed Calls"))
                {
                    lock (delayQueue)
                    {
                        while (delayQueue.Count > 0)
                        {
                            delayQueue.Dequeue().Invoke();
                        }
                    }
                }

                InternalEditorUtility.RepaintAllViews();

                ProfilingUtility.Clear();
                //ConsoleProfiler.Dump();
            }
        }
Ejemplo n.º 11
0
        public static bool CanMakeGenericTypeVia(this Type openConstructedType, Type closedConstructedType)
        {
            using (ProfilingUtility.SampleBlock(nameof(CanMakeGenericTypeVia)))
            {
                Ensure.That(nameof(openConstructedType)).IsNotNull(openConstructedType);
                Ensure.That(nameof(closedConstructedType)).IsNotNull(closedConstructedType);

                if (openConstructedType == closedConstructedType)
                {
                    return(true);
                }

                if (openConstructedType.IsGenericParameter)                 // e.g.: T
                {
                    // The open-constructed type is a generic parameter.

                    // First, check if all special attribute constraints are respected.

                    var constraintAttributes = openConstructedType.GenericParameterAttributes;

                    if (constraintAttributes != GenericParameterAttributes.None)
                    {
                        // e.g.: where T : struct
                        if (constraintAttributes.HasFlag(GenericParameterAttributes.NotNullableValueTypeConstraint) &&
                            !closedConstructedType.IsValueType)
                        {
                            return(false);
                        }

                        // e.g.: where T : class
                        if (constraintAttributes.HasFlag(GenericParameterAttributes.ReferenceTypeConstraint) &&
                            closedConstructedType.IsValueType)
                        {
                            return(false);
                        }

                        // e.g.: where T : new()
                        if (constraintAttributes.HasFlag(GenericParameterAttributes.DefaultConstructorConstraint) &&
                            closedConstructedType.GetConstructor(Type.EmptyTypes) == null)
                        {
                            return(false);
                        }
                    }

                    // Then, check if all type constraints are respected.

                    // e.g.: where T : BaseType, IInterface1, IInterface2
                    foreach (var constraint in openConstructedType.GetGenericParameterConstraints())
                    {
                        if (!constraint.IsAssignableFrom(closedConstructedType))
                        {
                            return(false);
                        }
                    }

                    return(true);
                }
                else if (openConstructedType.ContainsGenericParameters)
                {
                    // The open-constructed type is not a generic parameter but contains generic parameters.
                    // It could be either a generic type or an array.

                    if (openConstructedType.IsGenericType)                     // e.g. Generic<T1, int, T2>
                    {
                        // The open-constructed type is a generic type.

                        var openConstructedGenericDefinition = openConstructedType.GetGenericTypeDefinition();                   // e.g.: Generic<,,>
                        var openConstructedGenericArguments  = openConstructedType.GetGenericArguments();                        // e.g.: { T1, int, T2 }

                        // Check a list of possible candidate closed-constructed types:
                        //	- the closed-constructed type itself
                        //  - its base type, if any (i.e.: if the closed-constructed type is not object)
                        //  - its implemented interfaces

                        foreach (var inheritedClosedConstructedType in closedConstructedType.AndBaseTypeAndInterfaces())
                        {
                            if (inheritedClosedConstructedType.IsGenericType &&
                                inheritedClosedConstructedType.GetGenericTypeDefinition() == openConstructedGenericDefinition)
                            {
                                // The inherited closed-constructed type and the open-constructed type share the same generic definition.

                                var inheritedClosedConstructedGenericArguments = inheritedClosedConstructedType.GetGenericArguments();                                 // e.g.: { float, int, string }

                                // For each open-constructed generic argument, recursively check if it
                                // can be made into a closed-constructed type via the closed-constructed generic argument.

                                for (var i = 0; i < openConstructedGenericArguments.Length; i++)
                                {
                                    if (!openConstructedGenericArguments[i].CanMakeGenericTypeVia(inheritedClosedConstructedGenericArguments[i]))                                     // !T1.IsAssignableFromGeneric(float)
                                    {
                                        return(false);
                                    }
                                }

                                // The inherited closed-constructed type matches the generic definition of
                                // the open-constructed type and each of its type arguments are assignable to each equivalent type
                                // argument of the constraint.

                                return(true);
                            }
                        }

                        // The open-constructed type contains generic parameters, but no
                        // inherited closed-constructed type has a matching generic definition.

                        return(false);
                    }
                    else if (openConstructedType.IsArray)                     // e.g. T[]
                    {
                        // The open-constructed type is an array.

                        if (!closedConstructedType.IsArray ||
                            closedConstructedType.GetArrayRank() != openConstructedType.GetArrayRank())
                        {
                            // Fail if the closed-constructed type isn't an array of the same rank.
                            return(false);
                        }

                        var openConstructedElementType   = openConstructedType.GetElementType();
                        var closedConstructedElementType = closedConstructedType.GetElementType();

                        return(openConstructedElementType.CanMakeGenericTypeVia(closedConstructedElementType));
                    }
                    else if (openConstructedType.IsByRef)                     // e.g. T&
                    {
                        // The open-constructed type is by ref.

                        if (!closedConstructedType.IsByRef)
                        {
                            // Fail if the closed-constructed type isn't also by ref.
                            return(false);
                        }

                        var openConstructedElementType   = openConstructedType.GetElementType();
                        var closedConstructedElementType = closedConstructedType.GetElementType();

                        return(openConstructedElementType.CanMakeGenericTypeVia(closedConstructedElementType));
                    }
                    else
                    {
                        throw new NotImplementedException();
                    }
                }
                else
                {
                    // The open-constructed type does not contain generic parameters,
                    // we can proceed to a regular closed-type check.

                    return(openConstructedType.IsAssignableFrom(closedConstructedType));
                }
            }
        }
Ejemplo n.º 12
0
 public ProfilingScope(string name)
 {
     ProfilingUtility.BeginSample(name);
 }
Ejemplo n.º 13
0
 public void Dispose()
 {
     ProfilingUtility.EndSample();
 }
Ejemplo n.º 14
0
        static Codebase()
        {
            using (ProfilingUtility.SampleBlock("Codebase initialization"))
            {
                _assemblies             = new List <Assembly>();
                _runtimeAssemblies      = new List <Assembly>();
                _editorAssemblies       = new List <Assembly>();
                _ludiqAssemblies        = new List <Assembly>();
                _ludiqRuntimeAssemblies = new List <Assembly>();
                _ludiqEditorAssemblies  = new List <Assembly>();

                _types             = new List <Type>();
                _runtimeTypes      = new List <Type>();
                _editorTypes       = new List <Type>();
                _ludiqTypes        = new List <Type>();
                _ludiqRuntimeTypes = new List <Type>();
                _ludiqEditorTypes  = new List <Type>();

                foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
                {
                    if (assembly.IsDynamic)
                    {
                        continue;
                    }

                    _assemblies.Add(assembly);

                    var isRuntimeAssembly      = IsRuntimeAssembly(assembly);
                    var isEditorAssembly       = IsEditorDependentAssembly(assembly);
                    var isLudiqAssembly        = IsLudiqRuntimeDependentAssembly(assembly) || IsLudiqEditorDependentAssembly(assembly);
                    var isLudiqEditorAssembly  = IsLudiqEditorDependentAssembly(assembly);
                    var isLudiqRuntimeAssembly = IsLudiqRuntimeDependentAssembly(assembly) && !IsLudiqEditorDependentAssembly(assembly);

                    if (isRuntimeAssembly)
                    {
                        _runtimeAssemblies.Add(assembly);
                    }

                    if (isEditorAssembly)
                    {
                        _editorAssemblies.Add(assembly);
                    }

                    if (isLudiqAssembly)
                    {
                        _ludiqAssemblies.Add(assembly);
                    }

                    if (isLudiqEditorAssembly)
                    {
                        _ludiqEditorAssemblies.Add(assembly);
                    }

                    if (isLudiqRuntimeAssembly)
                    {
                        _ludiqRuntimeAssemblies.Add(assembly);
                    }

                    foreach (var type in assembly.GetTypesSafely())
                    {
                        _types.Add(type);

                        // RuntimeCodebase.PrewarmTypeDeserialization(type);

                        if (isRuntimeAssembly)
                        {
                            _runtimeTypes.Add(type);
                        }

                        if (isEditorAssembly)
                        {
                            _editorTypes.Add(type);
                        }

                        if (isLudiqAssembly)
                        {
                            _ludiqTypes.Add(type);
                        }

                        if (isLudiqEditorAssembly)
                        {
                            _ludiqEditorTypes.Add(type);
                        }

                        if (isLudiqRuntimeAssembly)
                        {
                            _ludiqRuntimeTypes.Add(type);
                        }
                    }
                }

                assemblies             = _assemblies.AsReadOnly();
                runtimeAssemblies      = _runtimeAssemblies.AsReadOnly();
                editorAssemblies       = _editorAssemblies.AsReadOnly();
                ludiqAssemblies        = _ludiqAssemblies.AsReadOnly();
                ludiqRuntimeAssemblies = _ludiqRuntimeAssemblies.AsReadOnly();
                ludiqEditorAssemblies  = _ludiqEditorAssemblies.AsReadOnly();

                types             = _types.AsReadOnly();
                runtimeTypes      = _runtimeTypes.AsReadOnly();
                editorTypes       = _editorTypes.AsReadOnly();
                ludiqTypes        = _ludiqTypes.AsReadOnly();
                ludiqRuntimeTypes = _ludiqRuntimeTypes.AsReadOnly();
                ludiqEditorTypes  = _ludiqEditorTypes.AsReadOnly();
            }
        }