text
stringlengths
7
35.3M
id
stringlengths
11
185
metadata
dict
__index_level_0__
int64
0
2.14k
using System; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using NuGet.Common; using NuGet.Protocol; using NuGet.Protocol.Core.Types; using NuGet.Versioning; namespace ICSharpCode.ILSpyCmd { internal record PackageCheckResult(NuGetVersion RunningVersion, NuGetVersion LatestVersion, bool UpdateRecommendation); // Idea from https://github.com/ErikEJ/EFCorePowerTools/blob/master/src/GUI/efcpt/Services/PackageService.cs internal static class DotNetToolUpdateChecker { static NuGetVersion CurrentPackageVersion() { return new NuGetVersion(Assembly.GetEntryAssembly()!.GetCustomAttribute<AssemblyInformationalVersionAttribute>()! .InformationalVersion); } public static async Task<PackageCheckResult> CheckForPackageUpdateAsync(string packageId) { try { using var cache = new SourceCacheContext(); var repository = Repository.Factory.GetCoreV3("https://api.nuget.org/v3/index.json"); var resource = await repository.GetResourceAsync<FindPackageByIdResource>().ConfigureAwait(false); var versions = await resource.GetAllVersionsAsync( packageId, cache, new NullLogger(), CancellationToken.None).ConfigureAwait(false); var latestVersion = versions.Where(v => v.Release == "").MaxBy(v => v); var runningVersion = CurrentPackageVersion(); int comparisonResult = latestVersion.CompareTo(runningVersion, VersionComparison.Version); return new PackageCheckResult(runningVersion, latestVersion, comparisonResult > 0); } #pragma warning disable RCS1075 // Avoid empty catch clause that catches System.Exception. catch (Exception) { } #pragma warning restore RCS1075 // Avoid empty catch clause that catches System.Exception. return null; } } }
ILSpy/ICSharpCode.ILSpyCmd/DotNetToolUpdateChecker.cs/0
{ "file_path": "ILSpy/ICSharpCode.ILSpyCmd/DotNetToolUpdateChecker.cs", "repo_id": "ILSpy", "token_count": 577 }
247
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net8.0</TargetFramework> <Nullable>enable</Nullable> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <WarningsAsErrors>nullable</WarningsAsErrors> <SignAssembly>True</SignAssembly> <AssemblyOriginatorKeyFile>..\ICSharpCode.Decompiler\ICSharpCode.Decompiler.snk</AssemblyOriginatorKeyFile> <NeutralLanguage>en-US</NeutralLanguage> <GenerateAssemblyVersionAttribute>False</GenerateAssemblyVersionAttribute> <GenerateAssemblyFileVersionAttribute>False</GenerateAssemblyFileVersionAttribute> <GenerateAssemblyInformationalVersionAttribute>False</GenerateAssemblyInformationalVersionAttribute> </PropertyGroup> <PropertyGroup> <PackageId>ICSharpCode.ILSpyX</PackageId> <PackageVersion>8.0.0.0-noversion</PackageVersion> <Title>ILSpyX Platform</Title> <Authors>ILSpy Contributors</Authors> <PackageLicenseExpression>MIT</PackageLicenseExpression> <PackageProjectUrl>https://github.com/icsharpcode/ILSpy/</PackageProjectUrl> <Description>Core cross-platform library used by ILSpy.</Description> <PackageReadmeFile>PackageReadme.md</PackageReadmeFile> <Company>ic#code</Company> <Product>ILSpyX</Product> <RepositoryType>git</RepositoryType> <RepositoryUrl>https://github.com/icsharpcode/ILSpy.git</RepositoryUrl> <PackageIconUrl>../ICSharpCode.Decompiler/DecompilerNuGetPackageIcon.png</PackageIconUrl> <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> <Copyright>Copyright 2022-$([System.DateTime]::Now.Year) AlphaSierraPapa</Copyright> <PackageTags>C# Decompiler ILSpy</PackageTags> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> <DebugType>embedded</DebugType> <DebugSymbols>true</DebugSymbols> <EmbedUntrackedSources>true</EmbedUntrackedSources> <PublishRepositoryUrl>true</PublishRepositoryUrl> </PropertyGroup> <ItemGroup> <None Include="PackageReadme.md" Pack="true" PackagePath="\" /> </ItemGroup> <ItemGroup> <Compile Remove="Properties\AssemblyInfo.template.cs" /> </ItemGroup> <PropertyGroup Condition="'$(GITHUB_ACTIONS)' == 'true'"> <ContinuousIntegrationBuild>true</ContinuousIntegrationBuild> </PropertyGroup> <!-- Inject ILSpyUpdateAssemblyInfo as dependency of the GetPackageVersion target so Pack uses the generated version when evaluating project references. --> <PropertyGroup> <GetPackageVersionDependsOn> ILSpyUpdateAssemblyInfo; $(GetPackageVersionDependsOn) </GetPackageVersionDependsOn> </PropertyGroup> <ItemGroup> <PackageReference Include="System.Reflection.Metadata" /> <PackageReference Include="System.Runtime.CompilerServices.Unsafe" /> <PackageReference Include="System.Composition" /> <PackageReference Include="Mono.Cecil" /> <PackageReference Include="K4os.Compression.LZ4" /> <PackageReference Include="Microsoft.SourceLink.GitHub"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> </ItemGroup> <ItemGroup> <ProjectReference Include="..\ICSharpCode.Decompiler\ICSharpCode.Decompiler.csproj" /> </ItemGroup> <Target Name="ILSpyUpdateAssemblyInfo" AfterTargets="ResolveProjectReferences"> <ReadLinesFromFile ContinueOnError="true" File="..\VERSION"> <Output TaskParameter="Lines" PropertyName="PackageVersion" /> </ReadLinesFromFile> </Target> </Project>
ILSpy/ICSharpCode.ILSpyX/ICSharpCode.ILSpyX.csproj/0
{ "file_path": "ILSpy/ICSharpCode.ILSpyX/ICSharpCode.ILSpyX.csproj", "repo_id": "ILSpy", "token_count": 1219 }
248
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Concurrent; using System.Globalization; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Threading; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.ILSpyX.Abstractions; namespace ICSharpCode.ILSpyX.Search { public class MetadataTokenSearchStrategy : AbstractEntitySearchStrategy { readonly EntityHandle searchTermToken; public MetadataTokenSearchStrategy(ILanguage language, ApiVisibility apiVisibility, SearchRequest request, IProducerConsumerCollection<SearchResult> resultQueue) : base(language, apiVisibility, request, resultQueue) { var terms = request.Keywords; if (terms.Length == 1) { int.TryParse(terms[0], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var token); searchTermToken = MetadataTokenHelpers.EntityHandleOrNil(token); } } public override void Search(PEFile module, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (searchTermToken.IsNil) return; var typeSystem = module.GetTypeSystemWithDecompilerSettingsOrNull(searchRequest.DecompilerSettings); if (typeSystem == null) return; var metadataModule = (MetadataModule)typeSystem.MainModule; int row = module.Metadata.GetRowNumber(searchTermToken); switch (searchTermToken.Kind) { case HandleKind.TypeDefinition: if (row < 1 || row > module.Metadata.TypeDefinitions.Count) break; var type = metadataModule.GetDefinition((TypeDefinitionHandle)searchTermToken); if (!CheckVisibility(type) || !IsInNamespaceOrAssembly(type)) break; OnFoundResult(type); break; case HandleKind.MethodDefinition: if (row < 1 || row > module.Metadata.MethodDefinitions.Count) break; var method = metadataModule.GetDefinition((MethodDefinitionHandle)searchTermToken); if (!CheckVisibility(method) || !IsInNamespaceOrAssembly(method)) break; OnFoundResult(method); break; case HandleKind.FieldDefinition: if (row < 1 || row > module.Metadata.FieldDefinitions.Count) break; var field = metadataModule.GetDefinition((FieldDefinitionHandle)searchTermToken); if (!CheckVisibility(field) || !IsInNamespaceOrAssembly(field)) break; OnFoundResult(field); break; case HandleKind.PropertyDefinition: if (row < 1 || row > module.Metadata.PropertyDefinitions.Count) break; var property = metadataModule.GetDefinition((PropertyDefinitionHandle)searchTermToken); if (!CheckVisibility(property) || !IsInNamespaceOrAssembly(property)) break; OnFoundResult(property); break; case HandleKind.EventDefinition: if (row < 1 || row > module.Metadata.EventDefinitions.Count) break; var @event = metadataModule.GetDefinition((EventDefinitionHandle)searchTermToken); if (!CheckVisibility(@event) || !IsInNamespaceOrAssembly(@event)) break; OnFoundResult(@event); break; } } } }
ILSpy/ICSharpCode.ILSpyX/Search/MetadataTokenSearchStrategy.cs/0
{ "file_path": "ILSpy/ICSharpCode.ILSpyX/Search/MetadataTokenSearchStrategy.cs", "repo_id": "ILSpy", "token_count": 1391 }
249
using System; using System.IO; using System.Linq; using Microsoft.VisualStudio.Shell; namespace ICSharpCode.ILSpy.AddIn.Commands { class OpenProjectOutputCommand : ILSpyCommand { static OpenProjectOutputCommand instance; public OpenProjectOutputCommand(ILSpyAddInPackage owner) : base(owner, PkgCmdIDList.cmdidOpenProjectOutputInILSpy) { ThreadHelper.ThrowIfNotOnUIThread(); } protected override void OnBeforeQueryStatus(object sender, EventArgs e) { ThreadHelper.ThrowIfNotOnUIThread(); if (sender is OleMenuCommand menuItem) { menuItem.Visible = false; var selectedItem = owner.DTE.SelectedItems.Item(1); menuItem.Visible = (ProjectItemForILSpy.Detect(owner, selectedItem) != null); } } protected override void OnExecute(object sender, EventArgs e) { ThreadHelper.ThrowIfNotOnUIThread(); if (owner.DTE.SelectedItems.Count != 1) return; var projectItemWrapper = ProjectItemForILSpy.Detect(owner, owner.DTE.SelectedItems.Item(1)); if (projectItemWrapper != null) { OpenAssembliesInILSpy(projectItemWrapper.GetILSpyParameters(owner)); } } internal static void Register(ILSpyAddInPackage owner) { ThreadHelper.ThrowIfNotOnUIThread(); instance = new OpenProjectOutputCommand(owner); } } }
ILSpy/ILSpy.AddIn.Shared/Commands/OpenProjectOutputCommand.cs/0
{ "file_path": "ILSpy/ILSpy.AddIn.Shared/Commands/OpenProjectOutputCommand.cs", "repo_id": "ILSpy", "token_count": 473 }
250
// Dummy types so that we can use compile some ICS.Decompiler classes in the AddIn context // without depending on SRM etc. using System; using System.Collections.Generic; using System.Text; namespace ICSharpCode.Decompiler { public class ReferenceLoadInfo { public void AddMessage(params object[] args) { } } enum MessageKind { Warning } public static class MetadataExtensions { public static string ToHexString(this IEnumerable<byte> bytes, int estimatedLength) { if (bytes == null) throw new ArgumentNullException(nameof(bytes)); StringBuilder sb = new StringBuilder(estimatedLength * 2); foreach (var b in bytes) sb.AppendFormat("{0:x2}", b); return sb.ToString(); } } }
ILSpy/ILSpy.AddIn/Decompiler/Dummy.cs/0
{ "file_path": "ILSpy/ILSpy.AddIn/Decompiler/Dummy.cs", "repo_id": "ILSpy", "token_count": 242 }
251
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:MyNamespace="clr-namespace:ILSpy.BamlDecompiler.Tests.Cases"> <Style x:Key="style1"> <Setter Property="MyNamespace:CustomControl.CustomName" Value="Test" /> </Style> </ResourceDictionary>
ILSpy/ILSpy.BamlDecompiler.Tests/Cases/Issue775.xaml/0
{ "file_path": "ILSpy/ILSpy.BamlDecompiler.Tests/Cases/Issue775.xaml", "repo_id": "ILSpy", "token_count": 128 }
252
// Copyright (c) 2020 Siegfried Pammer // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Windows; using System.Windows.Controls.Primitives; namespace AvalonDock { public class DockingManager { public DockingManager() { } } public class Resizer : Thumb { static Resizer() { //This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class. //This style is defined in themes\generic.xaml DefaultStyleKeyProperty.OverrideMetadata(typeof(Resizer), new FrameworkPropertyMetadata(typeof(Resizer))); MinWidthProperty.OverrideMetadata(typeof(Resizer), new FrameworkPropertyMetadata(6.0, FrameworkPropertyMetadataOptions.AffectsParentMeasure)); MinHeightProperty.OverrideMetadata(typeof(Resizer), new FrameworkPropertyMetadata(6.0, FrameworkPropertyMetadataOptions.AffectsParentMeasure)); HorizontalAlignmentProperty.OverrideMetadata(typeof(Resizer), new FrameworkPropertyMetadata(HorizontalAlignment.Stretch, FrameworkPropertyMetadataOptions.AffectsParentMeasure)); VerticalAlignmentProperty.OverrideMetadata(typeof(Resizer), new FrameworkPropertyMetadata(VerticalAlignment.Stretch, FrameworkPropertyMetadataOptions.AffectsParentMeasure)); } } public enum AvalonDockBrushes { DefaultBackgroundBrush, DockablePaneTitleBackground, DockablePaneTitleBackgroundSelected, DockablePaneTitleForeground, DockablePaneTitleForegroundSelected, PaneHeaderCommandBackground, PaneHeaderCommandBorderBrush, DocumentHeaderBackground, DocumentHeaderForeground, DocumentHeaderForegroundSelected, DocumentHeaderForegroundSelectedActivated, DocumentHeaderBackgroundSelected, DocumentHeaderBackgroundSelectedActivated, DocumentHeaderBackgroundMouseOver, DocumentHeaderBorderBrushMouseOver, DocumentHeaderBorder, DocumentHeaderBorderSelected, DocumentHeaderBorderSelectedActivated, NavigatorWindowTopBackground, NavigatorWindowTitleForeground, NavigatorWindowDocumentTypeForeground, NavigatorWindowInfoTipForeground, NavigatorWindowForeground, NavigatorWindowBackground, NavigatorWindowSelectionBackground, NavigatorWindowSelectionBorderbrush, NavigatorWindowBottomBackground } public enum ContextMenuElement { DockablePane, DocumentPane, DockableFloatingWindow, DocumentFloatingWindow } }
ILSpy/ILSpy.BamlDecompiler.Tests/Mocks/AvalonDock.cs/0
{ "file_path": "ILSpy/ILSpy.BamlDecompiler.Tests/Mocks/AvalonDock.cs", "repo_id": "ILSpy", "token_count": 952 }
253
 Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32014.148 MinimumVisualStudioVersion = 15.0 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "doc", "doc", "{F45DB999-7E72-4000-B5AD-3A7B485A0896}" ProjectSection(SolutionItems) = preProject doc\Command Line.txt = doc\Command Line.txt doc\ILAst.txt = doc\ILAst.txt doc\IntPtr.txt = doc\IntPtr.txt EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ILSpy", "ILSpy\ILSpy.csproj", "{1E85EFF9-E370-4683-83E4-8A3D063FF791}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ICSharpCode.TreeView", "SharpTreeView\ICSharpCode.TreeView.csproj", "{DDE2A481-8271-4EAC-A330-8FA6A38D13D1}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ICSharpCode.Decompiler", "ICSharpCode.Decompiler\ICSharpCode.Decompiler.csproj", "{984CC812-9470-4A13-AFF9-CC44068D666C}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ICSharpCode.Decompiler.Tests", "ICSharpCode.Decompiler.Tests\ICSharpCode.Decompiler.Tests.csproj", "{FEC0DA52-C4A6-4710-BE36-B484A20C5E22}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestPlugin", "TestPlugin\TestPlugin.csproj", "{F32EBCC8-0E53-4421-867E-05B3D6E10C70}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ILSpy.BamlDecompiler", "ILSpy.BamlDecompiler\ILSpy.BamlDecompiler.csproj", "{A6BAD2BA-76BA-461C-8B6D-418607591247}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ILSpy.BamlDecompiler.Tests", "ILSpy.BamlDecompiler.Tests\ILSpy.BamlDecompiler.Tests.csproj", "{1169E6D1-1899-43D4-A500-07CE4235B388}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ILSpy.Tests", "ILSpy.Tests\ILSpy.Tests.csproj", "{B51C6636-B8D1-4200-9869-08F2689DE6C2}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ILSpy.ReadyToRun", "ILSpy.ReadyToRun\ILSpy.ReadyToRun.csproj", "{0313F581-C63B-43BB-AA9B-07615DABD8A3}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ICSharpCode.ILSpyCmd", "ICSharpCode.ILSpyCmd\ICSharpCode.ILSpyCmd.csproj", "{743B439A-E7AD-4A0A-BAB6-222E1EA83C6D}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ICSharpCode.Decompiler.PowerShell", "ICSharpCode.Decompiler.PowerShell\ICSharpCode.Decompiler.PowerShell.csproj", "{50060E0C-FA25-41F4-B72F-8490324EC9F0}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ICSharpCode.Decompiler.TestRunner", "ICSharpCode.Decompiler.TestRunner\ICSharpCode.Decompiler.TestRunner.csproj", "{4FBB470F-69EB-4C8B-8961-8B4DF4EBB999}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ICSharpCode.ILSpyX", "ICSharpCode.ILSpyX\ICSharpCode.ILSpyX.csproj", "{F8EFCF9D-B9A3-4BA0-A1B2-B026A71DAC22}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ICSharpCode.BamlDecompiler", "ICSharpCode.BamlDecompiler\ICSharpCode.BamlDecompiler.csproj", "{81A30182-3378-4952-8880-F44822390040}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {1E85EFF9-E370-4683-83E4-8A3D063FF791}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1E85EFF9-E370-4683-83E4-8A3D063FF791}.Debug|Any CPU.Build.0 = Debug|Any CPU {1E85EFF9-E370-4683-83E4-8A3D063FF791}.Release|Any CPU.ActiveCfg = Release|Any CPU {1E85EFF9-E370-4683-83E4-8A3D063FF791}.Release|Any CPU.Build.0 = Release|Any CPU {DDE2A481-8271-4EAC-A330-8FA6A38D13D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DDE2A481-8271-4EAC-A330-8FA6A38D13D1}.Debug|Any CPU.Build.0 = Debug|Any CPU {DDE2A481-8271-4EAC-A330-8FA6A38D13D1}.Release|Any CPU.ActiveCfg = Release|Any CPU {DDE2A481-8271-4EAC-A330-8FA6A38D13D1}.Release|Any CPU.Build.0 = Release|Any CPU {984CC812-9470-4A13-AFF9-CC44068D666C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {984CC812-9470-4A13-AFF9-CC44068D666C}.Debug|Any CPU.Build.0 = Debug|Any CPU {984CC812-9470-4A13-AFF9-CC44068D666C}.Release|Any CPU.ActiveCfg = Release|Any CPU {984CC812-9470-4A13-AFF9-CC44068D666C}.Release|Any CPU.Build.0 = Release|Any CPU {FEC0DA52-C4A6-4710-BE36-B484A20C5E22}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {FEC0DA52-C4A6-4710-BE36-B484A20C5E22}.Debug|Any CPU.Build.0 = Debug|Any CPU {FEC0DA52-C4A6-4710-BE36-B484A20C5E22}.Release|Any CPU.ActiveCfg = Release|Any CPU {FEC0DA52-C4A6-4710-BE36-B484A20C5E22}.Release|Any CPU.Build.0 = Release|Any CPU {F32EBCC8-0E53-4421-867E-05B3D6E10C70}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F32EBCC8-0E53-4421-867E-05B3D6E10C70}.Debug|Any CPU.Build.0 = Debug|Any CPU {F32EBCC8-0E53-4421-867E-05B3D6E10C70}.Release|Any CPU.ActiveCfg = Release|Any CPU {F32EBCC8-0E53-4421-867E-05B3D6E10C70}.Release|Any CPU.Build.0 = Release|Any CPU {A6BAD2BA-76BA-461C-8B6D-418607591247}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A6BAD2BA-76BA-461C-8B6D-418607591247}.Debug|Any CPU.Build.0 = Debug|Any CPU {A6BAD2BA-76BA-461C-8B6D-418607591247}.Release|Any CPU.ActiveCfg = Release|Any CPU {A6BAD2BA-76BA-461C-8B6D-418607591247}.Release|Any CPU.Build.0 = Release|Any CPU {1169E6D1-1899-43D4-A500-07CE4235B388}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1169E6D1-1899-43D4-A500-07CE4235B388}.Debug|Any CPU.Build.0 = Debug|Any CPU {1169E6D1-1899-43D4-A500-07CE4235B388}.Release|Any CPU.ActiveCfg = Release|Any CPU {1169E6D1-1899-43D4-A500-07CE4235B388}.Release|Any CPU.Build.0 = Release|Any CPU {B51C6636-B8D1-4200-9869-08F2689DE6C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B51C6636-B8D1-4200-9869-08F2689DE6C2}.Debug|Any CPU.Build.0 = Debug|Any CPU {B51C6636-B8D1-4200-9869-08F2689DE6C2}.Release|Any CPU.ActiveCfg = Release|Any CPU {B51C6636-B8D1-4200-9869-08F2689DE6C2}.Release|Any CPU.Build.0 = Release|Any CPU {0313F581-C63B-43BB-AA9B-07615DABD8A3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0313F581-C63B-43BB-AA9B-07615DABD8A3}.Debug|Any CPU.Build.0 = Debug|Any CPU {0313F581-C63B-43BB-AA9B-07615DABD8A3}.Release|Any CPU.ActiveCfg = Release|Any CPU {0313F581-C63B-43BB-AA9B-07615DABD8A3}.Release|Any CPU.Build.0 = Release|Any CPU {743B439A-E7AD-4A0A-BAB6-222E1EA83C6D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {743B439A-E7AD-4A0A-BAB6-222E1EA83C6D}.Debug|Any CPU.Build.0 = Debug|Any CPU {743B439A-E7AD-4A0A-BAB6-222E1EA83C6D}.Release|Any CPU.ActiveCfg = Release|Any CPU {743B439A-E7AD-4A0A-BAB6-222E1EA83C6D}.Release|Any CPU.Build.0 = Release|Any CPU {50060E0C-FA25-41F4-B72F-8490324EC9F0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {50060E0C-FA25-41F4-B72F-8490324EC9F0}.Debug|Any CPU.Build.0 = Debug|Any CPU {50060E0C-FA25-41F4-B72F-8490324EC9F0}.Release|Any CPU.ActiveCfg = Release|Any CPU {50060E0C-FA25-41F4-B72F-8490324EC9F0}.Release|Any CPU.Build.0 = Release|Any CPU {4FBB470F-69EB-4C8B-8961-8B4DF4EBB999}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4FBB470F-69EB-4C8B-8961-8B4DF4EBB999}.Debug|Any CPU.Build.0 = Debug|Any CPU {4FBB470F-69EB-4C8B-8961-8B4DF4EBB999}.Release|Any CPU.ActiveCfg = Release|Any CPU {4FBB470F-69EB-4C8B-8961-8B4DF4EBB999}.Release|Any CPU.Build.0 = Release|Any CPU {F8EFCF9D-B9A3-4BA0-A1B2-B026A71DAC22}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F8EFCF9D-B9A3-4BA0-A1B2-B026A71DAC22}.Debug|Any CPU.Build.0 = Debug|Any CPU {F8EFCF9D-B9A3-4BA0-A1B2-B026A71DAC22}.Release|Any CPU.ActiveCfg = Release|Any CPU {F8EFCF9D-B9A3-4BA0-A1B2-B026A71DAC22}.Release|Any CPU.Build.0 = Release|Any CPU {81A30182-3378-4952-8880-F44822390040}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {81A30182-3378-4952-8880-F44822390040}.Debug|Any CPU.Build.0 = Debug|Any CPU {81A30182-3378-4952-8880-F44822390040}.Release|Any CPU.ActiveCfg = Release|Any CPU {81A30182-3378-4952-8880-F44822390040}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {C764218F-7633-4412-923D-558CE7EE0560} EndGlobalSection EndGlobal
ILSpy/ILSpy.sln/0
{ "file_path": "ILSpy/ILSpy.sln", "repo_id": "ILSpy", "token_count": 4021 }
254
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Linq; using ICSharpCode.ILSpy.TreeNodes; namespace ICSharpCode.ILSpy.Analyzers.TreeNodes { using ICSharpCode.Decompiler.TypeSystem; internal sealed class AnalyzedEventTreeNode : AnalyzerEntityTreeNode { readonly IEvent analyzedEvent; readonly string prefix; public AnalyzedEventTreeNode(IEvent analyzedEvent, string prefix = "") { this.analyzedEvent = analyzedEvent ?? throw new ArgumentNullException(nameof(analyzedEvent)); this.prefix = prefix; this.LazyLoading = true; } public override IEntity Member => analyzedEvent; public override object Icon => EventTreeNode.GetIcon(analyzedEvent); // TODO: This way of formatting is not suitable for events which explicitly implement interfaces. public override object Text => prefix + Language.EventToString(analyzedEvent, includeDeclaringTypeName: true, includeNamespace: false, includeNamespaceOfDeclaringTypeName: true); protected override void LoadChildren() { if (analyzedEvent.CanAdd) this.Children.Add(new AnalyzedAccessorTreeNode(analyzedEvent.AddAccessor, "add")); if (analyzedEvent.CanRemove) this.Children.Add(new AnalyzedAccessorTreeNode(analyzedEvent.RemoveAccessor, "remove")); if (TryFindBackingField(analyzedEvent, out var backingField)) this.Children.Add(new AnalyzedFieldTreeNode(backingField)); //foreach (var accessor in analyzedEvent.OtherMethods) // this.Children.Add(new AnalyzedAccessorTreeNode(accessor, null)); var analyzers = App.ExportProvider.GetExports<IAnalyzer, IAnalyzerMetadata>("Analyzer"); foreach (var lazy in analyzers.OrderBy(item => item.Metadata.Order)) { var analyzer = lazy.Value; if (analyzer.Show(analyzedEvent)) { this.Children.Add(new AnalyzerSearchTreeNode(analyzedEvent, analyzer, lazy.Metadata.Header)); } } } bool TryFindBackingField(IEvent analyzedEvent, out IField backingField) { backingField = null; foreach (var field in analyzedEvent.DeclaringTypeDefinition.GetFields(options: GetMemberOptions.IgnoreInheritedMembers)) { if (field.Name == analyzedEvent.Name && field.Accessibility == Accessibility.Private) { backingField = field; return true; } } return false; } } }
ILSpy/ILSpy/Analyzers/TreeNodes/AnalyzedEventTreeNode.cs/0
{ "file_path": "ILSpy/ILSpy/Analyzers/TreeNodes/AnalyzedEventTreeNode.cs", "repo_id": "ILSpy", "token_count": 1048 }
255
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #if DEBUG using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using ICSharpCode.Decompiler; using ICSharpCode.ILSpy.Properties; using ICSharpCode.ILSpy.TextView; using ICSharpCode.ILSpyX; using TomsToolbox.Essentials; namespace ICSharpCode.ILSpy { [ExportMainMenuCommand(ParentMenuID = nameof(Resources._File), Header = nameof(Resources.DEBUGDecompile), MenuCategory = nameof(Resources.Open), MenuOrder = 2.5)] sealed class DecompileAllCommand : SimpleCommand { public override bool CanExecute(object parameter) { return System.IO.Directory.Exists("c:\\temp\\decompiled"); } public override void Execute(object parameter) { Docking.DockWorkspace.Instance.RunWithCancellation(ct => Task<AvalonEditTextOutput>.Factory.StartNew(() => { AvalonEditTextOutput output = new AvalonEditTextOutput(); Parallel.ForEach( Partitioner.Create(MainWindow.Instance.CurrentAssemblyList.GetAssemblies(), loadBalance: true), new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, CancellationToken = ct }, delegate (LoadedAssembly asm) { if (!asm.HasLoadError) { Stopwatch w = Stopwatch.StartNew(); Exception exception = null; using (var writer = new System.IO.StreamWriter("c:\\temp\\decompiled\\" + asm.ShortName + ".cs")) { try { var options = MainWindow.Instance.CreateDecompilationOptions(); options.CancellationToken = ct; options.FullDecompilation = true; new CSharpLanguage().DecompileAssembly(asm, new PlainTextOutput(writer), options); } catch (Exception ex) { writer.WriteLine(ex.ToString()); exception = ex; } } lock (output) { output.Write(asm.ShortName + " - " + w.Elapsed); if (exception != null) { output.Write(" - "); output.Write(exception.GetType().Name); } output.WriteLine(); } } }); return output; }, ct)).Then(output => Docking.DockWorkspace.Instance.ShowText(output)).HandleExceptions(); } } [ExportMainMenuCommand(ParentMenuID = nameof(Resources._File), Header = nameof(Resources.DEBUGDecompile100x), MenuCategory = nameof(Resources.Open), MenuOrder = 2.6)] sealed class Decompile100TimesCommand : SimpleCommand { public override void Execute(object parameter) { const int numRuns = 100; var language = MainWindow.Instance.CurrentLanguage; var nodes = MainWindow.Instance.SelectedNodes.ToArray(); var options = MainWindow.Instance.CreateDecompilationOptions(); Docking.DockWorkspace.Instance.RunWithCancellation(ct => Task<AvalonEditTextOutput>.Factory.StartNew(() => { options.CancellationToken = ct; Stopwatch w = Stopwatch.StartNew(); for (int i = 0; i < numRuns; ++i) { foreach (var node in nodes) { node.Decompile(language, new PlainTextOutput(), options); } } w.Stop(); AvalonEditTextOutput output = new AvalonEditTextOutput(); double msPerRun = w.Elapsed.TotalMilliseconds / numRuns; output.Write($"Average time: {msPerRun.ToString("f1")}ms\n"); return output; }, ct)).Then(output => Docking.DockWorkspace.Instance.ShowText(output)).HandleExceptions(); } } } #endif
ILSpy/ILSpy/Commands/DecompileAllCommand.cs/0
{ "file_path": "ILSpy/ILSpy/Commands/DecompileAllCommand.cs", "repo_id": "ILSpy", "token_count": 1627 }
256
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Drawing; using System.Windows.Forms; namespace ICSharpCode.ILSpy.Controls { public sealed class CustomDialog : System.Windows.Forms.Form { System.Windows.Forms.Label label; System.Windows.Forms.Panel panel; int acceptButton; int cancelButton; int result = -1; /// <summary> /// Gets the index of the button pressed. /// </summary> public int Result { get { return result; } } public CustomDialog(string caption, string message, int acceptButton, int cancelButton, string[] buttonLabels) { this.SuspendLayout(); MyInitializeComponent(); this.Icon = null; this.acceptButton = acceptButton; this.cancelButton = cancelButton; this.Text = caption; using (Graphics g = this.CreateGraphics()) { Rectangle screen = Screen.PrimaryScreen.WorkingArea; SizeF size = g.MeasureString(message, label.Font, screen.Width - 20); Size clientSize = size.ToSize(); Button[] buttons = new Button[buttonLabels.Length]; int[] positions = new int[buttonLabels.Length]; int pos = 0; for (int i = 0; i < buttons.Length; i++) { Button newButton = new Button(); newButton.FlatStyle = FlatStyle.System; newButton.Tag = i; string buttonLabel = buttonLabels[i]; newButton.Text = buttonLabel; newButton.Click += new EventHandler(ButtonClick); SizeF buttonSize = g.MeasureString(buttonLabel, newButton.Font); newButton.Width = Math.Max(newButton.Width, ((int)Math.Ceiling(buttonSize.Width / 8.0) + 1) * 8); positions[i] = pos; buttons[i] = newButton; pos += newButton.Width + 4; } if (acceptButton >= 0) { AcceptButton = buttons[acceptButton]; } if (cancelButton >= 0) { CancelButton = buttons[cancelButton]; } pos += 4; // add space before first button // (we don't start with pos=4 because this space doesn't belong to the button panel) if (pos > clientSize.Width) { clientSize.Width = pos; } clientSize.Height += panel.Height + 6; this.ClientSize = clientSize; int start = (clientSize.Width - pos) / 2; for (int i = 0; i < buttons.Length; i++) { buttons[i].Location = new Point(start + positions[i], 4); } panel.Controls.AddRange(buttons); } label.Text = message; this.ResumeLayout(false); } protected override void OnKeyDown(KeyEventArgs e) { if (cancelButton == -1 && e.KeyCode == Keys.Escape) { this.Close(); } else if (e.KeyCode == Keys.C && e.Control) { Clipboard.SetText(this.Text + Environment.NewLine + label.Text); } } void ButtonClick(object sender, EventArgs e) { result = (int)((Control)sender).Tag; this.Close(); } /// <summary> /// This method is required for Windows Forms designer support. /// Do not change the method contents inside the source code editor. The Forms designer might /// not be able to load this method if it was changed manually. /// </summary> void MyInitializeComponent() { this.panel = new System.Windows.Forms.Panel(); this.label = new System.Windows.Forms.Label(); // // panel // this.panel.Dock = System.Windows.Forms.DockStyle.Bottom; this.panel.Location = new System.Drawing.Point(4, 80); this.panel.Name = "panel"; this.panel.Size = new System.Drawing.Size(266, 32); this.panel.TabIndex = 0; // // label // this.label.Dock = System.Windows.Forms.DockStyle.Fill; this.label.FlatStyle = System.Windows.Forms.FlatStyle.System; this.label.Location = new System.Drawing.Point(4, 4); this.label.Name = "label"; this.label.Size = new System.Drawing.Size(266, 76); this.label.TabIndex = 1; this.label.UseMnemonic = false; // // CustomDialog // this.ClientSize = new System.Drawing.Size(274, 112); this.Controls.Add(this.label); this.Controls.Add(this.panel); this.DockPadding.Left = 4; this.DockPadding.Right = 4; this.DockPadding.Top = 4; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.ShowInTaskbar = false; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "CustomDialog"; this.KeyPreview = true; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "CustomDialog"; this.AutoScaleMode = AutoScaleMode.Dpi; this.AutoScaleDimensions = new SizeF(96, 96); } } }
ILSpy/ILSpy/Controls/CustomDialog.cs/0
{ "file_path": "ILSpy/ILSpy/Controls/CustomDialog.cs", "repo_id": "ILSpy", "token_count": 2043 }
257
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" viewBox="0 0 16 16" enable-background="new 0 0 16 16" version="1.1" id="svg8" sodipodi:docname="Constructor.svg" inkscape:version="0.92.4 (5da689c313, 2019-01-14)"> <metadata id="metadata14"> <rdf:RDF> <cc:Work rdf:about=""> <dc:format>image/svg+xml</dc:format> <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> <dc:title></dc:title> </cc:Work> </rdf:RDF> </metadata> <defs id="defs12" /> <sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1920" inkscape:window-height="1017" id="namedview10" showgrid="false" inkscape:zoom="5.2149125" inkscape:cx="34.571566" inkscape:cy="-20.671176" inkscape:window-x="-8" inkscape:window-y="340" inkscape:window-maximized="1" inkscape:current-layer="svg8" /> <style type="text/css" id="style2">.icon-canvas-transparent{opacity:0;fill:#F6F6F6;} .icon-vs-out{fill:#F6F6F6;} .icon-vs-fg{fill:#F0EFF1;} .icon-vs-action-purple{fill:#652D90;}</style> <path class="icon-canvas-transparent" d="M16 16h-16v-16h16v16z" id="canvas" /> <path class="icon-vs-out" d="M15 3.349v8.403l-6.025 4.248h-.905l-7.07-4.418v-8.255l6.595-3.327h1.118l6.287 3.349z" id="outline" /> <path class="icon-vs-fg" d="M12.715 4.398l-4.228 2.622-4.922-2.748 4.578-2.309 4.572 2.435zm-9.715.704l5 2.792v5.705l-5-3.125v-5.372zm6 8.434v-5.658l4-2.48v5.317l-4 2.821z" id="iconFg" /> <path class="icon-vs-action-purple" d="M8.156.837l-6.156 3.105v7.085l6.517 4.073 5.483-3.867v-7.283l-5.844-3.113zm4.559 3.561l-4.228 2.622-4.922-2.748 4.578-2.309 4.572 2.435zm-9.715.704l5 2.792v5.705l-5-3.125v-5.372zm6 8.434v-5.658l4-2.48v5.317l-4 2.821z" id="iconBg" style="fill:#218022;fill-opacity:1" /> </svg>
ILSpy/ILSpy/Images/Constructor.svg/0
{ "file_path": "ILSpy/ILSpy/Images/Constructor.svg", "repo_id": "ILSpy", "token_count": 1339 }
258
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" width="16" height="16" version="1.1" id="svg8" sodipodi:docname="OverlayProtectedInternal.svg" inkscape:version="0.92.4 (5da689c313, 2019-01-14)" inkscape:export-filename="C:\Users\sie_p\Projects\ILSpy master\ILSpy\Images\OverlayProtectedInternal.png" inkscape:export-xdpi="96" inkscape:export-ydpi="96"> <metadata id="metadata14"> <rdf:RDF> <cc:Work rdf:about=""> <dc:format>image/svg+xml</dc:format> <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> <dc:title></dc:title> </cc:Work> </rdf:RDF> </metadata> <defs id="defs12" /> <sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="2048" inkscape:window-height="1089" id="namedview10" showgrid="false" showguides="true" inkscape:guide-bbox="true" inkscape:zoom="22.627417" inkscape:cx="12.450379" inkscape:cy="5.9771371" inkscape:window-x="1912" inkscape:window-y="-8" inkscape:window-maximized="1" inkscape:current-layer="svg8" /> <style type="text/css" id="style2">.icon-canvas-transparent{opacity:0;fill:#F6F6F6;} .icon-vs-out{fill:#F6F6F6;} .icon-vs-bg{fill:#424242;} .icon-vs-action-blue{fill:#00539C;}</style> <path class="icon-canvas-transparent" d="M16 16h-16v-16h16v16z" id="canvas" /> <path style="fill:#f6f6f6" d="M 13.042969 8.953125 C 12.874161 8.9677415 12.691141 9.0136719 12.494141 9.1386719 C 12.294313 9.0135149 12.09064 8.9550781 11.3125 8.9550781 C 10.596915 8.9550781 9.2534415 9.8075932 9.0390625 11 L 8.9433594 11 L 8.34375 9 L 6.8554688 9 L 6.2558594 11 L 4.0996094 11 L 4.0996094 12.5 L 5.4921875 13.544922 L 4.7558594 16 L 6.4335938 16 L 7.5996094 15.125 L 8.7675781 16 L 10.443359 16 L 9.7070312 13.544922 L 9.8183594 13.460938 C 10.414825 14.142547 11.740234 15.623047 11.740234 15.623047 L 12.037109 15.955078 L 12.947266 15.955078 L 13.246094 15.603516 C 13.246094 15.603516 15.082531 13.444359 15.394531 13.068359 C 15.737531 12.626359 15.933594 12.407 15.933594 11.4375 C 15.933594 10.468 14.820906 8.9550781 13.503906 8.9550781 C 13.365906 8.9550781 13.211777 8.9385085 13.042969 8.953125 z " id="outline" /> <path class="icon-vs-bg" d="m 13.504709,9.9558058 c -0.527,0 -0.86,0.7470002 -1.071,1.2500002 -0.211,-0.503 -0.545,-1.2500002 -1.071,-1.2500002 -0.728,0 -1.4290002,0.6640002 -1.4290002,1.4820002 0,0.375 0.1270002,0.756 0.3290002,1.018 0.29,0.35 2.222,2.5 2.222,2.5 0,0 1.829,-2.15 2.119,-2.5 0.203,-0.262 0.33,-0.643 0.33,-1.018 0,-0.818 -0.7,-1.4820002 -1.429,-1.4820002 z" id="iconBg" inkscape:connector-curvature="0" style="fill:#424242" sodipodi:nodetypes="scsscccss" /> <path class="icon-vs-bg" d="m 9.0999995,15 -1.5,-1.125 -1.5,1.125 0.551,-1.837 L 5.1,12 h 1.8999995 l 0.6,-2 0.6,2 h 1.8999995 l -1.5509995,1.163 z" id="notificationBg" inkscape:connector-curvature="0" style="fill:#424242" /> </svg>
ILSpy/ILSpy/Images/OverlayProtectedInternal.svg/0
{ "file_path": "ILSpy/ILSpy/Images/OverlayProtectedInternal.svg", "repo_id": "ILSpy", "token_count": 1856 }
259
<!-- This file was generated by the AiToXaml tool.--> <!-- Tool Version: 14.0.22307.0 --> <DrawingGroup xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> <DrawingGroup.Children> <GeometryDrawing Brush="#00FFFFFF" Geometry="F1M16,16L0,16 0,0 16,0z" /> <GeometryDrawing Brush="#FFF6F6F6" Geometry="F1M16,2L16,16 2.586,16 0,13.414 0,2C0,0.897,0.897,0,2,0L14,0C15.103,0,16,0.897,16,2" /> <GeometryDrawing Brush="#FFEFEFF0" Geometry="F1M4,10L4,15 6,15 6,12 8,12 8,15 12,15 12,10z M13,7L3,7 3,3 13,3z" /> <GeometryDrawing Brush="#FF00529C" Geometry="F1M13,3L3,3 3,7 13,7z M15,2L15,15 12,15 12,10 4,10 4,15 3,15 1,13 1,2C1,1.448,1.448,1,2,1L14,1C14.553,1,15,1.448,15,2 M6,12L8,12 8,15 6,15z" /> </DrawingGroup.Children> </DrawingGroup>
ILSpy/ILSpy/Images/Save.xaml/0
{ "file_path": "ILSpy/ILSpy/Images/Save.xaml", "repo_id": "ILSpy", "token_count": 390 }
260
<!-- This file was generated by the AiToXaml tool.--> <!-- Tool Version: 14.0.22307.0 --> <DrawingGroup xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> <DrawingGroup.Transform> <RotateTransform Angle="90"/> </DrawingGroup.Transform> <DrawingGroup.Children> <GeometryDrawing Brush="#00FFFFFF" Geometry="F1M16,16L0,16 0,0 16,0z" /> <GeometryDrawing Brush="#FFF6F6F6" Geometry="F1M12.996,6.5874L12.996,8.4144 9.412,12.0004 8.586,12.0004 7,10.4144 7,9.0004 4,9.0004 4,6.0014 7,6.0014 7,4.5874 8.586,3.0014 9.412,3.0014z" /> <GeometryDrawing Brush="#FF424242" Geometry="F1M10.996,7.5869L9,9.5859 9,5.4159 10.996,7.4159z M9,4.0019L8,5.0019 8,7.0019 5,7.0019 5,8.0019 8,8.0019 8,9.9999 9,10.9999 11.996,8.0019 11.996,7.0019z" /> <GeometryDrawing Brush="#FFF0EFF1" Geometry="F1M9,5.4155L10.996,7.4155 10.996,7.5865 9,9.5855z" /> </DrawingGroup.Children> </DrawingGroup>
ILSpy/ILSpy/Images/SubTypes.xaml/0
{ "file_path": "ILSpy/ILSpy/Images/SubTypes.xaml", "repo_id": "ILSpy", "token_count": 432 }
261
// Copyright (c) 2018 Siegfried Pammer // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Threading; using System.Windows; using System.Windows.Media; using ICSharpCode.AvalonEdit.Highlighting; using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.CSharp; using ICSharpCode.Decompiler.CSharp.OutputVisitor; using ICSharpCode.Decompiler.CSharp.Syntax; using ICSharpCode.Decompiler.Disassembler; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.Decompiler.Util; using ICSharpCode.ILSpyX; using ICSharpCode.ILSpyX.Extensions; namespace ICSharpCode.ILSpy { using SequencePoint = ICSharpCode.Decompiler.DebugInfo.SequencePoint; [Export(typeof(Language))] class CSharpILMixedLanguage : ILLanguage { public override string Name => "IL with C#"; protected override ReflectionDisassembler CreateDisassembler(ITextOutput output, DecompilationOptions options) { var displaySettings = MainWindow.Instance.CurrentDisplaySettings; return new ReflectionDisassembler(output, new MixedMethodBodyDisassembler(output, options) { DetectControlStructure = detectControlStructure, ShowSequencePoints = options.DecompilerSettings.ShowDebugInfo }, options.CancellationToken) { ShowMetadataTokens = displaySettings.ShowMetadataTokens, ShowMetadataTokensInBase10 = displaySettings.ShowMetadataTokensInBase10, ShowRawRVAOffsetAndBytes = displaySettings.ShowRawOffsetsAndBytesBeforeInstruction, ExpandMemberDefinitions = options.DecompilerSettings.ExpandMemberDefinitions }; } static CSharpDecompiler CreateDecompiler(PEFile module, DecompilationOptions options) { CSharpDecompiler decompiler = new CSharpDecompiler(module, module.GetAssemblyResolver(), options.DecompilerSettings); decompiler.CancellationToken = options.CancellationToken; return decompiler; } static void WriteCode(TextWriter output, DecompilerSettings settings, SyntaxTree syntaxTree, IDecompilerTypeSystem typeSystem) { syntaxTree.AcceptVisitor(new InsertParenthesesVisitor { InsertParenthesesForReadability = true }); TokenWriter tokenWriter = new TextWriterTokenWriter(output) { IndentationString = settings.CSharpFormattingOptions.IndentationString }; tokenWriter = TokenWriter.WrapInWriterThatSetsLocationsInAST(tokenWriter); syntaxTree.AcceptVisitor(new CSharpOutputVisitor(tokenWriter, settings.CSharpFormattingOptions)); } class MixedMethodBodyDisassembler : MethodBodyDisassembler { readonly DecompilationOptions options; // list sorted by IL offset IList<SequencePoint> sequencePoints; // lines of raw c# source code string[] codeLines; public MixedMethodBodyDisassembler(ITextOutput output, DecompilationOptions options) : base(output, options.CancellationToken) { this.options = options; } public override void Disassemble(PEFile module, MethodDefinitionHandle handle) { try { var csharpOutput = new StringWriter(); CSharpDecompiler decompiler = CreateDecompiler(module, options); var st = decompiler.Decompile(handle); WriteCode(csharpOutput, options.DecompilerSettings, st, decompiler.TypeSystem); var mapping = decompiler.CreateSequencePoints(st).FirstOrDefault(kvp => (kvp.Key.MoveNextMethod ?? kvp.Key.Method)?.MetadataToken == handle); this.sequencePoints = mapping.Value ?? (IList<SequencePoint>)EmptyList<SequencePoint>.Instance; this.codeLines = csharpOutput.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None); base.Disassemble(module, handle); } finally { this.sequencePoints = null; this.codeLines = null; } } protected override void WriteInstruction(ITextOutput output, MetadataReader metadata, MethodDefinitionHandle methodHandle, ref BlobReader blob, int methodRva) { int index = sequencePoints.BinarySearch(blob.Offset, seq => seq.Offset); if (index >= 0) { var info = sequencePoints[index]; var highlightingOutput = output as ISmartTextOutput; if (!info.IsHidden) { for (int line = info.StartLine; line <= info.EndLine; line++) { if (highlightingOutput != null) { string text = codeLines[line - 1]; int startColumn = 1; int endColumn = text.Length + 1; if (line == info.StartLine) startColumn = info.StartColumn; if (line == info.EndLine) endColumn = info.EndColumn; WriteHighlightedCommentLine(highlightingOutput, text, startColumn - 1, endColumn - 1, info.StartLine == info.EndLine); } else WriteCommentLine(output, codeLines[line - 1]); } } else { output.Write("// "); highlightingOutput?.BeginSpan(gray); output.WriteLine("(no C# code)"); highlightingOutput?.EndSpan(); } } base.WriteInstruction(output, metadata, methodHandle, ref blob, methodRva); } HighlightingColor gray = new HighlightingColor { Foreground = new SimpleHighlightingBrush(Colors.DarkGray) }; void WriteHighlightedCommentLine(ISmartTextOutput output, string text, int startColumn, int endColumn, bool isSingleLine) { if (startColumn > text.Length) { Debug.Fail("startColumn is invalid"); startColumn = text.Length; } if (endColumn > text.Length) { Debug.Fail("endColumn is invalid"); endColumn = text.Length; } output.Write("// "); output.BeginSpan(gray); if (isSingleLine) output.Write(text.Substring(0, startColumn).TrimStart()); else output.Write(text.Substring(0, startColumn)); output.EndSpan(); output.Write(text.Substring(startColumn, endColumn - startColumn)); output.BeginSpan(gray); output.Write(text.Substring(endColumn)); output.EndSpan(); output.WriteLine(); } void WriteCommentLine(ITextOutput output, string text) { output.WriteLine("// " + text); } } } }
ILSpy/ILSpy/Languages/CSharpILMixedLanguage.cs/0
{ "file_path": "ILSpy/ILSpy/Languages/CSharpILMixedLanguage.cs", "repo_id": "ILSpy", "token_count": 2478 }
262
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Collections.Generic; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.Metadata; namespace ICSharpCode.ILSpy.Metadata { class DeclSecurityTableTreeNode : MetadataTableTreeNode { public DeclSecurityTableTreeNode(MetadataFile metadataFile) : base(HandleKind.DeclarativeSecurityAttribute, metadataFile) { } public override object Text => $"0E DeclSecurity ({metadataFile.Metadata.GetTableRowCount(TableIndex.DeclSecurity)})"; public override bool View(ViewModels.TabPageModel tabPage) { tabPage.Title = Text.ToString(); tabPage.SupportsLanguageSwitching = false; var view = Helpers.PrepareDataGrid(tabPage, this); var metadata = metadataFile.Metadata; var list = new List<DeclSecurityEntry>(); DeclSecurityEntry scrollTargetEntry = default; foreach (var row in metadata.DeclarativeSecurityAttributes) { var entry = new DeclSecurityEntry(metadataFile, row); if (scrollTarget == MetadataTokens.GetRowNumber(row)) { scrollTargetEntry = entry; } list.Add(entry); } view.ItemsSource = list; tabPage.Content = view; if (scrollTargetEntry.RID > 0) { ScrollItemIntoView(view, scrollTargetEntry); } return true; } struct DeclSecurityEntry { readonly MetadataFile metadataFile; readonly DeclarativeSecurityAttributeHandle handle; readonly DeclarativeSecurityAttribute declSecAttr; public int RID => MetadataTokens.GetRowNumber(handle); public int Token => MetadataTokens.GetToken(handle); public int Offset => metadataFile.MetadataOffset + metadataFile.Metadata.GetTableMetadataOffset(TableIndex.DeclSecurity) + metadataFile.Metadata.GetTableRowSize(TableIndex.DeclSecurity) * (RID - 1); [ColumnInfo("X8", Kind = ColumnKind.Token)] public int Parent => MetadataTokens.GetToken(declSecAttr.Parent); public void OnParentClick() { MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, declSecAttr.Parent, protocol: "metadata")); } string parentTooltip; public string ParentTooltip => GenerateTooltip(ref parentTooltip, metadataFile, declSecAttr.Parent); [ColumnInfo("X8", Kind = ColumnKind.Other)] public DeclarativeSecurityAction Action => declSecAttr.Action; public string ActionTooltip { get { return declSecAttr.Action.ToString(); } } [ColumnInfo("X8", Kind = ColumnKind.HeapOffset)] public int PermissionSet => MetadataTokens.GetHeapOffset(declSecAttr.PermissionSet); public string PermissionSetTooltip { get { return null; } } public DeclSecurityEntry(MetadataFile metadataFile, DeclarativeSecurityAttributeHandle handle) { this.metadataFile = metadataFile; this.handle = handle; this.declSecAttr = metadataFile.Metadata.GetDeclarativeSecurityAttribute(handle); this.parentTooltip = null; } } public override void Decompile(Language language, ITextOutput output, DecompilationOptions options) { language.WriteCommentLine(output, "DeclSecurityAttrs"); } } }
ILSpy/ILSpy/Metadata/CorTables/DeclSecurityTableTreeNode.cs/0
{ "file_path": "ILSpy/ILSpy/Metadata/CorTables/DeclSecurityTableTreeNode.cs", "repo_id": "ILSpy", "token_count": 1370 }
263
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Collections.Generic; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.Metadata; namespace ICSharpCode.ILSpy.Metadata { internal class MethodSemanticsTableTreeNode : MetadataTableTreeNode { public MethodSemanticsTableTreeNode(MetadataFile metadataFile) : base((HandleKind)0x18, metadataFile) { } public override object Text => $"18 MethodSemantics ({metadataFile.Metadata.GetTableRowCount(TableIndex.MethodSemantics)})"; public override bool View(ViewModels.TabPageModel tabPage) { tabPage.Title = Text.ToString(); tabPage.SupportsLanguageSwitching = false; var view = Helpers.PrepareDataGrid(tabPage, this); var list = new List<MethodSemanticsEntry>(); MethodSemanticsEntry scrollTargetEntry = default; foreach (var row in metadataFile.Metadata.GetMethodSemantics()) { MethodSemanticsEntry entry = new MethodSemanticsEntry(metadataFile, row.Handle, row.Semantics, row.Method, row.Association); if (entry.RID == this.scrollTarget) { scrollTargetEntry = entry; } list.Add(entry); } view.ItemsSource = list; tabPage.Content = view; if (scrollTargetEntry.RID > 0) { ScrollItemIntoView(view, scrollTargetEntry); } return true; } struct MethodSemanticsEntry { readonly MetadataFile metadataFile; readonly Handle handle; readonly MethodSemanticsAttributes semantics; readonly MethodDefinitionHandle method; readonly EntityHandle association; public int RID => MetadataTokens.GetToken(handle) & 0xFFFFFF; public int Token => MetadataTokens.GetToken(handle); public int Offset => metadataFile.MetadataOffset + metadataFile.Metadata.GetTableMetadataOffset(TableIndex.MethodDef) + metadataFile.Metadata.GetTableRowSize(TableIndex.MethodDef) * (RID - 1); [ColumnInfo("X8", Kind = ColumnKind.Other)] public MethodSemanticsAttributes Semantics => semantics; public string SemanticsTooltip => semantics.ToString(); [ColumnInfo("X8", Kind = ColumnKind.Token)] public int Method => MetadataTokens.GetToken(method); public void OnMethodClick() { MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, method, protocol: "metadata")); } string methodTooltip; public string MethodTooltip => GenerateTooltip(ref methodTooltip, metadataFile, method); [ColumnInfo("X8", Kind = ColumnKind.Token)] public int Association => MetadataTokens.GetToken(association); public void OnAssociationClick() { MainWindow.Instance.JumpToReference(new EntityReference(metadataFile, association, protocol: "metadata")); } string associationTooltip; public string AssociationTooltip => GenerateTooltip(ref associationTooltip, metadataFile, association); public MethodSemanticsEntry(MetadataFile metadataFile, Handle handle, MethodSemanticsAttributes semantics, MethodDefinitionHandle method, EntityHandle association) { this.metadataFile = metadataFile; this.handle = handle; this.semantics = semantics; this.method = method; this.association = association; this.methodTooltip = null; this.associationTooltip = null; } } public override void Decompile(Language language, ITextOutput output, DecompilationOptions options) { language.WriteCommentLine(output, "MethodDefs"); } } }
ILSpy/ILSpy/Metadata/CorTables/MethodSemanticsTableTreeNode.cs/0
{ "file_path": "ILSpy/ILSpy/Metadata/CorTables/MethodSemanticsTableTreeNode.cs", "repo_id": "ILSpy", "token_count": 1415 }
264
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #nullable enable using System.Reflection.PortableExecutable; using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.ILSpy.TreeNodes; using ICSharpCode.ILSpy.ViewModels; namespace ICSharpCode.ILSpy.Metadata { sealed class PdbChecksumTreeNode : ILSpyTreeNode { readonly PdbChecksumDebugDirectoryData entry; public PdbChecksumTreeNode(PdbChecksumDebugDirectoryData entry) { this.entry = entry; } override public object Text => nameof(DebugDirectoryEntryType.PdbChecksum); public override object ToolTip => "The entry stores a crypto hash of the content of the symbol file the PE/COFF\n" + "file was built with. The hash can be used to validate that a given PDB file was\n" + "built with the PE/COFF file and not altered in any way. More than one entry can\n" + "be present if multiple PDBs were produced during the build of the PE/COFF file\n" + "(for example, private and public symbols)."; public override object Icon => Images.MetadataTable; public override bool View(TabPageModel tabPage) { tabPage.Title = Text.ToString(); tabPage.SupportsLanguageSwitching = false; var dataGrid = Helpers.PrepareDataGrid(tabPage, this); dataGrid.ItemsSource = new[] { new PdbChecksumDebugDirectoryDataEntry(entry) }; tabPage.Content = dataGrid; return true; } sealed class PdbChecksumDebugDirectoryDataEntry { readonly PdbChecksumDebugDirectoryData entry; public PdbChecksumDebugDirectoryDataEntry(PdbChecksumDebugDirectoryData entry) { this.entry = entry; } public string AlgorithmName => entry.AlgorithmName; public string Checksum => entry.Checksum.ToHexString(entry.Checksum.Length); } public override void Decompile(Language language, ITextOutput output, DecompilationOptions options) { language.WriteCommentLine(output, Text.ToString()); language.WriteCommentLine(output, $"AlgorithmName: {entry.AlgorithmName}"); language.WriteCommentLine(output, $"Checksum: {entry.Checksum.ToHexString(entry.Checksum.Length)}"); } } }
ILSpy/ILSpy/Metadata/DebugDirectory/PdbChecksumTreeNode.cs/0
{ "file_path": "ILSpy/ILSpy/Metadata/DebugDirectory/PdbChecksumTreeNode.cs", "repo_id": "ILSpy", "token_count": 992 }
265
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Linq; using System.Reflection; using System.Reflection.Metadata.Ecma335; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.ILSpy.Metadata; using ICSharpCode.ILSpy.Properties; namespace ICSharpCode.ILSpy.Commands { [ExportContextMenuEntry(Header = nameof(Resources.GoToToken), Order = 10)] class GoToTokenCommand : IContextMenuEntry { public void Execute(TextViewContext context) { int token = GetSelectedToken(context.DataGrid, out PEFile module).Value; MainWindow.Instance.JumpToReference(new EntityReference(module, MetadataTokens.Handle(token), protocol: "metadata")); } public bool IsEnabled(TextViewContext context) { return true; } public bool IsVisible(TextViewContext context) { return context.DataGrid?.Name == "MetadataView" && GetSelectedToken(context.DataGrid, out _) != null; } private int? GetSelectedToken(DataGrid grid, out PEFile module) { module = null; if (grid == null) return null; var cell = grid.CurrentCell; if (!cell.IsValid) return null; Type type = cell.Item.GetType(); var property = type.GetProperty(cell.Column.Header.ToString()); var moduleField = type.GetField("module", BindingFlags.NonPublic | BindingFlags.Instance); if (property == null || property.PropertyType != typeof(int) || !property.GetCustomAttributes(false).Any(a => a is ColumnInfoAttribute { Kind: ColumnKind.Token } c)) return null; module = (PEFile)moduleField.GetValue(cell.Item); return (int)property.GetValue(cell.Item); } } [ExportContextMenuEntry(Header = nameof(Resources.Copy), Order = 10)] class CopyCommand : IContextMenuEntry { public void Execute(TextViewContext context) { string content = GetSelectedCellContent(context.DataGrid, context.MousePosition); Clipboard.SetText(content); } public bool IsEnabled(TextViewContext context) { return true; } public bool IsVisible(TextViewContext context) { return context.DataGrid?.Name == "MetadataView" && GetSelectedCellContent(context.DataGrid, context.MousePosition) != null; } private string GetSelectedCellContent(DataGrid grid, Point position) { position = grid.PointFromScreen(position); var hit = VisualTreeHelper.HitTest(grid, position); if (hit == null) return null; var cell = hit.VisualHit.GetParent<DataGridCell>(); if (cell == null) return null; return cell.DataContext.GetType() .GetProperty(cell.Column.Header.ToString(), BindingFlags.Instance | BindingFlags.Public) .GetValue(cell.DataContext).ToString(); } } }
ILSpy/ILSpy/Metadata/GoToTokenCommand.cs/0
{ "file_path": "ILSpy/ILSpy/Metadata/GoToTokenCommand.cs", "repo_id": "ILSpy", "token_count": 1208 }
266
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Collections.Generic; using System.Reflection.PortableExecutable; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.ILSpy.TreeNodes; using ICSharpCode.ILSpyX.Extensions; namespace ICSharpCode.ILSpy.Metadata { class OptionalHeaderTreeNode : ILSpyTreeNode { private PEFile module; public OptionalHeaderTreeNode(PEFile module) { this.module = module; } public override object Text => "Optional Header"; public override object Icon => Images.Header; public override bool View(ViewModels.TabPageModel tabPage) { tabPage.Title = Text.ToString(); tabPage.SupportsLanguageSwitching = false; var dataGrid = Helpers.PrepareDataGrid(tabPage, this); dataGrid.RowDetailsTemplateSelector = new CharacteristicsDataTemplateSelector("DLL Characteristics"); dataGrid.RowDetailsVisibilityMode = DataGridRowDetailsVisibilityMode.Collapsed; dataGrid.Columns.Clear(); dataGrid.AutoGenerateColumns = false; dataGrid.Columns.AddRange( new[] { new DataGridTextColumn { IsReadOnly = true, Header = "Member", Binding = new Binding("Member") }, new DataGridTextColumn { IsReadOnly = true, Header = "Offset", Binding = new Binding("Offset") { StringFormat = "X8" } }, new DataGridTextColumn { IsReadOnly = true, Header = "Size", Binding = new Binding("Size") }, new DataGridTextColumn { IsReadOnly = true, Header = "Value", Binding = new Binding(".") { Converter = ByteWidthConverter.Instance } }, new DataGridTextColumn { IsReadOnly = true, Header = "Meaning", Binding = new Binding("Meaning") } } ); var headers = module.Reader.PEHeaders; var reader = module.Reader.GetEntireImage().GetReader(headers.PEHeaderStartOffset, 128); var header = headers.PEHeader; var isPE32Plus = (header.Magic == PEMagic.PE32Plus); var entries = new List<Entry>(); ushort dllCharacteristics; Entry characteristics; entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, reader.ReadUInt16(), 2, "Magic", header.Magic.ToString())); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, reader.ReadByte(), 1, "Major Linker Version", "")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, reader.ReadByte(), 1, "Minor Linker Version", "")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, reader.ReadInt32(), 4, "Code Size", "Size of the code (text) section, or the sum of all code sections if there are multiple sections.")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, reader.ReadInt32(), 4, "Initialized Data Size", "Size of the initialized data section, or the sum of all initialized data sections if there are multiple data sections.")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, reader.ReadInt32(), 4, "Uninitialized Data Size", "Size of the uninitialized data section, or the sum of all uninitialized data sections if there are multiple uninitialized data sections.")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, reader.ReadInt32(), 4, "Entry Point RVA", "RVA of entry point, needs to point to bytes 0xFF 0x25 followed by the RVA in a section marked execute / read for EXEs or 0 for DLLs")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, reader.ReadInt32(), 4, "Base Of Code", "RVA of the code section.")); entries.Add(new Entry(isPE32Plus ? 0 : headers.PEHeaderStartOffset + reader.Offset, isPE32Plus ? 0UL : reader.ReadUInt32(), isPE32Plus ? 0 : 4, "Base Of Data", "PE32 only (not present in PE32Plus): RVA of the data section, relative to the Image Base.")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, isPE32Plus ? reader.ReadUInt64() : reader.ReadUInt32(), isPE32Plus ? 8 : 4, "Image Base", "Shall be a multiple of 0x10000.")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, reader.ReadInt32(), 4, "Section Alignment", "Shall be greater than File Alignment.")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, reader.ReadInt32(), 4, "File Alignment", "")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, reader.ReadUInt16(), 2, "Major OS Version", "")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, reader.ReadUInt16(), 2, "Minor OS Version", "")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, reader.ReadUInt16(), 2, "Major Image Version", "")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, reader.ReadUInt16(), 2, "Minor Image Version", "")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, reader.ReadUInt16(), 2, "Major Subsystem Version", "")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, reader.ReadUInt16(), 2, "Minor Subsystem Version", "")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, reader.ReadUInt32(), 4, "Win32VersionValue", "")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, reader.ReadInt32(), 4, "Image Size", "Size, in bytes, of image, including all headers and padding; shall be a multiple of Section Alignment.")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, reader.ReadInt32(), 4, "Header Size", "Combined size of MS-DOS Header, PE Header, PE Optional Header and padding; shall be a multiple of the file alignment.")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, reader.ReadInt32(), 4, "File Checksum", "")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, reader.ReadUInt16(), 2, "Subsystem", header.Subsystem.ToString())); entries.Add(characteristics = new Entry(headers.PEHeaderStartOffset + reader.Offset, dllCharacteristics = reader.ReadUInt16(), 2, "DLL Characteristics", header.DllCharacteristics.ToString(), new[] { new BitEntry((dllCharacteristics & 0x0001) != 0, "<0001> Process Init (Reserved)"), new BitEntry((dllCharacteristics & 0x0002) != 0, "<0002> Process Term (Reserved)"), new BitEntry((dllCharacteristics & 0x0004) != 0, "<0004> Thread Init (Reserved)"), new BitEntry((dllCharacteristics & 0x0008) != 0, "<0008> Thread Term (Reserved)"), new BitEntry((dllCharacteristics & 0x0010) != 0, "<0010> Unused"), new BitEntry((dllCharacteristics & 0x0020) != 0, "<0020> Image can handle a high entropy 64-bit virtual address space (ASLR)"), new BitEntry((dllCharacteristics & 0x0040) != 0, "<0040> DLL can be relocated at load time"), new BitEntry((dllCharacteristics & 0x0080) != 0, "<0080> Code integrity checks are enforced"), new BitEntry((dllCharacteristics & 0x0100) != 0, "<0100> Image is NX compatible"), new BitEntry((dllCharacteristics & 0x0200) != 0, "<0200> Isolation aware, but do not isolate the image"), new BitEntry((dllCharacteristics & 0x0400) != 0, "<0400> Does not use structured exception handling (SEH)"), new BitEntry((dllCharacteristics & 0x0800) != 0, "<0800> Do not bind the image"), new BitEntry((dllCharacteristics & 0x1000) != 0, "<1000> Image must execute in an AppContainer"), new BitEntry((dllCharacteristics & 0x2000) != 0, "<2000> Driver is a WDM Driver"), new BitEntry((dllCharacteristics & 0x4000) != 0, "<4000> Image supports Control Flow Guard"), new BitEntry((dllCharacteristics & 0x8000) != 0, "<8000> Image is Terminal Server aware"), })); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, isPE32Plus ? reader.ReadUInt64() : reader.ReadUInt32(), isPE32Plus ? 8 : 4, "Stack Reserve Size", "")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, isPE32Plus ? reader.ReadUInt64() : reader.ReadUInt32(), isPE32Plus ? 8 : 4, "Stack Commit Size", "")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, isPE32Plus ? reader.ReadUInt64() : reader.ReadUInt32(), isPE32Plus ? 8 : 4, "Heap Reserve Size", "")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, isPE32Plus ? reader.ReadUInt64() : reader.ReadUInt32(), isPE32Plus ? 8 : 4, "Heap Commit Size", "")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, reader.ReadUInt32(), 4, "Loader Flags", "")); entries.Add(new Entry(headers.PEHeaderStartOffset + reader.Offset, reader.ReadInt32(), 4, "Number of Data Directories", "")); dataGrid.ItemsSource = entries; dataGrid.SetDetailsVisibilityForItem(characteristics, Visibility.Visible); tabPage.Content = dataGrid; return true; } public override void Decompile(Language language, ITextOutput output, DecompilationOptions options) { language.WriteCommentLine(output, "Optional Header"); } } }
ILSpy/ILSpy/Metadata/OptionalHeaderTreeNode.cs/0
{ "file_path": "ILSpy/ILSpy/Metadata/OptionalHeaderTreeNode.cs", "repo_id": "ILSpy", "token_count": 3128 }
267
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ICSharpCode.ILSpy.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ICSharpCode.ILSpy.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to _About. /// </summary> public static string _About { get { return ResourceManager.GetString("_About", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Add To Main List. /// </summary> public static string _AddMainList { get { return ResourceManager.GetString("_AddMainList", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Analy_zer. /// </summary> public static string _Analyzer { get { return ResourceManager.GetString("_Analyzer", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Assemblies. /// </summary> public static string _Assemblies { get { return ResourceManager.GetString("_Assemblies", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Check for Updates. /// </summary> public static string _CheckUpdates { get { return ResourceManager.GetString("_CheckUpdates", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Collapse all tree nodes. /// </summary> public static string _CollapseTreeNodes { get { return ResourceManager.GetString("_CollapseTreeNodes", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _File. /// </summary> public static string _File { get { return ResourceManager.GetString("_File", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Help. /// </summary> public static string _Help { get { return ResourceManager.GetString("_Help", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Load Dependencies. /// </summary> public static string _LoadDependencies { get { return ResourceManager.GetString("_LoadDependencies", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _New. /// </summary> public static string _New { get { return ResourceManager.GetString("_New", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Open.... /// </summary> public static string _Open { get { return ResourceManager.GetString("_Open", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Open Command Line Here. /// </summary> public static string _OpenCommandLineHere { get { return ResourceManager.GetString("_OpenCommandLineHere", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Open Containing Folder. /// </summary> public static string _OpenContainingFolder { get { return ResourceManager.GetString("_OpenContainingFolder", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Options.... /// </summary> public static string _Options { get { return ResourceManager.GetString("_Options", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Reload. /// </summary> public static string _Reload { get { return ResourceManager.GetString("_Reload", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Remove. /// </summary> public static string _Remove { get { return ResourceManager.GetString("_Remove", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Remove Assemblies with load errors. /// </summary> public static string _RemoveAssembliesWithLoadErrors { get { return ResourceManager.GetString("_RemoveAssembliesWithLoadErrors", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Reset. /// </summary> public static string _Reset { get { return ResourceManager.GetString("_Reset", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Resources. /// </summary> public static string _Resources { get { return ResourceManager.GetString("_Resources", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Save Code.... /// </summary> public static string _SaveCode { get { return ResourceManager.GetString("_SaveCode", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Search:. /// </summary> public static string _Search { get { return ResourceManager.GetString("_Search", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Search for:. /// </summary> public static string _SearchFor { get { return ResourceManager.GetString("_SearchFor", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Show debug steps. /// </summary> public static string _ShowDebugSteps { get { return ResourceManager.GetString("_ShowDebugSteps", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Toggle Folding. /// </summary> public static string _ToggleFolding { get { return ResourceManager.GetString("_ToggleFolding", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _View. /// </summary> public static string _View { get { return ResourceManager.GetString("_View", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Window. /// </summary> public static string _Window { get { return ResourceManager.GetString("_Window", resourceCulture); } } /// <summary> /// Looks up a localized string similar to About. /// </summary> public static string About { get { return ResourceManager.GetString("About", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Add preconfigured list.... /// </summary> public static string AddPreconfiguredList { get { return ResourceManager.GetString("AddPreconfiguredList", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Add shell integration. /// </summary> public static string AddShellIntegration { get { return ResourceManager.GetString("AddShellIntegration", resourceCulture); } } /// <summary> /// Looks up a localized string similar to This will add &quot;{0}&quot; to the registry at &quot;HKCU\Software\Classes\dllfile\shell\Open with ILSpy\command&quot; and &quot;HKCU\Software\Classes\exefile\shell\Open with ILSpy\command&quot; to allow opening .dll and .exe files from the Windows Explorer context menu. /// ///Do you want to continue?. /// </summary> public static string AddShellIntegrationMessage { get { return ResourceManager.GetString("AddShellIntegrationMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to |All Files|*.*. /// </summary> public static string AllFiles { get { return ResourceManager.GetString("AllFiles", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Allow multiple instances. /// </summary> public static string AllowMultipleInstances { get { return ResourceManager.GetString("AllowMultipleInstances", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Always use braces. /// </summary> public static string AlwaysBraces { get { return ResourceManager.GetString("AlwaysBraces", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Analyze. /// </summary> public static string Analyze { get { return ResourceManager.GetString("Analyze", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Assemblies. /// </summary> public static string Assemblies { get { return ResourceManager.GetString("Assemblies", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Assembly. /// </summary> public static string Assembly { get { return ResourceManager.GetString("Assembly", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The directory is not empty. File will be overwritten. ///Are you sure you want to continue?. /// </summary> public static string AssemblySaveCodeDirectoryNotEmpty { get { return ResourceManager.GetString("AssemblySaveCodeDirectoryNotEmpty", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Project Directory not empty. /// </summary> public static string AssemblySaveCodeDirectoryNotEmptyTitle { get { return ResourceManager.GetString("AssemblySaveCodeDirectoryNotEmptyTitle", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Automatically check for updates every week. /// </summary> public static string AutomaticallyCheckUpdatesEveryWeek { get { return ResourceManager.GetString("AutomaticallyCheckUpdatesEveryWeek", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Back. /// </summary> public static string Back { get { return ResourceManager.GetString("Back", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Base Types. /// </summary> public static string BaseTypes { get { return ResourceManager.GetString("BaseTypes", resourceCulture); } } /// <summary> /// Looks up a localized string similar to C_lone. /// </summary> public static string C_lone { get { return ResourceManager.GetString("C_lone", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Cancel. /// </summary> public static string Cancel { get { return ResourceManager.GetString("Cancel", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Entity could not be resolved. Cannot analyze entities from missing assembly references. Add the missing reference and try again.. /// </summary> public static string CannotAnalyzeMissingRef { get { return ResourceManager.GetString("CannotAnalyzeMissingRef", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Cannot create PDB file for {0}, because it does not contain a PE Debug Directory Entry of type &apos;CodeView&apos;.. /// </summary> public static string CannotCreatePDBFile { get { return ResourceManager.GetString("CannotCreatePDBFile", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Check again. /// </summary> public static string CheckAgain { get { return ResourceManager.GetString("CheckAgain", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Checking.... /// </summary> public static string Checking { get { return ResourceManager.GetString("Checking", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Check for updates. /// </summary> public static string CheckUpdates { get { return ResourceManager.GetString("CheckUpdates", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Clear assembly list. /// </summary> public static string ClearAssemblyList { get { return ResourceManager.GetString("ClearAssemblyList", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Close. /// </summary> public static string Close { get { return ResourceManager.GetString("Close", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Collapse all tree nodes. /// </summary> public static string CollapseTreeNodes { get { return ResourceManager.GetString("CollapseTreeNodes", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Copy. /// </summary> public static string Copy { get { return ResourceManager.GetString("Copy", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Copy error message. /// </summary> public static string CopyErrorMessage { get { return ResourceManager.GetString("CopyErrorMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Copy FQ Name. /// </summary> public static string CopyName { get { return ResourceManager.GetString("CopyName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not use SDK-style project format, because no compatible target-framework moniker was found.. /// </summary> public static string CouldNotUseSdkStyleProjectFormat { get { return ResourceManager.GetString("CouldNotUseSdkStyleProjectFormat", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Create. /// </summary> public static string Create { get { return ResourceManager.GetString("Create", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Culture. /// </summary> public static string CultureLabel { get { return ResourceManager.GetString("CultureLabel", resourceCulture); } } /// <summary> /// Looks up a localized string similar to DEBUG -- Decompile All. /// </summary> public static string DEBUGDecompile { get { return ResourceManager.GetString("DEBUGDecompile", resourceCulture); } } /// <summary> /// Looks up a localized string similar to DEBUG -- Decompile 100x. /// </summary> public static string DEBUGDecompile100x { get { return ResourceManager.GetString("DEBUGDecompile100x", resourceCulture); } } /// <summary> /// Looks up a localized string similar to DEBUG -- Disassemble All. /// </summary> public static string DEBUGDisassemble { get { return ResourceManager.GetString("DEBUGDisassemble", resourceCulture); } } /// <summary> /// Looks up a localized string similar to DEBUG -- Dump PDB as XML. /// </summary> public static string DEBUGDumpPDBAsXML { get { return ResourceManager.GetString("DEBUGDumpPDBAsXML", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Debug Steps. /// </summary> public static string DebugSteps { get { return ResourceManager.GetString("DebugSteps", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Debug this step. /// </summary> public static string DebugThisStep { get { return ResourceManager.GetString("DebugThisStep", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Decompilation complete in {0:F1} seconds.. /// </summary> public static string DecompilationCompleteInF1Seconds { get { return ResourceManager.GetString("DecompilationCompleteInF1Seconds", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Decompilation view options. /// </summary> public static string DecompilationViewOptions { get { return ResourceManager.GetString("DecompilationViewOptions", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Decompilation was cancelled.. /// </summary> public static string DecompilationWasCancelled { get { return ResourceManager.GetString("DecompilationWasCancelled", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Decompile. /// </summary> public static string Decompile { get { return ResourceManager.GetString("Decompile", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Decompiler. /// </summary> public static string Decompiler { get { return ResourceManager.GetString("Decompiler", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Always inline local variables if possible. /// </summary> public static string DecompilerSettings_AggressiveInlining { get { return ResourceManager.GetString("DecompilerSettings.AggressiveInlining", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Allow extension &apos;Add&apos; methods in collection initializer expressions. /// </summary> public static string DecompilerSettings_AllowExtensionAddMethodsInCollectionInitializerExpressions { get { return ResourceManager.GetString("DecompilerSettings.AllowExtensionAddMethodsInCollectionInitializerExpressions", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use &apos;ref&apos; extension methods. /// </summary> public static string DecompilerSettings_AllowExtensionMethodSyntaxOnRef { get { return ResourceManager.GetString("DecompilerSettings.AllowExtensionMethodSyntaxOnRef", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Always cast targets of explicit interface implementation calls. /// </summary> public static string DecompilerSettings_AlwaysCastTargetsOfExplicitInterfaceImplementationCalls { get { return ResourceManager.GetString("DecompilerSettings.AlwaysCastTargetsOfExplicitInterfaceImplementationCalls", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Always qualify member references. /// </summary> public static string DecompilerSettings_AlwaysQualifyMemberReferences { get { return ResourceManager.GetString("DecompilerSettings.AlwaysQualifyMemberReferences", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Always show enum member values. /// </summary> public static string DecompilerSettings_AlwaysShowEnumMemberValues { get { return ResourceManager.GetString("DecompilerSettings.AlwaysShowEnumMemberValues", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Always use braces. /// </summary> public static string DecompilerSettings_AlwaysUseBraces { get { return ResourceManager.GetString("DecompilerSettings.AlwaysUseBraces", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Always fully qualify namespaces using the &quot;global::&quot; prefix. /// </summary> public static string DecompilerSettings_AlwaysUseGlobal { get { return ResourceManager.GetString("DecompilerSettings.AlwaysUseGlobal", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Apply Windows Runtime projections on loaded assemblies. /// </summary> public static string DecompilerSettings_ApplyWindowsRuntimeProjectionsOnLoadedAssemblies { get { return ResourceManager.GetString("DecompilerSettings.ApplyWindowsRuntimeProjectionsOnLoadedAssemblies", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Array initializer expressions. /// </summary> public static string DecompilerSettings_ArrayInitializerExpressions { get { return ResourceManager.GetString("DecompilerSettings.ArrayInitializerExpressions", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Decompile async IAsyncEnumerator methods. /// </summary> public static string DecompilerSettings_AsyncEnumerator { get { return ResourceManager.GetString("DecompilerSettings.AsyncEnumerator", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Automatically load assembly references. /// </summary> public static string DecompilerSettings_AutoLoadAssemblyReferences { get { return ResourceManager.GetString("DecompilerSettings.AutoLoadAssemblyReferences", resourceCulture); } } /// <summary> /// Looks up a localized string similar to User-defined checked operators. /// </summary> public static string DecompilerSettings_CheckedOperators { get { return ResourceManager.GetString("DecompilerSettings.CheckedOperators", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Decompile anonymous methods/lambdas. /// </summary> public static string DecompilerSettings_DecompileAnonymousMethodsLambdas { get { return ResourceManager.GetString("DecompilerSettings.DecompileAnonymousMethodsLambdas", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Decompile anonymous types. /// </summary> public static string DecompilerSettings_DecompileAnonymousTypes { get { return ResourceManager.GetString("DecompilerSettings.DecompileAnonymousTypes", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Decompile async methods. /// </summary> public static string DecompilerSettings_DecompileAsyncMethods { get { return ResourceManager.GetString("DecompilerSettings.DecompileAsyncMethods", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Decompile automatic events. /// </summary> public static string DecompilerSettings_DecompileAutomaticEvents { get { return ResourceManager.GetString("DecompilerSettings.DecompileAutomaticEvents", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Decompile automatic properties. /// </summary> public static string DecompilerSettings_DecompileAutomaticProperties { get { return ResourceManager.GetString("DecompilerSettings.DecompileAutomaticProperties", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Decompile await in catch/finally blocks. /// </summary> public static string DecompilerSettings_DecompileAwaitInCatchFinallyBlocks { get { return ResourceManager.GetString("DecompilerSettings.DecompileAwaitInCatchFinallyBlocks", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Decompile C# 1.0 &apos;public unsafe fixed int arr[10];&apos; members. /// </summary> public static string DecompilerSettings_DecompileC10PublicUnsafeFixedIntArr10Members { get { return ResourceManager.GetString("DecompilerSettings.DecompileC10PublicUnsafeFixedIntArr10Members", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Decompile [DecimalConstant(...)] as simple literal values. /// </summary> public static string DecompilerSettings_DecompileDecimalConstantAsSimpleLiteralValues { get { return ResourceManager.GetString("DecompilerSettings.DecompileDecimalConstantAsSimpleLiteralValues", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Decompile enumerators (yield return). /// </summary> public static string DecompilerSettings_DecompileEnumeratorsYieldReturn { get { return ResourceManager.GetString("DecompilerSettings.DecompileEnumeratorsYieldReturn", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Decompile expression trees. /// </summary> public static string DecompilerSettings_DecompileExpressionTrees { get { return ResourceManager.GetString("DecompilerSettings.DecompileExpressionTrees", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Decompile foreach statements with GetEnumerator extension methods. /// </summary> public static string DecompilerSettings_DecompileForEachWithGetEnumeratorExtension { get { return ResourceManager.GetString("DecompilerSettings.DecompileForEachWithGetEnumeratorExtension", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Decompile use of the &apos;dynamic&apos; type. /// </summary> public static string DecompilerSettings_DecompileUseOfTheDynamicType { get { return ResourceManager.GetString("DecompilerSettings.DecompileUseOfTheDynamicType", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Detect deconstruction assignments. /// </summary> public static string DecompilerSettings_Deconstruction { get { return ResourceManager.GetString("DecompilerSettings.Deconstruction", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Detect awaited using and foreach statements. /// </summary> public static string DecompilerSettings_DetectAsyncUsingAndForeachStatements { get { return ResourceManager.GetString("DecompilerSettings.DetectAsyncUsingAndForeachStatements", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Detect foreach statements. /// </summary> public static string DecompilerSettings_DetectForeachStatements { get { return ResourceManager.GetString("DecompilerSettings.DetectForeachStatements", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Detect lock statements. /// </summary> public static string DecompilerSettings_DetectLockStatements { get { return ResourceManager.GetString("DecompilerSettings.DetectLockStatements", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Detect switch on string. /// </summary> public static string DecompilerSettings_DetectSwitchOnString { get { return ResourceManager.GetString("DecompilerSettings.DetectSwitchOnString", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Detect tuple comparisons. /// </summary> public static string DecompilerSettings_DetectTupleComparisons { get { return ResourceManager.GetString("DecompilerSettings.DetectTupleComparisons", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Detect using statements. /// </summary> public static string DecompilerSettings_DetectUsingStatements { get { return ResourceManager.GetString("DecompilerSettings.DetectUsingStatements", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Dictionary initializer expressions. /// </summary> public static string DecompilerSettings_DictionaryInitializerExpressions { get { return ResourceManager.GetString("DecompilerSettings.DictionaryInitializerExpressions", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Transform to do-while, if possible. /// </summary> public static string DecompilerSettings_DoWhileStatement { get { return ResourceManager.GetString("DecompilerSettings.DoWhileStatement", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use file-scoped namespace declarations. /// </summary> public static string DecompilerSettings_FileScopedNamespaces { get { return ResourceManager.GetString("DecompilerSettings.FileScopedNamespaces", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Transform to for, if possible. /// </summary> public static string DecompilerSettings_ForStatement { get { return ResourceManager.GetString("DecompilerSettings.ForStatement", resourceCulture); } } /// <summary> /// Looks up a localized string similar to F#-specific options. /// </summary> public static string DecompilerSettings_FSpecificOptions { get { return ResourceManager.GetString("DecompilerSettings.FSpecificOptions", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Function pointers. /// </summary> public static string DecompilerSettings_FunctionPointers { get { return ResourceManager.GetString("DecompilerSettings.FunctionPointers", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Decompile getter-only automatic properties. /// </summary> public static string DecompilerSettings_GetterOnlyAutomaticProperties { get { return ResourceManager.GetString("DecompilerSettings.GetterOnlyAutomaticProperties", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Include XML documentation comments in the decompiled code. /// </summary> public static string DecompilerSettings_IncludeXMLDocumentationCommentsInTheDecompiledCode { get { return ResourceManager.GetString("DecompilerSettings.IncludeXMLDocumentationCommentsInTheDecompiledCode", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Allow init; accessors. /// </summary> public static string DecompilerSettings_InitAccessors { get { return ResourceManager.GetString("DecompilerSettings.InitAccessors", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Insert using declarations. /// </summary> public static string DecompilerSettings_InsertUsingDeclarations { get { return ResourceManager.GetString("DecompilerSettings.InsertUsingDeclarations", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Introduce local functions. /// </summary> public static string DecompilerSettings_IntroduceLocalFunctions { get { return ResourceManager.GetString("DecompilerSettings.IntroduceLocalFunctions", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Introduce static local functions. /// </summary> public static string DecompilerSettings_IntroduceStaticLocalFunctions { get { return ResourceManager.GetString("DecompilerSettings.IntroduceStaticLocalFunctions", resourceCulture); } } /// <summary> /// Looks up a localized string similar to IsByRefLikeAttribute should be replaced with &apos;ref&apos; modifiers on structs. /// </summary> public static string DecompilerSettings_IsByRefLikeAttributeShouldBeReplacedWithRefModifiersOnStructs { get { return ResourceManager.GetString("DecompilerSettings.IsByRefLikeAttributeShouldBeReplacedWithRefModifiersOnStructs", resourceCulture); } } /// <summary> /// Looks up a localized string similar to IsReadOnlyAttribute should be replaced with &apos;readonly&apos;/&apos;in&apos; modifiers on structs/parameters. /// </summary> public static string DecompilerSettings_IsReadOnlyAttributeShouldBeReplacedWithReadonlyInModifiersOnStructsParameters { get { return ResourceManager.GetString("DecompilerSettings.IsReadOnlyAttributeShouldBeReplacedWithReadonlyInModifiersOnSt" + "ructsParameters", resourceCulture); } } /// <summary> /// Looks up a localized string similar to IsUnmanagedAttribute on type parameters should be replaced with &apos;unmanaged&apos; constraints. /// </summary> public static string DecompilerSettings_IsUnmanagedAttributeOnTypeParametersShouldBeReplacedWithUnmanagedConstraints { get { return ResourceManager.GetString("DecompilerSettings.IsUnmanagedAttributeOnTypeParametersShouldBeReplacedWithUnmana" + "gedConstraints", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use nint/nuint types. /// </summary> public static string DecompilerSettings_NativeIntegers { get { return ResourceManager.GetString("DecompilerSettings.NativeIntegers", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Nullable reference types. /// </summary> public static string DecompilerSettings_NullableReferenceTypes { get { return ResourceManager.GetString("DecompilerSettings.NullableReferenceTypes", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Decompile ?. and ?[] operators. /// </summary> public static string DecompilerSettings_NullPropagation { get { return ResourceManager.GetString("DecompilerSettings.NullPropagation", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Treat (U)IntPtr as n(u)int. /// </summary> public static string DecompilerSettings_NumericIntPtr { get { return ResourceManager.GetString("DecompilerSettings.NumericIntPtr", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Object/collection initializer expressions. /// </summary> public static string DecompilerSettings_ObjectCollectionInitializerExpressions { get { return ResourceManager.GetString("DecompilerSettings.ObjectCollectionInitializerExpressions", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Other. /// </summary> public static string DecompilerSettings_Other { get { return ResourceManager.GetString("DecompilerSettings.Other", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use parameter null checking. /// </summary> public static string DecompilerSettings_ParameterNullCheck { get { return ResourceManager.GetString("DecompilerSettings.ParameterNullCheck", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Pattern combinators (and, or, not). /// </summary> public static string DecompilerSettings_PatternCombinators { get { return ResourceManager.GetString("DecompilerSettings.PatternCombinators", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use pattern matching expressions. /// </summary> public static string DecompilerSettings_PatternMatching { get { return ResourceManager.GetString("DecompilerSettings.PatternMatching", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Project export. /// </summary> public static string DecompilerSettings_ProjectExport { get { return ResourceManager.GetString("DecompilerSettings.ProjectExport", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Ranges. /// </summary> public static string DecompilerSettings_Ranges { get { return ResourceManager.GetString("DecompilerSettings.Ranges", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Read-only methods. /// </summary> public static string DecompilerSettings_ReadOnlyMethods { get { return ResourceManager.GetString("DecompilerSettings.ReadOnlyMethods", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Record classes. /// </summary> public static string DecompilerSettings_RecordClasses { get { return ResourceManager.GetString("DecompilerSettings.RecordClasses", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Record structs. /// </summary> public static string DecompilerSettings_RecordStructs { get { return ResourceManager.GetString("DecompilerSettings.RecordStructs", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Recursive pattern matching. /// </summary> public static string DecompilerSettings_RecursivePatternMatching { get { return ResourceManager.GetString("DecompilerSettings.RecursivePatternMatching", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Relational patterns. /// </summary> public static string DecompilerSettings_RelationalPatterns { get { return ResourceManager.GetString("DecompilerSettings.RelationalPatterns", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Remove dead and side effect free code (use with caution!). /// </summary> public static string DecompilerSettings_RemoveDeadAndSideEffectFreeCodeUseWithCaution { get { return ResourceManager.GetString("DecompilerSettings.RemoveDeadAndSideEffectFreeCodeUseWithCaution", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Remove dead stores (use with caution!). /// </summary> public static string DecompilerSettings_RemoveDeadStores { get { return ResourceManager.GetString("DecompilerSettings.RemoveDeadStores", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Remove optional arguments, if possible. /// </summary> public static string DecompilerSettings_RemoveOptionalArgumentsIfPossible { get { return ResourceManager.GetString("DecompilerSettings.RemoveOptionalArgumentsIfPossible", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Required members. /// </summary> public static string DecompilerSettings_RequiredMembers { get { return ResourceManager.GetString("DecompilerSettings.RequiredMembers", resourceCulture); } } /// <summary> /// Looks up a localized string similar to &apos;scoped&apos; lifetime annotation. /// </summary> public static string DecompilerSettings_ScopedRef { get { return ResourceManager.GetString("DecompilerSettings.ScopedRef", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Separate local variable declarations and initializers (int x = 5; -&gt; int x; x = 5;), if possible. /// </summary> public static string DecompilerSettings_SeparateLocalVariableDeclarations { get { return ResourceManager.GetString("DecompilerSettings.SeparateLocalVariableDeclarations", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Show info from debug symbols, if available. /// </summary> public static string DecompilerSettings_ShowInfoFromDebugSymbolsIfAvailable { get { return ResourceManager.GetString("DecompilerSettings.ShowInfoFromDebugSymbolsIfAvailable", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Detect switch on integer even if IL code does not use a jump table. /// </summary> public static string DecompilerSettings_SparseIntegerSwitch { get { return ResourceManager.GetString("DecompilerSettings.SparseIntegerSwitch", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Decompile &apos;string.Concat(a, b)&apos; calls into &apos;a + b&apos;. /// </summary> public static string DecompilerSettings_StringConcat { get { return ResourceManager.GetString("DecompilerSettings.StringConcat", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Switch expressions. /// </summary> public static string DecompilerSettings_SwitchExpressions { get { return ResourceManager.GetString("DecompilerSettings.SwitchExpressions", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use switch on (ReadOnly)Span&lt;char&gt;. /// </summary> public static string DecompilerSettings_SwitchOnReadOnlySpanChar { get { return ResourceManager.GetString("DecompilerSettings.SwitchOnReadOnlySpanChar", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Unsigned right shift (&gt;&gt;&gt;). /// </summary> public static string DecompilerSettings_UnsignedRightShift { get { return ResourceManager.GetString("DecompilerSettings.UnsignedRightShift", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use discards. /// </summary> public static string DecompilerSettings_UseDiscards { get { return ResourceManager.GetString("DecompilerSettings.UseDiscards", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use enhanced using variable declarations. /// </summary> public static string DecompilerSettings_UseEnhancedUsing { get { return ResourceManager.GetString("DecompilerSettings.UseEnhancedUsing", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use expression-bodied member syntax for get-only properties. /// </summary> public static string DecompilerSettings_UseExpressionBodiedMemberSyntaxForGetOnlyProperties { get { return ResourceManager.GetString("DecompilerSettings.UseExpressionBodiedMemberSyntaxForGetOnlyProperties", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use extension method syntax. /// </summary> public static string DecompilerSettings_UseExtensionMethodSyntax { get { return ResourceManager.GetString("DecompilerSettings.UseExtensionMethodSyntax", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use implicit conversions between tuple types. /// </summary> public static string DecompilerSettings_UseImplicitConversionsBetweenTupleTypes { get { return ResourceManager.GetString("DecompilerSettings.UseImplicitConversionsBetweenTupleTypes", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use implicit method group conversions. /// </summary> public static string DecompilerSettings_UseImplicitMethodGroupConversions { get { return ResourceManager.GetString("DecompilerSettings.UseImplicitMethodGroupConversions", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use lambda syntax, if possible. /// </summary> public static string DecompilerSettings_UseLambdaSyntaxIfPossible { get { return ResourceManager.GetString("DecompilerSettings.UseLambdaSyntaxIfPossible", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use lifted operators for nullables. /// </summary> public static string DecompilerSettings_UseLiftedOperatorsForNullables { get { return ResourceManager.GetString("DecompilerSettings.UseLiftedOperatorsForNullables", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use LINQ expression syntax. /// </summary> public static string DecompilerSettings_UseLINQExpressionSyntax { get { return ResourceManager.GetString("DecompilerSettings.UseLINQExpressionSyntax", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use named arguments. /// </summary> public static string DecompilerSettings_UseNamedArguments { get { return ResourceManager.GetString("DecompilerSettings.UseNamedArguments", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use nested directories for namespaces. /// </summary> public static string DecompilerSettings_UseNestedDirectoriesForNamespaces { get { return ResourceManager.GetString("DecompilerSettings.UseNestedDirectoriesForNamespaces", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use non-trailing named arguments. /// </summary> public static string DecompilerSettings_UseNonTrailingNamedArguments { get { return ResourceManager.GetString("DecompilerSettings.UseNonTrailingNamedArguments", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use out variable declarations. /// </summary> public static string DecompilerSettings_UseOutVariableDeclarations { get { return ResourceManager.GetString("DecompilerSettings.UseOutVariableDeclarations", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use pattern-based fixed statement. /// </summary> public static string DecompilerSettings_UsePatternBasedFixedStatement { get { return ResourceManager.GetString("DecompilerSettings.UsePatternBasedFixedStatement", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use primary constructor syntax with records. /// </summary> public static string DecompilerSettings_UsePrimaryConstructorSyntax { get { return ResourceManager.GetString("DecompilerSettings.UsePrimaryConstructorSyntax", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use ref locals to accurately represent order of evaluation. /// </summary> public static string DecompilerSettings_UseRefLocalsForAccurateOrderOfEvaluation { get { return ResourceManager.GetString("DecompilerSettings.UseRefLocalsForAccurateOrderOfEvaluation", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use new SDK style format for generated project files (*.csproj). /// </summary> public static string DecompilerSettings_UseSdkStyleProjectFormat { get { return ResourceManager.GetString("DecompilerSettings.UseSdkStyleProjectFormat", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use stackalloc initializer syntax. /// </summary> public static string DecompilerSettings_UseStackallocInitializerSyntax { get { return ResourceManager.GetString("DecompilerSettings.UseStackallocInitializerSyntax", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use string interpolation. /// </summary> public static string DecompilerSettings_UseStringInterpolation { get { return ResourceManager.GetString("DecompilerSettings.UseStringInterpolation", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use throw expressions. /// </summary> public static string DecompilerSettings_UseThrowExpressions { get { return ResourceManager.GetString("DecompilerSettings.UseThrowExpressions", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use tuple type syntax. /// </summary> public static string DecompilerSettings_UseTupleTypeSyntax { get { return ResourceManager.GetString("DecompilerSettings.UseTupleTypeSyntax", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use variable names from debug symbols, if available. /// </summary> public static string DecompilerSettings_UseVariableNamesFromDebugSymbolsIfAvailable { get { return ResourceManager.GetString("DecompilerSettings.UseVariableNamesFromDebugSymbolsIfAvailable", resourceCulture); } } /// <summary> /// Looks up a localized string similar to UTF-8 string literals. /// </summary> public static string DecompilerSettings_Utf8StringLiterals { get { return ResourceManager.GetString("DecompilerSettings.Utf8StringLiterals", resourceCulture); } } /// <summary> /// Looks up a localized string similar to VB-specific options. /// </summary> public static string DecompilerSettings_VBSpecificOptions { get { return ResourceManager.GetString("DecompilerSettings.VBSpecificOptions", resourceCulture); } } /// <summary> /// Looks up a localized string similar to &apos;with&apos; initializer expressions. /// </summary> public static string DecompilerSettings_WithExpressions { get { return ResourceManager.GetString("DecompilerSettings.WithExpressions", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The settings selected below are applied to the decompiler output in combination with the selection in the language drop-down. Selecting a lower language version in the drop-down will deactivate all selected options of the higher versions. Note that some settings implicitly depend on each other, e.g.: LINQ expressions cannot be introduced without first transforming static calls to extension method calls.. /// </summary> public static string DecompilerSettingsPanelLongText { get { return ResourceManager.GetString("DecompilerSettingsPanelLongText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Decompile to new tab. /// </summary> public static string DecompileToNewPanel { get { return ResourceManager.GetString("DecompileToNewPanel", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Decompiling.... /// </summary> public static string Decompiling { get { return ResourceManager.GetString("Decompiling", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Dependencies. /// </summary> public static string Dependencies { get { return ResourceManager.GetString("Dependencies", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Derived Types. /// </summary> public static string DerivedTypes { get { return ResourceManager.GetString("DerivedTypes", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Display. /// </summary> public static string Display { get { return ResourceManager.GetString("Display", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Display Code. /// </summary> public static string DisplayCode { get { return ResourceManager.GetString("DisplayCode", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Font:. /// </summary> public static string DisplaySettingsPanel_Font { get { return ResourceManager.GetString("DisplaySettingsPanel_Font", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Theme:. /// </summary> public static string DisplaySettingsPanel_Theme { get { return ResourceManager.GetString("DisplaySettingsPanel_Theme", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Download. /// </summary> public static string Download { get { return ResourceManager.GetString("Download", resourceCulture); } } /// <summary> /// Looks up a localized string similar to E_xit. /// </summary> public static string E_xit { get { return ResourceManager.GetString("E_xit", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Editor. /// </summary> public static string Editor { get { return ResourceManager.GetString("Editor", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Enable folding on all blocks in braces. /// </summary> public static string EnableFoldingBlocksBraces { get { return ResourceManager.GetString("EnableFoldingBlocksBraces", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Enable word wrap. /// </summary> public static string EnableWordWrap { get { return ResourceManager.GetString("EnableWordWrap", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Enter a list name:. /// </summary> public static string EnterListName { get { return ResourceManager.GetString("EnterListName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Exit. /// </summary> public static string Exit { get { return ResourceManager.GetString("Exit", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Expand member definitions after decompilation. /// </summary> public static string ExpandMemberDefinitionsAfterDecompilation { get { return ResourceManager.GetString("ExpandMemberDefinitionsAfterDecompilation", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Expand using declarations after decompilation. /// </summary> public static string ExpandUsingDeclarationsAfterDecompilation { get { return ResourceManager.GetString("ExpandUsingDeclarationsAfterDecompilation", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Extract package entry. /// </summary> public static string ExtractPackageEntry { get { return ResourceManager.GetString("ExtractPackageEntry", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Folding. /// </summary> public static string Folding { get { return ResourceManager.GetString("Folding", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Font. /// </summary> public static string Font { get { return ResourceManager.GetString("Font", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Forward. /// </summary> public static string Forward { get { return ResourceManager.GetString("Forward", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Generate portable PDB. /// </summary> public static string GeneratePortable { get { return ResourceManager.GetString("GeneratePortable", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Generation complete in {0} seconds.. /// </summary> public static string GenerationCompleteInSeconds { get { return ResourceManager.GetString("GenerationCompleteInSeconds", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Generation was cancelled.. /// </summary> public static string GenerationWasCancelled { get { return ResourceManager.GetString("GenerationWasCancelled", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Go to token. /// </summary> public static string GoToToken { get { return ResourceManager.GetString("GoToToken", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Hide empty metadata tables from tree view. /// </summary> public static string HideEmptyMetadataTables { get { return ResourceManager.GetString("HideEmptyMetadataTables", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Highlight current line. /// </summary> public static string HighlightCurrentLine { get { return ResourceManager.GetString("HighlightCurrentLine", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Highlight matching braces. /// </summary> public static string HighlightMatchingBraces { get { return ResourceManager.GetString("HighlightMatchingBraces", resourceCulture); } } /// <summary> /// Looks up a localized string similar to ILSpyAboutPage.txt. /// </summary> public static string ILSpyAboutPageTxt { get { return ResourceManager.GetString("ILSpyAboutPageTxt", resourceCulture); } } /// <summary> /// Looks up a localized string similar to ILSpy version . /// </summary> public static string ILSpyVersion { get { return ResourceManager.GetString("ILSpyVersion", resourceCulture); } } /// <summary> /// Looks up a localized string similar to A new ILSpy version is available.. /// </summary> public static string ILSpyVersionAvailable { get { return ResourceManager.GetString("ILSpyVersionAvailable", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Indentation. /// </summary> public static string Indentation { get { return ResourceManager.GetString("Indentation", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Indent size:. /// </summary> public static string IndentSize { get { return ResourceManager.GetString("IndentSize", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Insert using declarations. /// </summary> public static string InsertUsingDeclarations { get { return ResourceManager.GetString("InsertUsingDeclarations", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Are you sure that you want to delete the selected assembly list?. /// </summary> public static string ListDeleteConfirmation { get { return ResourceManager.GetString("ListDeleteConfirmation", resourceCulture); } } /// <summary> /// Looks up a localized string similar to A list with the same name was found.. /// </summary> public static string ListExistsAlready { get { return ResourceManager.GetString("ListExistsAlready", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Are you sure that you want to remove all assembly lists and recreate the default assembly lists?. /// </summary> public static string ListsResetConfirmation { get { return ResourceManager.GetString("ListsResetConfirmation", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Load assemblies that were loaded in the last instance.. /// </summary> public static string LoadAssembliesThatWereLoadedInTheLastInstance { get { return ResourceManager.GetString("LoadAssembliesThatWereLoadedInTheLastInstance", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Loading.... /// </summary> public static string Loading { get { return ResourceManager.GetString("Loading", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Location. /// </summary> public static string Location { get { return ResourceManager.GetString("Location", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Manage assembly _lists.... /// </summary> public static string ManageAssembly_Lists { get { return ResourceManager.GetString("ManageAssembly_Lists", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Manage Assembly Lists. /// </summary> public static string ManageAssemblyLists { get { return ResourceManager.GetString("ManageAssemblyLists", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Metadata. /// </summary> public static string Metadata { get { return ResourceManager.GetString("Metadata", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Misc. /// </summary> public static string Misc { get { return ResourceManager.GetString("Misc", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Name. /// </summary> public static string Name { get { return ResourceManager.GetString("Name", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Navigation. /// </summary> public static string Navigation { get { return ResourceManager.GetString("Navigation", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Navigation failed because the target is hidden or a compiler-generated class.\n ///Please disable all filters that might hide the item (i.e. activate &quot;View &gt; Show internal types and members&quot;) and try again.. /// </summary> public static string NavigationFailed { get { return ResourceManager.GetString("NavigationFailed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to .NET version . /// </summary> public static string NETFrameworkVersion { get { return ResourceManager.GetString("NETFrameworkVersion", resourceCulture); } } /// <summary> /// Looks up a localized string similar to New list. /// </summary> public static string NewList { get { return ResourceManager.GetString("NewList", resourceCulture); } } /// <summary> /// Looks up a localized string similar to New Tab. /// </summary> public static string NewTab { get { return ResourceManager.GetString("NewTab", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Nuget Package Browser. /// </summary> public static string NugetPackageBrowser { get { return ResourceManager.GetString("NugetPackageBrowser", resourceCulture); } } /// <summary> /// Looks up a localized string similar to OK. /// </summary> public static string OK { get { return ResourceManager.GetString("OK", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Open. /// </summary> public static string Open { get { return ResourceManager.GetString("Open", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Open Explorer. /// </summary> public static string OpenExplorer { get { return ResourceManager.GetString("OpenExplorer", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Open From GAC. /// </summary> public static string OpenFrom { get { return ResourceManager.GetString("OpenFrom", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Open from _GAC.... /// </summary> public static string OpenFrom_GAC { get { return ResourceManager.GetString("OpenFrom_GAC", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Delete. /// </summary> public static string OpenListDialog__Delete { get { return ResourceManager.GetString("OpenListDialog__Delete", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Open. /// </summary> public static string OpenListDialog__Open { get { return ResourceManager.GetString("OpenListDialog__Open", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Operation was cancelled.. /// </summary> public static string OperationWasCancelled { get { return ResourceManager.GetString("OperationWasCancelled", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Options. /// </summary> public static string Options { get { return ResourceManager.GetString("Options", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Other. /// </summary> public static string Other { get { return ResourceManager.GetString("Other", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Other options. /// </summary> public static string OtherOptions { get { return ResourceManager.GetString("OtherOptions", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Other Resources. /// </summary> public static string OtherResources { get { return ResourceManager.GetString("OtherResources", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Portable PDB|*.pdb|All files|*.*. /// </summary> public static string PortablePDBPdbAllFiles { get { return ResourceManager.GetString("PortablePDBPdbAllFiles", resourceCulture); } } /// <summary> /// Looks up a localized string similar to You can change this by toggling the setting at Options &gt; Decompiler &gt; Project export &gt; Use new SDK style format for generated project files (*.csproj).. /// </summary> public static string ProjectExportFormatChangeSettingHint { get { return ResourceManager.GetString("ProjectExportFormatChangeSettingHint", resourceCulture); } } /// <summary> /// Looks up a localized string similar to A Non-SDK project was generated. Learn more at https://docs.microsoft.com/en-us/nuget/resources/check-project-format.. /// </summary> public static string ProjectExportFormatNonSDKHint { get { return ResourceManager.GetString("ProjectExportFormatNonSDKHint", resourceCulture); } } /// <summary> /// Looks up a localized string similar to A SDK-style project was generated. Learn more at https://docs.microsoft.com/en-us/nuget/resources/check-project-format.. /// </summary> public static string ProjectExportFormatSDKHint { get { return ResourceManager.GetString("ProjectExportFormatSDKHint", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Failed to decompile the assemblies {0} because the namespace names are too long or the directory structure is nested too deep. /// ///If you are using Windows 10.0.14393 (Windows 10 version 1607) or later, you can enable &quot;Long path support&quot; by creating a REG_DWORD registry key named &quot;LongPathsEnabled&quot; with value 0x1 at &quot;HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem&quot; (see https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation for more information). /// ///If this does not [rest of string was truncated]&quot;;. /// </summary> public static string ProjectExportPathTooLong { get { return ResourceManager.GetString("ProjectExportPathTooLong", resourceCulture); } } /// <summary> /// Looks up a localized string similar to for ex. property getter/setter access. To get optimal decompilation results, please manually add the missing references to the list of loaded assemblies.. /// </summary> public static string PropertyManuallyMissingReferencesListLoadedAssemblies { get { return ResourceManager.GetString("PropertyManuallyMissingReferencesListLoadedAssemblies", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Public Key Token. /// </summary> public static string PublicToken { get { return ResourceManager.GetString("PublicToken", resourceCulture); } } /// <summary> /// Looks up a localized string similar to R_ename. /// </summary> public static string R_ename { get { return ResourceManager.GetString("R_ename", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Reference Name. /// </summary> public static string ReferenceName { get { return ResourceManager.GetString("ReferenceName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to References. /// </summary> public static string References { get { return ResourceManager.GetString("References", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Reload all assemblies. /// </summary> public static string RefreshCommand_ReloadAssemblies { get { return ResourceManager.GetString("RefreshCommand_ReloadAssemblies", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Reload all assemblies. /// </summary> public static string ReloadAssemblies { get { return ResourceManager.GetString("ReloadAssemblies", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Remove. /// </summary> public static string Remove { get { return ResourceManager.GetString("Remove", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Remove dead and side effect free code. /// </summary> public static string RemoveDeadSideEffectFreeCode { get { return ResourceManager.GetString("RemoveDeadSideEffectFreeCode", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Remove shell integration. /// </summary> public static string RemoveShellIntegration { get { return ResourceManager.GetString("RemoveShellIntegration", resourceCulture); } } /// <summary> /// Looks up a localized string similar to This will remove &quot;{0}&quot; from the registry at &quot;HKCU\Software\Classes\dllfile\shell\Open with ILSpy\command&quot; and &quot;HKCU\Software\Classes\exefile\shell\Open with ILSpy\command&quot;. /// ///Do you want to continue?. /// </summary> public static string RemoveShellIntegrationMessage { get { return ResourceManager.GetString("RemoveShellIntegrationMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Rename list. /// </summary> public static string RenameList { get { return ResourceManager.GetString("RenameList", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Reset to defaults. /// </summary> public static string ResetToDefaults { get { return ResourceManager.GetString("ResetToDefaults", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Do you really want to load the default settings for the active page?. /// </summary> public static string ResetToDefaultsConfirmationMessage { get { return ResourceManager.GetString("ResetToDefaultsConfirmationMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Resources file (*.resources)|*.resources|Resource XML file|*.resx. /// </summary> public static string ResourcesFileFilter { get { return ResourceManager.GetString("ResourcesFileFilter", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Save. /// </summary> public static string Save { get { return ResourceManager.GetString("Save", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Save Code. /// </summary> public static string SaveCode { get { return ResourceManager.GetString("SaveCode", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Scope search to this assembly. /// </summary> public static string ScopeSearchToThisAssembly { get { return ResourceManager.GetString("ScopeSearchToThisAssembly", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Scope search to this namespace. /// </summary> public static string ScopeSearchToThisNamespace { get { return ResourceManager.GetString("ScopeSearchToThisNamespace", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Search.... /// </summary> public static string Search { get { return ResourceManager.GetString("Search", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Search aborted, more than 1000 results found.. /// </summary> public static string SearchAbortedMoreThan1000ResultsFound { get { return ResourceManager.GetString("SearchAbortedMoreThan1000ResultsFound", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Search (Ctrl+Shift+F or Ctrl+E). /// </summary> public static string SearchCtrlShiftFOrCtrlE { get { return ResourceManager.GetString("SearchCtrlShiftFOrCtrlE", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Searching.... /// </summary> public static string Searching { get { return ResourceManager.GetString("Searching", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Search Microsoft Docs.... /// </summary> public static string SearchMSDN { get { return ResourceManager.GetString("SearchMSDN", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Search. /// </summary> public static string SearchPane_Search { get { return ResourceManager.GetString("SearchPane_Search", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Select All. /// </summary> public static string Select { get { return ResourceManager.GetString("Select", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Select assemblies to open:. /// </summary> public static string SelectAssembliesOpen { get { return ResourceManager.GetString("SelectAssembliesOpen", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Select a list of assemblies (Alt+A). /// </summary> public static string SelectAssemblyListDropdownTooltip { get { return ResourceManager.GetString("SelectAssemblyListDropdownTooltip", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Select language to decompile to (Alt+L). /// </summary> public static string SelectLanguageDropdownTooltip { get { return ResourceManager.GetString("SelectLanguageDropdownTooltip", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Select a list:. /// </summary> public static string SelectList { get { return ResourceManager.GetString("SelectList", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Select PDB.... /// </summary> public static string SelectPDB { get { return ResourceManager.GetString("SelectPDB", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Select version of language to output (Alt+E). /// </summary> public static string SelectVersionDropdownTooltip { get { return ResourceManager.GetString("SelectVersionDropdownTooltip", resourceCulture); } } /// <summary> /// Looks up a localized string similar to You must restart ILSpy for the change to take effect.. /// </summary> public static string SettingsChangeRestartRequired { get { return ResourceManager.GetString("SettingsChangeRestartRequired", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Shell. /// </summary> public static string Shell { get { return ResourceManager.GetString("Shell", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Show _all types and members. /// </summary> public static string Show_allTypesAndMembers { get { return ResourceManager.GetString("Show_allTypesAndMembers", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Show public, private and internal. /// </summary> public static string Show_internalTypesMembers { get { return ResourceManager.GetString("Show_internalTypesMembers", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Show only _public types and members. /// </summary> public static string Show_publiconlyTypesMembers { get { return ResourceManager.GetString("Show_publiconlyTypesMembers", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Show all types and members. /// </summary> public static string ShowAllTypesAndMembers { get { return ResourceManager.GetString("ShowAllTypesAndMembers", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Show assembly load log. /// </summary> public static string ShowAssemblyLoad { get { return ResourceManager.GetString("ShowAssemblyLoad", resourceCulture); } } /// <summary> /// Looks up a localized string similar to ShowChildIndexInBlock. /// </summary> public static string ShowChildIndexInBlock { get { return ResourceManager.GetString("ShowChildIndexInBlock", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Show XML documentation in decompiled code. /// </summary> public static string ShowDocumentationDecompiledCode { get { return ResourceManager.GetString("ShowDocumentationDecompiledCode", resourceCulture); } } /// <summary> /// Looks up a localized string similar to ShowILRanges. /// </summary> public static string ShowILRanges { get { return ResourceManager.GetString("ShowILRanges", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Show info from debug symbols, if available. /// </summary> public static string ShowInfoFromDebugSymbolsAvailable { get { return ResourceManager.GetString("ShowInfoFromDebugSymbolsAvailable", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Show public, private and internal. /// </summary> public static string ShowInternalTypesMembers { get { return ResourceManager.GetString("ShowInternalTypesMembers", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Show line numbers. /// </summary> public static string ShowLineNumbers { get { return ResourceManager.GetString("ShowLineNumbers", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Show metadata tokens. /// </summary> public static string ShowMetadataTokens { get { return ResourceManager.GetString("ShowMetadataTokens", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Show metadata tokens in base 10. /// </summary> public static string ShowMetadataTokensInBase10 { get { return ResourceManager.GetString("ShowMetadataTokensInBase10", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Show only public types and members. /// </summary> public static string ShowPublicOnlyTypesMembers { get { return ResourceManager.GetString("ShowPublicOnlyTypesMembers", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Show raw offsets and bytes before each instruction. /// </summary> public static string ShowRawOffsetsAndBytesBeforeInstruction { get { return ResourceManager.GetString("ShowRawOffsetsAndBytesBeforeInstruction", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Show state after this step. /// </summary> public static string ShowStateAfterThisStep { get { return ResourceManager.GetString("ShowStateAfterThisStep", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Show state before this step. /// </summary> public static string ShowStateBeforeThisStep { get { return ResourceManager.GetString("ShowStateBeforeThisStep", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Size:. /// </summary> public static string Size { get { return ResourceManager.GetString("Size", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Sort assembly _list by name. /// </summary> public static string SortAssembly_listName { get { return ResourceManager.GetString("SortAssembly_listName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Sort assembly list by name. /// </summary> public static string SortAssemblyListName { get { return ResourceManager.GetString("SortAssemblyListName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Sort results by fitness. /// </summary> public static string SortResultsFitness { get { return ResourceManager.GetString("SortResultsFitness", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Stand by.... /// </summary> public static string StandBy { get { return ResourceManager.GetString("StandBy", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Status. /// </summary> public static string Status { get { return ResourceManager.GetString("Status", resourceCulture); } } /// <summary> /// Looks up a localized string similar to String Table. /// </summary> public static string StringTable { get { return ResourceManager.GetString("StringTable", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Style the window title bar. /// </summary> public static string StyleTheWindowTitleBar { get { return ResourceManager.GetString("StyleTheWindowTitleBar", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Tab size:. /// </summary> public static string TabSize { get { return ResourceManager.GetString("TabSize", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Theme. /// </summary> public static string Theme { get { return ResourceManager.GetString("Theme", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Toggle All Folding. /// </summary> public static string ToggleFolding { get { return ResourceManager.GetString("ToggleFolding", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Tree view options. /// </summary> public static string TreeViewOptions { get { return ResourceManager.GetString("TreeViewOptions", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Type. /// </summary> public static string Type { get { return ResourceManager.GetString("Type", resourceCulture); } } /// <summary> /// Looks up a localized string similar to UI Language. /// </summary> public static string UILanguage { get { return ResourceManager.GetString("UILanguage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to System. /// </summary> public static string UILanguage_System { get { return ResourceManager.GetString("UILanguage_System", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No update for ILSpy found.. /// </summary> public static string UpdateILSpyFound { get { return ResourceManager.GetString("UpdateILSpyFound", resourceCulture); } } /// <summary> /// Looks up a localized string similar to UseFieldSugar. /// </summary> public static string UseFieldSugar { get { return ResourceManager.GetString("UseFieldSugar", resourceCulture); } } /// <summary> /// Looks up a localized string similar to UseLogicOperationSugar. /// </summary> public static string UseLogicOperationSugar { get { return ResourceManager.GetString("UseLogicOperationSugar", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use nested namespace structure. /// </summary> public static string UseNestedNamespaceNodes { get { return ResourceManager.GetString("UseNestedNamespaceNodes", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use tabs instead of spaces. /// </summary> public static string UseTabsInsteadOfSpaces { get { return ResourceManager.GetString("UseTabsInsteadOfSpaces", resourceCulture); } } /// <summary> /// Looks up a localized string similar to You are using the latest release.. /// </summary> public static string UsingLatestRelease { get { return ResourceManager.GetString("UsingLatestRelease", resourceCulture); } } /// <summary> /// Looks up a localized string similar to You are using a nightly build newer than the latest release.. /// </summary> public static string UsingNightlyBuildNewerThanLatestRelease { get { return ResourceManager.GetString("UsingNightlyBuildNewerThanLatestRelease", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Value. /// </summary> public static string Value { get { return ResourceManager.GetString("Value", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Value (as string). /// </summary> public static string ValueString { get { return ResourceManager.GetString("ValueString", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use variable names from debug symbols, if available. /// </summary> public static string VariableNamesFromDebugSymbolsAvailable { get { return ResourceManager.GetString("VariableNamesFromDebugSymbolsAvailable", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Version. /// </summary> public static string Version { get { return ResourceManager.GetString("Version", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Version {0} is available.. /// </summary> public static string VersionAvailable { get { return ResourceManager.GetString("VersionAvailable", resourceCulture); } } /// <summary> /// Looks up a localized string similar to View. /// </summary> public static string View { get { return ResourceManager.GetString("View", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Visual Studio Solution file|*.sln|All files|*.*. /// </summary> public static string VisualStudioSolutionFileSlnAllFiles { get { return ResourceManager.GetString("VisualStudioSolutionFileSlnAllFiles", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Warning: This assembly is marked as &apos;reference assembly&apos;, which means that it only contains metadata and no executable code.. /// </summary> public static string WarningAsmMarkedRef { get { return ResourceManager.GetString("WarningAsmMarkedRef", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Warning: Some assembly references could not be resolved automatically. This might lead to incorrect decompilation of some parts,. /// </summary> public static string WarningSomeAssemblyReference { get { return ResourceManager.GetString("WarningSomeAssemblyReference", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Search for t:TypeName, m:Member or c:Constant; use exact match (=term), &apos;should not contain&apos; (-term) or &apos;must contain&apos; (+term); use /reg(ular)?Ex(pressions)?/ or both - t:/Type(Name)?/.... /// </summary> public static string WatermarkText { get { return ResourceManager.GetString("WatermarkText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Close all documents. /// </summary> public static string Window_CloseAllDocuments { get { return ResourceManager.GetString("Window_CloseAllDocuments", resourceCulture); } } /// <summary> /// Looks up a localized string similar to _Reset layout. /// </summary> public static string Window_ResetLayout { get { return ResourceManager.GetString("Window_ResetLayout", resourceCulture); } } } }
ILSpy/ILSpy/Properties/Resources.Designer.cs/0
{ "file_path": "ILSpy/ILSpy/Properties/Resources.Designer.cs", "repo_id": "ILSpy", "token_count": 48805 }
268
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Threading; using ICSharpCode.AvalonEdit.Editing; namespace ICSharpCode.ILSpy.TextView { /// <summary> /// Animated rectangle around the caret. /// This is used after clicking links that lead to another location within the text view. /// </summary> sealed class CaretHighlightAdorner : Adorner { readonly Pen pen; readonly RectangleGeometry geometry; public CaretHighlightAdorner(TextArea textArea) : base(textArea.TextView) { Rect min = textArea.Caret.CalculateCaretRectangle(); min.Offset(-textArea.TextView.ScrollOffset); Rect max = min; double size = Math.Max(min.Width, min.Height) * 0.25; max.Inflate(size, size); pen = new Pen(TextBlock.GetForeground(textArea.TextView).Clone(), 1); geometry = new RectangleGeometry(min, 2, 2); geometry.BeginAnimation(RectangleGeometry.RectProperty, new RectAnimation(min, max, new Duration(TimeSpan.FromMilliseconds(300))) { AutoReverse = true }); pen.Brush.BeginAnimation(Brush.OpacityProperty, new DoubleAnimation(1, 0, new Duration(TimeSpan.FromMilliseconds(200))) { BeginTime = TimeSpan.FromMilliseconds(450) }); } public static void DisplayCaretHighlightAnimation(TextArea textArea) { AdornerLayer layer = AdornerLayer.GetAdornerLayer(textArea.TextView); CaretHighlightAdorner adorner = new CaretHighlightAdorner(textArea); layer.Add(adorner); DispatcherTimer timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromSeconds(1); timer.Tick += delegate { timer.Stop(); layer.Remove(adorner); }; timer.Start(); } protected override void OnRender(DrawingContext drawingContext) { drawingContext.DrawGeometry(null, pen, geometry); } } }
ILSpy/ILSpy/TextView/CaretHighlightAdorner.cs/0
{ "file_path": "ILSpy/ILSpy/TextView/CaretHighlightAdorner.cs", "repo_id": "ILSpy", "token_count": 947 }
269
// Copyright (c) 2021 Tom Englert // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Windows; namespace ICSharpCode.ILSpy.Themes { public static class ResourceKeys { public static ResourceKey TextBackgroundBrush = new ComponentResourceKey(typeof(ResourceKeys), nameof(TextBackgroundBrush)); public static ResourceKey TextForegroundBrush = new ComponentResourceKey(typeof(ResourceKeys), nameof(TextForegroundBrush)); public static ResourceKey TextMarkerBackgroundColor = new ComponentResourceKey(typeof(ResourceKeys), nameof(TextMarkerBackgroundColor)); public static ResourceKey TextMarkerDefinitionBackgroundColor = new ComponentResourceKey(typeof(ResourceKeys), nameof(TextMarkerDefinitionBackgroundColor)); public static ResourceKey SearchResultBackgroundBrush = new ComponentResourceKey(typeof(ResourceKeys), nameof(SearchResultBackgroundBrush)); public static ResourceKey LinkTextForegroundBrush = new ComponentResourceKey(typeof(ResourceKeys), nameof(LinkTextForegroundBrush)); public static ResourceKey BracketHighlightBackgroundBrush = new ComponentResourceKey(typeof(ResourceKeys), nameof(BracketHighlightBackgroundBrush)); public static ResourceKey BracketHighlightBorderPen = new ComponentResourceKey(typeof(ResourceKeys), nameof(BracketHighlightBorderPen)); public static ResourceKey LineNumbersForegroundBrush = new ComponentResourceKey(typeof(ResourceKeys), nameof(LineNumbersForegroundBrush)); public static ResourceKey CurrentLineBackgroundBrush = new ComponentResourceKey(typeof(ResourceKeys), nameof(CurrentLineBackgroundBrush)); public static ResourceKey CurrentLineBorderPen = new ComponentResourceKey(typeof(ResourceKeys), nameof(CurrentLineBorderPen)); public static ResourceKey ThemeAwareButtonEffect = new ComponentResourceKey(typeof(ResourceKeys), nameof(ThemeAwareButtonEffect)); } }
ILSpy/ILSpy/Themes/ResourceKeys.cs/0
{ "file_path": "ILSpy/ILSpy/Themes/ResourceKeys.cs", "repo_id": "ILSpy", "token_count": 727 }
270
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Linq; using System.Reflection.Metadata; using System.Windows.Threading; using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.ILSpyX; using ICSharpCode.TreeView; namespace ICSharpCode.ILSpy.TreeNodes { /// <summary> /// Lists the base types of a class. /// </summary> sealed class BaseTypesTreeNode : ILSpyTreeNode { readonly PEFile module; readonly ITypeDefinition type; public BaseTypesTreeNode(PEFile module, ITypeDefinition type) { this.module = module; this.type = type; this.LazyLoading = true; } public override object Text => Properties.Resources.BaseTypes; public override object Icon => Images.SuperTypes; protected override void LoadChildren() { AddBaseTypes(this.Children, module, type); } internal static void AddBaseTypes(SharpTreeNodeCollection children, PEFile module, ITypeDefinition typeDefinition) { TypeDefinitionHandle handle = (TypeDefinitionHandle)typeDefinition.MetadataToken; DecompilerTypeSystem typeSystem = new DecompilerTypeSystem(module, module.GetAssemblyResolver(), TypeSystemOptions.Default | TypeSystemOptions.Uncached); var t = typeSystem.MainModule.ResolveEntity(handle) as ITypeDefinition; foreach (var td in t.GetAllBaseTypeDefinitions().Reverse().Skip(1)) { if (t.Kind != TypeKind.Interface || t.Kind == td.Kind) children.Add(new BaseTypesEntryNode(td)); } } public override void Decompile(Language language, ITextOutput output, DecompilationOptions options) { App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(EnsureLazyChildren)); foreach (ILSpyTreeNode child in this.Children) { child.Decompile(language, output, options); } } } }
ILSpy/ILSpy/TreeNodes/BaseTypesTreeNode.cs/0
{ "file_path": "ILSpy/ILSpy/TreeNodes/BaseTypesTreeNode.cs", "repo_id": "ILSpy", "token_count": 893 }
271
using System; using System.ComponentModel; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using ICSharpCode.Decompiler.IL; using ICSharpCode.Decompiler.IL.Transforms; using ICSharpCode.ILSpy.Docking; using ICSharpCode.ILSpy.Options; using ICSharpCode.ILSpy.ViewModels; namespace ICSharpCode.ILSpy { public partial class DebugSteps : UserControl { static readonly ILAstWritingOptions writingOptions = new ILAstWritingOptions { UseFieldSugar = true, UseLogicOperationSugar = true }; public static ILAstWritingOptions Options => writingOptions; #if DEBUG ILAstLanguage language; #endif FilterSettings filterSettings; public DebugSteps() { InitializeComponent(); #if DEBUG DockWorkspace.Instance.PropertyChanged += DockWorkspace_PropertyChanged; filterSettings = DockWorkspace.Instance.ActiveTabPage.FilterSettings; filterSettings.PropertyChanged += FilterSettings_PropertyChanged; MainWindow.Instance.SelectionChanged += SelectionChanged; writingOptions.PropertyChanged += WritingOptions_PropertyChanged; if (MainWindow.Instance.CurrentLanguage is ILAstLanguage l) { l.StepperUpdated += ILAstStepperUpdated; language = l; ILAstStepperUpdated(null, null); } #endif } private void DockWorkspace_PropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case nameof(DockWorkspace.Instance.ActiveTabPage): filterSettings.PropertyChanged -= FilterSettings_PropertyChanged; filterSettings = DockWorkspace.Instance.ActiveTabPage.FilterSettings; filterSettings.PropertyChanged += FilterSettings_PropertyChanged; break; } } private void WritingOptions_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { DecompileAsync(lastSelectedStep); } private void SelectionChanged(object sender, SelectionChangedEventArgs e) { Dispatcher.Invoke(() => { tree.ItemsSource = null; lastSelectedStep = int.MaxValue; }); } private void FilterSettings_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { #if DEBUG if (e.PropertyName == "Language") { if (language != null) { language.StepperUpdated -= ILAstStepperUpdated; } if (MainWindow.Instance.CurrentLanguage is ILAstLanguage l) { l.StepperUpdated += ILAstStepperUpdated; language = l; ILAstStepperUpdated(null, null); } } #endif } private void ILAstStepperUpdated(object sender, EventArgs e) { #if DEBUG if (language == null) return; Dispatcher.Invoke(() => { tree.ItemsSource = language.Stepper.Steps; lastSelectedStep = int.MaxValue; }); #endif } private void ShowStateAfter_Click(object sender, RoutedEventArgs e) { Stepper.Node n = (Stepper.Node)tree.SelectedItem; if (n == null) return; DecompileAsync(n.EndStep); } private void ShowStateBefore_Click(object sender, RoutedEventArgs e) { Stepper.Node n = (Stepper.Node)tree.SelectedItem; if (n == null) return; DecompileAsync(n.BeginStep); } private void DebugStep_Click(object sender, RoutedEventArgs e) { Stepper.Node n = (Stepper.Node)tree.SelectedItem; if (n == null) return; DecompileAsync(n.BeginStep, true); } int lastSelectedStep = int.MaxValue; void DecompileAsync(int step, bool isDebug = false) { lastSelectedStep = step; var window = MainWindow.Instance; var state = DockWorkspace.Instance.ActiveTabPage.GetState(); DockWorkspace.Instance.ActiveTabPage.ShowTextViewAsync(textView => textView.DecompileAsync(window.CurrentLanguage, window.SelectedNodes, new DecompilationOptions(window.CurrentLanguageVersion, window.CurrentDecompilerSettings, window.CurrentDisplaySettings) { StepLimit = step, IsDebug = isDebug, TextViewState = state as TextView.DecompilerTextViewState })); } private void tree_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter || e.Key == Key.Return) { if (e.KeyboardDevice.Modifiers == ModifierKeys.Shift) ShowStateBefore_Click(sender, e); else ShowStateAfter_Click(sender, e); e.Handled = true; } } } }
ILSpy/ILSpy/Views/DebugSteps.xaml.cs/0
{ "file_path": "ILSpy/ILSpy/Views/DebugSteps.xaml.cs", "repo_id": "ILSpy", "token_count": 1541 }
272
// Copyright (c) 2020 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Reflection; using System.Windows; using System.Windows.Markup; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ICSharpCode.TreeView")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] [assembly: XmlnsPrefix("http://icsharpcode.net/sharpdevelop/treeview", "treeview")] [assembly: XmlnsDefinition("http://icsharpcode.net/sharpdevelop/treeview", "ICSharpCode.TreeView")]
ILSpy/SharpTreeView/Properties/AssemblyInfo.cs/0
{ "file_path": "ILSpy/SharpTreeView/Properties/AssemblyInfo.cs", "repo_id": "ILSpy", "token_count": 744 }
273
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under MIT X11 license (for details please see \doc\license.txt) using System.Linq; using ICSharpCode.ILSpy; using ICSharpCode.ILSpy.TreeNodes; using Microsoft.Win32; namespace TestPlugin { [ExportContextMenuEntryAttribute(Header = "_Save Assembly")] public class SaveAssembly : IContextMenuEntry { public bool IsVisible(TextViewContext context) { return context.SelectedTreeNodes != null && context.SelectedTreeNodes.All(n => n is AssemblyTreeNode); } public bool IsEnabled(TextViewContext context) { return context.SelectedTreeNodes != null && context.SelectedTreeNodes.Length == 1; } public void Execute(TextViewContext context) { if (context.SelectedTreeNodes == null) return; AssemblyTreeNode node = (AssemblyTreeNode)context.SelectedTreeNodes[0]; var asm = node.LoadedAssembly.GetPEFileOrNull(); if (asm != null) { /*SaveFileDialog dlg = new SaveFileDialog(); dlg.FileName = node.LoadedAssembly.FileName; dlg.Filter = "Assembly|*.dll;*.exe"; if (dlg.ShowDialog(MainWindow.Instance) == true) { asm.MainModule.Write(dlg.FileName); }*/ } } } }
ILSpy/TestPlugin/ContextMenuCommand.cs/0
{ "file_path": "ILSpy/TestPlugin/ContextMenuCommand.cs", "repo_id": "ILSpy", "token_count": 455 }
274
<?xml version="1.0" encoding="utf-8"?> <Project> <Import Project="Sdk.props" Sdk="Microsoft.NET.Sdk" /> <PropertyGroup> <AssemblyName>BeeBuildProgramCommon.Data</AssemblyName> <TargetFramework>netstandard2.1</TargetFramework> <GenerateDocumentationFile>false</GenerateDocumentationFile> <AllowUnsafeBlocks>false</AllowUnsafeBlocks> <EnableDefaultItems>false</EnableDefaultItems> <LangVersion>latest</LangVersion> <NoWarn>1701</NoWarn> </PropertyGroup> <ItemGroup> <Compile Include="Data.cs" /> </ItemGroup> <Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk" /> </Project>
UnityCsReference/Editor/IncrementalBuildPipeline/BeeBuildProgramCommon.Data/BeeBuildProgramCommon.Data.gen.csproj/0
{ "file_path": "UnityCsReference/Editor/IncrementalBuildPipeline/BeeBuildProgramCommon.Data/BeeBuildProgramCommon.Data.gen.csproj", "repo_id": "UnityCsReference", "token_count": 231 }
275
// 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 UnityEditor.Build; using UnityEditor.AssetImporters; using UnityEngine; using UnityEngine.Bindings; using UnityEngine.Scripting; using UnityEngine.U2D; namespace UnityEditor.U2D { // SpriteAtlas Importer lets you modify [[SpriteAtlas]] [HelpURL("https://docs.unity3d.com/2023.2/Documentation/Manual/SpriteAtlasV2.html")] [NativeHeader("Editor/Src/2D/SpriteAtlas/SpriteAtlasImporter.h")] public sealed partial class SpriteAtlasImporter : AssetImporter { extern internal static void MigrateAllSpriteAtlases(); extern public float variantScale { get; set; } extern public bool includeInBuild { get; set; } extern public SpriteAtlasPackingSettings packingSettings { get; set; } extern public SpriteAtlasTextureSettings textureSettings { get; set; } extern public void SetPlatformSettings(TextureImporterPlatformSettings src); extern public TextureImporterPlatformSettings GetPlatformSettings(string buildTarget); extern internal TextureFormat GetTextureFormat(BuildTarget target); extern internal TextureImporterPlatformSettings GetSecondaryPlatformSettings(string buildTarget, string secondaryTextureName); extern internal void SetSecondaryPlatformSettings(TextureImporterPlatformSettings src, string secondaryTextureName); extern internal bool GetSecondaryColorSpace(string secondaryTextureName); extern internal void SetSecondaryColorSpace(string secondaryTextureName, bool srGB); extern internal void DeleteSecondaryPlatformSettings(string secondaryTextureName); } };
UnityCsReference/Editor/Mono/2D/SpriteAtlas/SpriteAtlasImporter.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/2D/SpriteAtlas/SpriteAtlasImporter.bindings.cs", "repo_id": "UnityCsReference", "token_count": 555 }
276
// 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 UnityEditor; namespace UnityEditorInternal { class AnimationPropertyContextualMenu { public static AnimationPropertyContextualMenu Instance = new AnimationPropertyContextualMenu(); IAnimationContextualResponder m_Responder; private static GUIContent addKeyContent = EditorGUIUtility.TrTextContent("Add Key"); private static GUIContent updateKeyContent = EditorGUIUtility.TrTextContent("Update Key"); private static GUIContent removeKeyContent = EditorGUIUtility.TrTextContent("Remove Key"); private static GUIContent removeCurveContent = EditorGUIUtility.TrTextContent("Remove All Keys"); private static GUIContent goToPreviousKeyContent = EditorGUIUtility.TrTextContent("Go to Previous Key"); private static GUIContent goToNextKeyContent = EditorGUIUtility.TrTextContent("Go to Next Key"); private static GUIContent addCandidatesContent = EditorGUIUtility.TrTextContent("Key All Modified"); private static GUIContent addAnimatedContent = EditorGUIUtility.TrTextContent("Key All Animated"); public AnimationPropertyContextualMenu() { EditorApplication.contextualPropertyMenu += OnPropertyContextMenu; MaterialEditor.contextualPropertyMenu += OnPropertyContextMenu; } public void SetResponder(IAnimationContextualResponder responder) { m_Responder = responder; } public bool IsResponder(IAnimationContextualResponder responder) { return responder == m_Responder; } void OnPropertyContextMenu(GenericMenu menu, SerializedProperty property) { if (m_Responder == null) return; PropertyModification[] modifications = AnimationWindowUtility.SerializedPropertyToPropertyModifications(property); bool isPropertyAnimatable = m_Responder.IsAnimatable(modifications); if (isPropertyAnimatable) { var targetObject = property.serializedObject.targetObject; if (m_Responder.IsEditable(targetObject)) OnPropertyContextMenu(menu, modifications); else OnDisabledPropertyContextMenu(menu); } } void OnPropertyContextMenu(GenericMenu menu, MaterialProperty property, Renderer[] renderers) { if (m_Responder == null) return; if (property.targets == null || property.targets.Length == 0) return; if (renderers == null || renderers.Length == 0) return; var modifications = new List<PropertyModification>(); foreach (Renderer renderer in renderers) { modifications.AddRange(MaterialAnimationUtility.MaterialPropertyToPropertyModifications(property, renderer)); } if (m_Responder.IsEditable(renderers[0])) OnPropertyContextMenu(menu, modifications.ToArray()); else OnDisabledPropertyContextMenu(menu); } void OnPropertyContextMenu(GenericMenu menu, PropertyModification[] modifications) { bool hasKey = m_Responder.KeyExists(modifications); bool hasCandidate = m_Responder.CandidateExists(modifications); bool hasCurve = (hasKey || m_Responder.CurveExists(modifications)); bool hasAnyCandidate = m_Responder.HasAnyCandidates(); bool hasAnyCurve = m_Responder.HasAnyCurves(); menu.AddItem(((hasKey && hasCandidate) ? updateKeyContent : addKeyContent), false, () => { m_Responder.AddKey(modifications); }); if (hasKey) { menu.AddItem(removeKeyContent, false, () => { m_Responder.RemoveKey(modifications); }); } else { menu.AddDisabledItem(removeKeyContent); } if (hasCurve) { menu.AddItem(removeCurveContent, false, () => { m_Responder.RemoveCurve(modifications); }); } else { menu.AddDisabledItem(removeCurveContent); } menu.AddSeparator(string.Empty); if (hasAnyCandidate) { menu.AddItem(addCandidatesContent, false, () => { m_Responder.AddCandidateKeys(); }); } else { menu.AddDisabledItem(addCandidatesContent); } if (hasAnyCurve) { menu.AddItem(addAnimatedContent, false, () => { m_Responder.AddAnimatedKeys(); }); } else { menu.AddDisabledItem(addAnimatedContent); } menu.AddSeparator(string.Empty); if (hasCurve) { menu.AddItem(goToPreviousKeyContent, false, () => { m_Responder.GoToPreviousKeyframe(modifications); }); menu.AddItem(goToNextKeyContent, false, () => { m_Responder.GoToNextKeyframe(modifications); }); } else { menu.AddDisabledItem(goToPreviousKeyContent); menu.AddDisabledItem(goToNextKeyContent); } } void OnDisabledPropertyContextMenu(GenericMenu menu) { menu.AddDisabledItem(addKeyContent); menu.AddDisabledItem(removeKeyContent); menu.AddDisabledItem(removeCurveContent); menu.AddSeparator(string.Empty); menu.AddDisabledItem(addCandidatesContent); menu.AddDisabledItem(addAnimatedContent); menu.AddSeparator(string.Empty); menu.AddDisabledItem(goToPreviousKeyContent); menu.AddDisabledItem(goToNextKeyContent); } } }
UnityCsReference/Editor/Mono/Animation/AnimationWindow/AnimationContextualPropertyMenu.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Animation/AnimationWindow/AnimationContextualPropertyMenu.cs", "repo_id": "UnityCsReference", "token_count": 3038 }
277
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEditor; namespace UnityEditorInternal { internal class AnimationWindowKeyframe { public float m_InTangent; public float m_OutTangent; public float m_InWeight; public float m_OutWeight; public WeightedMode m_WeightedMode; public int m_TangentMode; public int m_TimeHash; int m_Hash; float m_time; object m_value; AnimationWindowCurve m_curve; public float time { get { return m_time; } set { m_time = value; m_Hash = 0; m_TimeHash = value.GetHashCode(); } } public object value { get { return m_value; } set { m_value = value; } } public float inTangent { get { return m_InTangent; } set { m_InTangent = value; } } public float outTangent { get { return m_OutTangent; } set { m_OutTangent = value; } } public float inWeight { get { return m_InWeight; } set { m_InWeight = value; } } public float outWeight { get { return m_OutWeight; } set { m_OutWeight = value; } } public WeightedMode weightedMode { get { return m_WeightedMode; } set { m_WeightedMode = value; } } public AnimationWindowCurve curve { get { return m_curve; } set { m_curve = value; m_Hash = 0; } } public bool isPPtrCurve { get { return curve.isPPtrCurve; } } public bool isDiscreteCurve { get { return curve.isDiscreteCurve; } } public AnimationWindowKeyframe() { } public AnimationWindowKeyframe(AnimationWindowKeyframe key) { this.time = key.time; this.value = key.value; this.curve = key.curve; this.m_InTangent = key.m_InTangent; this.m_OutTangent = key.m_OutTangent; this.m_InWeight = key.inWeight; this.m_OutWeight = key.outWeight; this.m_WeightedMode = key.weightedMode; this.m_TangentMode = key.m_TangentMode; this.m_curve = key.m_curve; } public AnimationWindowKeyframe(AnimationWindowCurve curve, Keyframe key) { this.time = key.time; if (curve.isDiscreteCurve) { this.value = UnityEngine.Animations.DiscreteEvaluationAttributeUtilities.ConvertFloatToDiscreteInt(key.value); } else { this.value = key.value; } this.curve = curve; this.m_InTangent = key.inTangent; this.m_OutTangent = key.outTangent; this.m_InWeight = key.inWeight; this.m_OutWeight = key.outWeight; this.m_WeightedMode = key.weightedMode; this.m_TangentMode = key.tangentModeInternal; this.m_curve = curve; } public AnimationWindowKeyframe(AnimationWindowCurve curve, ObjectReferenceKeyframe key) { this.time = key.time; this.value = key.value; this.curve = curve; } public int GetHash() { if (m_Hash == 0) { // Berstein hash unchecked { m_Hash = curve.GetHashCode(); m_Hash = 33 * m_Hash + time.GetHashCode(); } } return m_Hash; } public int GetIndex() { for (int i = 0; i < curve.keyframes.Count; i++) { if (curve.keyframes[i] == this) { return i; } } return -1; } public Keyframe ToKeyframe() { float floatValue; if (curve.isDiscreteCurve) { // case 1395978 // Negative int values converted to float create NaN values. Limiting discrete int values to only positive values // until we rewrite the animation backend with dedicated int curves. floatValue = UnityEngine.Animations.DiscreteEvaluationAttributeUtilities.ConvertDiscreteIntToFloat(Math.Max(Convert.ToInt32(value), 0)); } else { floatValue = Convert.ToSingle(value); } var keyframe = new Keyframe(time, floatValue, inTangent, outTangent); keyframe.tangentModeInternal = m_TangentMode; keyframe.weightedMode = weightedMode; keyframe.inWeight = inWeight; keyframe.outWeight = outWeight; return keyframe; } public ObjectReferenceKeyframe ToObjectReferenceKeyframe() { var keyframe = new ObjectReferenceKeyframe(); keyframe.time = time; keyframe.value = (UnityEngine.Object)value; return keyframe; } } }
UnityCsReference/Editor/Mono/Animation/AnimationWindow/AnimationWindowKeyframe.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Animation/AnimationWindow/AnimationWindowKeyframe.cs", "repo_id": "UnityCsReference", "token_count": 3007 }
278
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; namespace UnityEditor { internal interface CurveRenderer { void DrawCurve(float minTime, float maxTime, Color color, Matrix4x4 transform, Color wrapColor); AnimationCurve GetCurve(); float RangeStart(); float RangeEnd(); void SetWrap(WrapMode wrap); void SetWrap(WrapMode preWrap, WrapMode postWrap); void SetCustomRange(float start, float end); float EvaluateCurveSlow(float time); float EvaluateCurveDeltaSlow(float time); Bounds GetBounds(); Bounds GetBounds(float minTime, float maxTime); float ClampedValue(float value); void FlushCache(); } } // namespace
UnityCsReference/Editor/Mono/Animation/AnimationWindow/CurveRenderer/CurveRenderer.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Animation/AnimationWindow/CurveRenderer/CurveRenderer.cs", "repo_id": "UnityCsReference", "token_count": 341 }
279
// 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 { internal class MinMaxCurveEditorWindow : EditorWindow { const int k_PresetsHeight = 46; const float k_WindowMinSize = 240; const float k_WindowMaxSize = 10000; const float k_PresetSwatchMargin = 45f; const float k_PresetSwatchWidth = 40f; const float k_PresetSwatchHeight = 25f; const float k_PresetSwatchSeperation = 5; const float k_PresetsDropdownButtonSize = 20; static MinMaxCurveEditorWindow s_SharedMinMaxCurveEditor; static CurveEditorWindow.Styles s_Styles; CurveEditor m_CurveEditor; AnimationCurve m_MinCurve; AnimationCurve m_MaxCurve; SerializedProperty m_MultiplierProperty; Color m_Color; DoubleCurvePresetsContentsForPopupWindow m_CurvePresets; [SerializeField] GUIView delegateView; public static MinMaxCurveEditorWindow instance { get { if (!s_SharedMinMaxCurveEditor) s_SharedMinMaxCurveEditor = ScriptableObject.CreateInstance<MinMaxCurveEditorWindow>(); return s_SharedMinMaxCurveEditor; } } public AnimationCurve minCurve { get { return m_MinCurve; } } public AnimationCurve maxCurve { get { return m_MaxCurve; } } public static string xAxisLabel { get; set; } = "time"; public static bool visible { get { return s_SharedMinMaxCurveEditor != null; } } // Called by OnEnable to make sure the CurveEditor is not null, // and by Show so we get a fresh CurveEditor when the user clicks a new curve. void Init(CurveEditorSettings settings) { m_CurveEditor = new CurveEditor(GetCurveEditorRect(), GetCurveWrapperArray(), true); m_CurveEditor.curvesUpdated = UpdateCurve; m_CurveEditor.scaleWithWindow = true; m_CurveEditor.margin = 40; if (settings != null) m_CurveEditor.settings = settings; m_CurveEditor.settings.hTickLabelOffset = 10; m_CurveEditor.settings.rectangleToolFlags = CurveEditorSettings.RectangleToolFlags.MiniRectangleTool; m_CurveEditor.settings.undoRedoSelection = true; m_CurveEditor.settings.showWrapperPopups = true; m_CurveEditor.settings.xAxisLabel = xAxisLabel; UpdateRegionDomain(); // For each of horizontal and vertical axis, if we have a finite range for that axis, use that range, // otherwise use framing logic to determine shown range for that axis. bool frameH = true; bool frameV = true; if (!float.IsNegativeInfinity(m_CurveEditor.settings.hRangeMin) && !float.IsInfinity(m_CurveEditor.settings.hRangeMax)) { m_CurveEditor.SetShownHRangeInsideMargins(m_CurveEditor.settings.hRangeMin, m_CurveEditor.settings.hRangeMax); frameH = false; } if (!float.IsNegativeInfinity(m_CurveEditor.settings.vRangeMin) && !float.IsInfinity(m_CurveEditor.settings.vRangeMax)) { m_CurveEditor.SetShownVRangeInsideMargins(m_CurveEditor.settings.vRangeMin, m_CurveEditor.settings.vRangeMax); frameV = false; } m_CurveEditor.FrameSelected(frameH, frameV); } void InitCurvePresets() { if (m_CurvePresets == null) { AnimationCurve max = m_CurveEditor.animationCurves[0].curve; AnimationCurve min = m_CurveEditor.animationCurves.Length > 1 ? m_CurveEditor.animationCurves[1].curve : new AnimationCurve(); // Selection callback for library window System.Action<DoubleCurve> presetSelectedCallback = delegate(DoubleCurve presetCurve) { var doubleCurve = new DoubleCurve(min, max, true); doubleCurve.minCurve.keys = CurveEditorWindow.GetNormalizedKeys(presetCurve.minCurve.keys, m_CurveEditor); doubleCurve.minCurve.postWrapMode = presetCurve.minCurve.postWrapMode; doubleCurve.minCurve.preWrapMode = presetCurve.minCurve.preWrapMode; doubleCurve.maxCurve.keys = CurveEditorWindow.GetNormalizedKeys(presetCurve.maxCurve.keys, m_CurveEditor); doubleCurve.maxCurve.postWrapMode = presetCurve.maxCurve.postWrapMode; doubleCurve.maxCurve.preWrapMode = presetCurve.maxCurve.preWrapMode; m_MinCurve = doubleCurve.minCurve; m_MaxCurve = doubleCurve.maxCurve; m_CurveEditor.SelectNone(); RefreshShownCurves(); SendEvent("CurveChanged", true); }; // We set the curve to save when showing the popup to ensure to scale the current state of the curve m_CurvePresets = new DoubleCurvePresetsContentsForPopupWindow(new DoubleCurve(min, max, true), presetSelectedCallback); m_CurvePresets.InitIfNeeded(); m_CurvePresets.GetPresetLibraryEditor().GetCurrentLib().useRanges = false; } } public static void SetCurves(SerializedProperty max, SerializedProperty min, SerializedProperty multiplier, Color color) { instance.m_Color = color; if (max == null) instance.m_MaxCurve = null; else instance.m_MaxCurve = max.hasMultipleDifferentValues ? new AnimationCurve() : max.animationCurveValue; if (min == null) instance.m_MinCurve = null; else instance.m_MinCurve = min.hasMultipleDifferentValues ? new AnimationCurve() : min.animationCurveValue; instance.m_MultiplierProperty = multiplier; instance.RefreshShownCurves(); } public static void ShowPopup(GUIView viewToUpdate) { instance.Show(viewToUpdate, null); } void SetAxisUiScalarsCallback(Vector2 newAxisScalars) { if (m_MultiplierProperty == null) return; m_MultiplierProperty.floatValue = newAxisScalars.y; // We must apply the changes as this is called outside of the OnGUI code and changes made will not be applied. m_MultiplierProperty.serializedObject.ApplyModifiedProperties(); } Vector2 GetAxisUiScalarsCallback() { if (m_MultiplierProperty == null) return Vector2.one; if (m_MultiplierProperty.floatValue < 0) { m_MultiplierProperty.floatValue = Mathf.Abs(m_MultiplierProperty.floatValue); m_MultiplierProperty.serializedObject.ApplyModifiedProperties(); } return new Vector2(1, m_MultiplierProperty.floatValue); } CurveWrapper GetCurveWrapper(AnimationCurve curve, int id) { CurveWrapper cw = new CurveWrapper(); cw.id = id; cw.groupId = -1; cw.color = m_Color; cw.hidden = false; cw.readOnly = false; cw.getAxisUiScalarsCallback = GetAxisUiScalarsCallback; cw.setAxisUiScalarsCallback = SetAxisUiScalarsCallback; cw.renderer = new NormalCurveRenderer(curve); cw.renderer.SetWrap(curve.preWrapMode, curve.postWrapMode); return cw; } CurveWrapper[] GetCurveWrapperArray() { int id = "Curve".GetHashCode(); if (m_MaxCurve != null) { var maxWrapper = GetCurveWrapper(m_MaxCurve, id); if (m_MinCurve != null) { var minWrapper = GetCurveWrapper(m_MinCurve, id + 1); minWrapper.regionId = maxWrapper.regionId = 1; return new[] { maxWrapper, minWrapper }; } else { return new[] { maxWrapper }; } } return new CurveWrapper[] {}; } Rect GetCurveEditorRect() { return new Rect(0, 0, position.width, position.height - k_PresetsHeight); } void OnEnable() { if (s_SharedMinMaxCurveEditor && s_SharedMinMaxCurveEditor != this) s_SharedMinMaxCurveEditor.Close(); s_SharedMinMaxCurveEditor = this; Init(null); } void OnDestroy() { m_CurvePresets.GetPresetLibraryEditor().UnloadUsedLibraries(); } void OnDisable() { m_CurveEditor.OnDisable(); if (s_SharedMinMaxCurveEditor == this) s_SharedMinMaxCurveEditor = null; } void RefreshShownCurves() { m_CurveEditor.animationCurves = GetCurveWrapperArray(); UpdateRegionDomain(); } void UpdateRegionDomain() { // Calculate region domain for drawing the shaded region between 2 curves. var domain = new Vector2(float.MaxValue, float.MinValue); if (m_MaxCurve != null && m_MinCurve != null) { foreach (var animationCurve in new[] { m_MaxCurve, m_MinCurve }) { var keyCount = animationCurve.length; if (keyCount > 0) { var keys = animationCurve.keys; domain.x = Mathf.Min(domain.x, animationCurve[0].time); domain.y = Math.Max(domain.y, animationCurve[keyCount - 1].time); } } } m_CurveEditor.settings.curveRegionDomain = domain; } public void Show(GUIView viewToUpdate, CurveEditorSettings settings) { delegateView = viewToUpdate; Init(settings); ShowAuxWindow(); titleContent = EditorGUIUtility.TrTextContent("Curve Editor"); // deal with window size minSize = new Vector2(k_WindowMinSize, k_WindowMinSize + k_PresetsHeight); maxSize = new Vector2(k_WindowMaxSize, k_WindowMaxSize); } void DrawPresetSwatchArea() { GUI.Box(new Rect(0, position.height - k_PresetsHeight, position.width, k_PresetsHeight), "", s_Styles.curveSwatchArea); Color curveColor = m_Color; curveColor.a *= 0.6f; float yPos = position.height - k_PresetsHeight + (k_PresetsHeight - k_PresetSwatchHeight) * 0.5f; InitCurvePresets(); var curveLibrary = m_CurvePresets.GetPresetLibraryEditor().GetCurrentLib(); if (curveLibrary != null) { GUIContent guiContent = EditorGUIUtility.TempContent(string.Empty); for (int i = 0; i < curveLibrary.Count(); i++) { Rect swatchRect = new Rect(k_PresetSwatchMargin + (k_PresetSwatchWidth + k_PresetSwatchSeperation) * i, yPos, k_PresetSwatchWidth, k_PresetSwatchHeight); guiContent.tooltip = curveLibrary.GetName(i); if (GUI.Button(swatchRect, guiContent, s_Styles.curveSwatch)) { AnimationCurve max = m_CurveEditor.animationCurves[0].curve; AnimationCurve min = m_CurveEditor.animationCurves.Length > 1 ? m_CurveEditor.animationCurves[1].curve : null; var animCurve = curveLibrary.GetPreset(i) as DoubleCurve; max.keys = CurveEditorWindow.GetDenormalizedKeys(animCurve.maxCurve.keys, m_CurveEditor); max.postWrapMode = animCurve.maxCurve.postWrapMode; max.preWrapMode = animCurve.maxCurve.preWrapMode; if (min != null) { min.keys = CurveEditorWindow.GetDenormalizedKeys(animCurve.minCurve.keys, m_CurveEditor); min.postWrapMode = animCurve.minCurve.postWrapMode; min.preWrapMode = animCurve.minCurve.preWrapMode; } m_CurveEditor.SelectNone(); RefreshShownCurves(); SendEvent("CurveChanged", true); } if (Event.current.type == EventType.Repaint) curveLibrary.Draw(swatchRect, i); if (swatchRect.xMax > position.width - 2 * k_PresetSwatchMargin) break; } } // Dropdown Rect presetDropDownButtonRect = new Rect(k_PresetSwatchMargin - k_PresetsDropdownButtonSize, yPos + k_PresetSwatchSeperation, k_PresetsDropdownButtonSize, k_PresetsDropdownButtonSize); if (EditorGUI.DropdownButton(presetDropDownButtonRect, EditorGUI.GUIContents.titleSettingsIcon, FocusType.Passive, EditorStyles.inspectorTitlebarText)) { if (m_MaxCurve != null) { AnimationCurve max = m_CurveEditor.animationCurves[0].curve; AnimationCurve maxCopy = new AnimationCurve(CurveEditorWindow.GetNormalizedKeys(max.keys, m_CurveEditor)); maxCopy.postWrapMode = max.postWrapMode; maxCopy.preWrapMode = max.preWrapMode; AnimationCurve minCopy = null; if (m_MinCurve != null) { AnimationCurve min = m_CurveEditor.animationCurves[1].curve; minCopy = new AnimationCurve(CurveEditorWindow.GetNormalizedKeys(min.keys, m_CurveEditor)); minCopy.postWrapMode = min.postWrapMode; minCopy.preWrapMode = min.preWrapMode; } m_CurvePresets.doubleCurveToSave = new DoubleCurve(minCopy, maxCopy, true); PopupWindow.Show(presetDropDownButtonRect, m_CurvePresets); } } } void OnGUI() { bool gotMouseUp = (Event.current.type == EventType.MouseUp); if (delegateView == null) { m_MinCurve = null; m_MaxCurve = null; } if (s_Styles == null) s_Styles = new CurveEditorWindow.Styles(); // Curve Editor m_CurveEditor.rect = GetCurveEditorRect(); m_CurveEditor.hRangeLocked = Event.current.shift; m_CurveEditor.vRangeLocked = EditorGUI.actionKey; GUI.changed = false; GUI.Label(m_CurveEditor.drawRect, GUIContent.none, s_Styles.curveEditorBackground); m_CurveEditor.OnGUI(); DrawPresetSwatchArea(); if (Event.current.type == EventType.Used && gotMouseUp) { DoUpdateCurve(false); SendEvent("CurveChangeCompleted", true); } else if (Event.current.type != EventType.Layout && Event.current.type != EventType.Repaint) { DoUpdateCurve(true); } } public void UpdateCurve() { DoUpdateCurve(false); } void DoUpdateCurve(bool exitGUI) { bool minChanged = m_CurveEditor.animationCurves.Length > 0 && m_CurveEditor.animationCurves[0] != null && m_CurveEditor.animationCurves[0].changed; bool maxChanged = m_CurveEditor.animationCurves.Length > 1 && m_CurveEditor.animationCurves[1] != null && m_CurveEditor.animationCurves[1].changed; if (minChanged || maxChanged) { if (minChanged) m_CurveEditor.animationCurves[0].changed = false; if (maxChanged) m_CurveEditor.animationCurves[1].changed = false; RefreshShownCurves(); SendEvent("CurveChanged", exitGUI); } } void SendEvent(string eventName, bool exitGUI) { if (delegateView) { Event e = EditorGUIUtility.CommandEvent(eventName); Repaint(); delegateView.SendEvent(e); if (exitGUI) GUIUtility.ExitGUI(); } GUI.changed = true; } } }
UnityCsReference/Editor/Mono/Animation/AnimationWindow/MinMaxCurveEditorWindow.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Animation/AnimationWindow/MinMaxCurveEditorWindow.cs", "repo_id": "UnityCsReference", "token_count": 8462 }
280
// 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 UnityEditor; namespace UnityEditorInternal { [NativeHeader("Editor/Src/AnimationCurvePreviewCache.bindings.h")] [NativeHeader("Editor/Src/Utility/SerializedProperty.h")] [NativeHeader("Runtime/Graphics/Texture2D.h")] [StaticAccessor("AnimationCurvePreviewCacheBindings", StaticAccessorType.DoubleColon)] internal class AnimationCurvePreviewCache { // Regions as SerializedProperty public static Texture2D GetPreview(int previewWidth, int previewHeight, SerializedProperty property, SerializedProperty property2, Color color, Rect curveRanges) { return GetPreview(previewWidth, previewHeight, property, property2, color, Color.clear, Color.clear); } public static Texture2D GetPreview(int previewWidth, int previewHeight, SerializedProperty property, SerializedProperty property2, Color color, Color topFillColor, Color bottomFillColor, Rect curveRanges) { if (property2 == null) return GetPropertyPreviewFilled(previewWidth, previewHeight, true, curveRanges, property, color, topFillColor, bottomFillColor); else return GetPropertyPreviewRegionFilled(previewWidth, previewHeight, true, curveRanges, property, property2, color, topFillColor, bottomFillColor); } public static Texture2D GetPreview(int previewWidth, int previewHeight, SerializedProperty property, SerializedProperty property2, Color color) { return GetPreview(previewWidth, previewHeight, property, property2, color, Color.clear, Color.clear); } public static Texture2D GetPreview(int previewWidth, int previewHeight, SerializedProperty property, SerializedProperty property2, Color color, Color topFillColor, Color bottomFillColor) { if (property2 == null) return GetPropertyPreviewFilled(previewWidth, previewHeight, false, new Rect(), property, color, topFillColor, bottomFillColor); else return GetPropertyPreviewRegionFilled(previewWidth, previewHeight, false, new Rect(), property, property2, color, topFillColor, bottomFillColor); } // Regions as AnimationCurves public static Texture2D GetPreview(int previewWidth, int previewHeight, AnimationCurve curve, AnimationCurve curve2, Color color, Color topFillColor, Color bottomFillColor, Rect curveRanges) { return GetCurvePreviewRegionFilled(previewWidth, previewHeight, true, curveRanges, curve, curve2, color, topFillColor, bottomFillColor); } public static Texture2D GetPreview(int previewWidth, int previewHeight, AnimationCurve curve, AnimationCurve curve2, Color color, Rect curveRanges) { return GetPreview(previewWidth, previewHeight, curve, curve2, color, Color.clear, Color.clear, curveRanges); } public static Texture2D GetPreview(int previewWidth, int previewHeight, AnimationCurve curve, AnimationCurve curve2, Color color, Color topFillColor, Color bottomFillColor) { return GetCurvePreviewRegionFilled(previewWidth, previewHeight, false, new Rect(), curve, curve2, color, topFillColor, bottomFillColor); } public static Texture2D GetPreview(int previewWidth, int previewHeight, AnimationCurve curve, AnimationCurve curve2, Color color) { return GetPreview(previewWidth, previewHeight, curve, curve2, color, Color.clear, Color.clear, new Rect()); } public static Texture2D GetPreview(int previewWidth, int previewHeight, SerializedProperty property, Color color, Color topFillColor, Color bottomFillColor, Rect curveRanges) { return GetPropertyPreviewFilled(previewWidth, previewHeight, true, curveRanges, property, color, topFillColor, bottomFillColor); } public static Texture2D GetPreview(int previewWidth, int previewHeight, SerializedProperty property, Color color, Rect curveRanges) { return GetPreview(previewWidth, previewHeight, property, color, Color.clear, Color.clear, curveRanges); } public static Texture2D GetPreview(int previewWidth, int previewHeight, SerializedProperty property, Color color, Color topFillColor, Color bottomFillColor) { return GetPropertyPreviewFilled(previewWidth, previewHeight, false, new Rect(), property, color, topFillColor, bottomFillColor); } public static Texture2D GetPreview(int previewWidth, int previewHeight, SerializedProperty property, Color color) { return GetPreview(previewWidth, previewHeight, property, color, Color.clear, Color.clear, new Rect()); } public static Texture2D GetPreview(int previewWidth, int previewHeight, AnimationCurve curve, Color color, Color topFillColor, Color bottomFillColor, Rect curveRanges) { return GetCurvePreviewFilled(previewWidth, previewHeight, true, curveRanges, curve, color, topFillColor, bottomFillColor); } public static Texture2D GetPreview(int previewWidth, int previewHeight, AnimationCurve curve, Color color, Rect curveRanges) { return GetPreview(previewWidth, previewHeight, curve, color, Color.clear, Color.clear, curveRanges); } public static Texture2D GetPreview(int previewWidth, int previewHeight, AnimationCurve curve, Color color, Color topFillColor, Color bottomFillColor) { return GetCurvePreviewFilled(previewWidth, previewHeight, false, new Rect(), curve, color, topFillColor, bottomFillColor); } public static Texture2D GetPreview(int previewWidth, int previewHeight, AnimationCurve curve, Color color) { return GetPreview(previewWidth, previewHeight, curve, color, Color.clear, Color.clear, new Rect()); } public static extern Texture2D GenerateCurvePreview(int previewWidth, int previewHeight, Rect curveRanges, AnimationCurve curve, Color color, Texture2D existingTexture); internal extern static void ClearCache(); private extern static Texture2D GetPropertyPreview(int previewWidth, int previewHeight, bool useCurveRanges, Rect curveRanges, SerializedProperty property, Color color); private extern static Texture2D GetPropertyPreviewFilled(int previewWidth, int previewHeight, bool useCurveRanges, Rect curveRanges, SerializedProperty property, Color color, Color topFillColor, Color bottomFillColor); private extern static Texture2D GetPropertyPreviewRegion(int previewWidth, int previewHeight, bool useCurveRanges, Rect curveRanges, SerializedProperty property, SerializedProperty property2, Color color); private extern static Texture2D GetPropertyPreviewRegionFilled(int previewWidth, int previewHeight, bool useCurveRanges, Rect curveRanges, SerializedProperty property, SerializedProperty property2, Color color, Color topFillColor, Color bottomFillColor); private extern static Texture2D GetCurvePreview(int previewWidth, int previewHeight, bool useCurveRanges, Rect curveRanges, AnimationCurve curve, Color color); private extern static Texture2D GetCurvePreviewFilled(int previewWidth, int previewHeight, bool useCurveRanges, Rect curveRanges, AnimationCurve curve, Color color, Color topFillColor, Color bottomFillColor); private extern static Texture2D GetCurvePreviewRegion(int previewWidth, int previewHeight, bool useCurveRanges, Rect curveRanges, AnimationCurve curve, AnimationCurve curve2, Color color); private extern static Texture2D GetCurvePreviewRegionFilled(int previewWidth, int previewHeight, bool useCurveRanges, Rect curveRanges, AnimationCurve curve, AnimationCurve curve2, Color color, Color topFillColor, Color bottomFillColor); } }
UnityCsReference/Editor/Mono/AnimationCurvePreviewCache.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/AnimationCurvePreviewCache.bindings.cs", "repo_id": "UnityCsReference", "token_count": 2556 }
281
// 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.VersionControl; using UnityEngine.Scripting; using uei = UnityEngine.Internal; namespace UnityEditor { public sealed partial class AssetDatabase { // Delegate to be called from [[AssetDatabase.ImportPackage]] callbacks public delegate void ImportPackageCallback(string packageName); // Delegate to be called from [[AssetDatabase.ImportPackage]] callbacks in the event of failure public delegate void ImportPackageFailedCallback(string packageName, string errorMessage); // Delegate to be called when package import begins public static event ImportPackageCallback importPackageStarted { add => m_importPackageStartedEvent.Add(value); remove => m_importPackageStartedEvent.Remove(value); } private static EventWithPerformanceTracker<ImportPackageCallback> m_importPackageStartedEvent = new EventWithPerformanceTracker<ImportPackageCallback>($"{nameof(AssetDatabase)}.{nameof(importPackageStarted)}"); // Delegate to be called when package import completes public static event ImportPackageCallback importPackageCompleted { add => m_importPackageCompletedEvent.Add(value); remove => m_importPackageCompletedEvent.Remove(value); } private static EventWithPerformanceTracker<ImportPackageCallback> m_importPackageCompletedEvent = new EventWithPerformanceTracker<ImportPackageCallback>($"{nameof(AssetDatabase)}.{nameof(importPackageCompleted)}"); // Called when package import completes, listing the selected items public static Action<string[]> onImportPackageItemsCompleted; private static DelegateWithPerformanceTracker<Action<string[]>> m_onImportPackageItemsCompleted = new DelegateWithPerformanceTracker<Action<string[]>>($"{nameof(AssetDatabase)}.{nameof(onImportPackageItemsCompleted)}"); // Delegate to be called when package import is cancelled public static event ImportPackageCallback importPackageCancelled { add => m_importPackageCancelledEvent.Add(value); remove => m_importPackageCancelledEvent.Remove(value); } private static EventWithPerformanceTracker<ImportPackageCallback> m_importPackageCancelledEvent = new EventWithPerformanceTracker<ImportPackageCallback>($"{nameof(AssetDatabase)}.{nameof(importPackageCancelled)}"); // Delegate to be called when package import fails public static event ImportPackageFailedCallback importPackageFailed { add => m_importPackageFailedEvent.Add(value); remove => m_importPackageFailedEvent.Remove(value); } private static EventWithPerformanceTracker<ImportPackageFailedCallback> m_importPackageFailedEvent = new EventWithPerformanceTracker<ImportPackageFailedCallback>($"{nameof(AssetDatabase)}.{nameof(importPackageFailed)}"); [RequiredByNativeCode] private static void Internal_CallImportPackageStarted(string packageName) { foreach (var evt in m_importPackageStartedEvent) evt(packageName); } [RequiredByNativeCode] private static void Internal_CallImportPackageCompleted(string packageName) { foreach (var evt in m_importPackageCompletedEvent) evt(packageName); } [RequiredByNativeCode] private static void Internal_CallOnImportPackageItemsCompleted(string[] items) { foreach (var evt in m_onImportPackageItemsCompleted.UpdateAndInvoke(onImportPackageItemsCompleted)) evt(items); } [RequiredByNativeCode] private static void Internal_CallImportPackageCancelled(string packageName) { foreach (var evt in m_importPackageCancelledEvent) evt(packageName); } [RequiredByNativeCode] private static void Internal_CallImportPackageFailed(string packageName, string errorMessage) { foreach (var evt in m_importPackageFailedEvent) evt(packageName, errorMessage); } [RequiredByNativeCode] private static bool Internal_IsOpenForEdit(string assetOrMetaFilePath) { return IsOpenForEdit(assetOrMetaFilePath); } public static void CanOpenForEdit(string[] assetOrMetaFilePaths, List<string> outNotEditablePaths, [uei.DefaultValue("StatusQueryOptions.UseCachedIfPossible")] StatusQueryOptions statusQueryOptions = StatusQueryOptions.UseCachedIfPossible) { if (assetOrMetaFilePaths == null) throw new ArgumentNullException(nameof(assetOrMetaFilePaths)); if (outNotEditablePaths == null) throw new ArgumentNullException(nameof(outNotEditablePaths)); UnityEngine.Profiling.Profiler.BeginSample("AssetDatabase.CanOpenForEdit"); AssetModificationProcessorInternal.CanOpenForEdit(assetOrMetaFilePaths, outNotEditablePaths, statusQueryOptions); UnityEngine.Profiling.Profiler.EndSample(); } public static void IsOpenForEdit(string[] assetOrMetaFilePaths, List<string> outNotEditablePaths, [uei.DefaultValue("StatusQueryOptions.UseCachedIfPossible")] StatusQueryOptions statusQueryOptions = StatusQueryOptions.UseCachedIfPossible) { if (assetOrMetaFilePaths == null) throw new ArgumentNullException(nameof(assetOrMetaFilePaths)); if (outNotEditablePaths == null) throw new ArgumentNullException(nameof(outNotEditablePaths)); UnityEngine.Profiling.Profiler.BeginSample("AssetDatabase.IsOpenForEdit"); AssetModificationProcessorInternal.IsOpenForEdit(assetOrMetaFilePaths, outNotEditablePaths, statusQueryOptions); UnityEngine.Profiling.Profiler.EndSample(); } [RequiredByNativeCode] private static bool Internal_MakeEditable(string path) { return MakeEditable(path); } public static bool MakeEditable(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); return MakeEditable(new[] {path}); } [RequiredByNativeCode] private static bool Internal_MakeEditable2(string[] paths, string prompt = null, List<string> outNotEditablePaths = null) { return MakeEditable(paths, prompt, outNotEditablePaths); } public static bool MakeEditable(string[] paths, string prompt = null, List<string> outNotEditablePaths = null) { if (paths == null) throw new ArgumentNullException(nameof(paths)); UnityEngine.Profiling.Profiler.BeginSample("AssetDatabase.MakeEditable"); ChangeSet changeSet = null; var result = Provider.HandlePreCheckoutCallback(ref paths, ref changeSet); if (result && !AssetModificationProcessorInternal.MakeEditable(paths, prompt, outNotEditablePaths)) result = false; if (result && !Provider.MakeEditableImpl(paths, prompt, changeSet, outNotEditablePaths)) result = false; UnityEngine.Profiling.Profiler.EndSample(); return result; } } }
UnityCsReference/Editor/Mono/AssetDatabase/AssetDatabase.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/AssetDatabase/AssetDatabase.cs", "repo_id": "UnityCsReference", "token_count": 2811 }
282
// 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 { [NativeHeader("Editor/Src/AssetPipeline/ComputeShaderImporter.h")] public sealed partial class ComputeShaderImporter : AssetImporter { public PreprocessorOverride preprocessorOverride { get { return PreprocessorOverride.UseProjectSettings; } set {} } } }
UnityCsReference/Editor/Mono/AssetPipeline/ComputeShaderImporter.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/AssetPipeline/ComputeShaderImporter.bindings.cs", "repo_id": "UnityCsReference", "token_count": 155 }
283
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using System; using UnityEngine.Rendering; using System.Collections.Generic; using static UnityEditor.SpeedTree.Importer.SpeedTreeImporterCommon; namespace UnityEditor.SpeedTree.Importer { [Serializable] internal class MeshSettings { public STUnitConversion unitConversion = STUnitConversion.kFeetToMeters; public float scaleFactor = SpeedTreeConstants.kFeetToMetersRatio; } [Serializable] internal class MaterialSettings { public Color mainColor = Color.white; public Color hueVariation = new Color(1.0f, 0.5f, 0.0f, 0.1f); public float alphaClipThreshold = 0.10f; public float transmissionScale = 0.0f; public bool enableHueVariation = false; public bool enableBumpMapping = true; public bool enableSubsurfaceScattering = true; public Vector4 diffusionProfileAssetID = Vector4.zero; public uint diffusionProfileID = 0; } [Serializable] internal class LightingSettings { public bool enableShadowCasting = true; public bool enableShadowReceiving = true; public bool enableLightProbes = true; public ReflectionProbeUsage reflectionProbeEnumValue = ReflectionProbeUsage.BlendProbes; } [Serializable] internal class AdditionalSettings { public MotionVectorGenerationMode motionVectorModeEnumValue = MotionVectorGenerationMode.Object; public bool generateColliders = true; public bool generateRigidbody = true; } [Serializable] internal class LODSettings { public bool enableSmoothLODTransition = true; public bool animateCrossFading = true; public float billboardTransitionCrossFadeWidth = 0.25f; public float fadeOutWidth = 0.25f; public bool hasBillboard = false; } [Serializable] internal class PerLODSettings { public bool enableSettingOverride = false; // LOD public float height = 0.5f; // Lighting public bool castShadows = false; public bool receiveShadows = false; public bool useLightProbes = false; public ReflectionProbeUsage reflectionProbeUsage = ReflectionProbeUsage.Off; // Material public bool enableBump = false; public bool enableHue = false; public bool enableSubsurface = false; }; [Serializable] internal class MaterialInfo { public Material material = null; public string defaultName = null; public bool exported = false; } [Serializable] internal class LODMaterials { public List<MaterialInfo> materials = new List<MaterialInfo>(); public Dictionary<int, List<int>> lodToMaterials = new Dictionary<int, List<int>>(); public Dictionary<string, int> matNameToIndex = new Dictionary<string, int>(); public void AddLodMaterialIndex(int lod, int matIndex) { if (lodToMaterials.ContainsKey(lod)) { lodToMaterials[lod].Add(matIndex); } else { lodToMaterials.Add(lod, new List<int>() { matIndex}); } } } [Serializable] internal class WindSettings { public bool enableWind = true; [Range(1.0f, 20.0f)] public float strenghResponse = 5.0f; [Range(1.0f, 20.0f)] public float directionResponse = 2.5f; [Range(0.0f, 1.0f)] public float randomness = 0.5f; } // Ideally, we should use 'AssetImporter.SourceAssetIdentifier', but this struct has many problems: // 1 - 'Type' is not a serializable type, so it's always equal to null in our context. // 2 - The C# struct is not matching the C++ class. // 3 - Missing the 'Serializable' attribute on top of the struct. [Serializable] internal class AssetIdentifier { public string type; public string name; public AssetIdentifier(UnityEngine.Object asset) { if (asset == null) { throw new ArgumentNullException("asset"); } this.type = asset.GetType().ToString(); this.name = asset.name; } public AssetIdentifier(Type type, string name) { if (type == null) { throw new ArgumentNullException("type"); } if (name == null) { throw new ArgumentNullException("name"); } if (string.IsNullOrEmpty(name)) { throw new ArgumentException("The name is empty", "name"); } this.type = type.ToString(); this.name = name; } } /// <summary> /// This attribute is used as a callback to set SRP specific properties from the importer. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class MaterialSettingsCallbackAttribute : Attribute { /// <summary> /// The version of the method. /// </summary> public int MethodVersion; /// <summary> /// Initializes a new instance of the MaterialSettingsCallbackAttribute with the given method version. /// </summary> /// <param name="methodVersion">The given method version.</param> public MaterialSettingsCallbackAttribute(int methodVersion) { MethodVersion = methodVersion; } [RequiredSignature] static void SignatureExample(GameObject mainObject) { throw new InvalidOperationException(); } } /// <summary> /// This attribute is used as a callback to extend the inspector by adding /// the Diffuse Profile property when the HDRP package is in use. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class DiffuseProfileCallbackAttribute : Attribute { /// <summary> /// The version of the method. /// </summary> public int MethodVersion; /// <summary> /// Initializes a new instance of the DiffuseProfileCallbackAttribute with the given method version. /// </summary> /// <param name="methodVersion">The given method version.</param> public DiffuseProfileCallbackAttribute(int methodVersion) { MethodVersion = methodVersion; } [RequiredSignature] static void SignatureExample(ref SerializedProperty diffusionProfileAsset, ref SerializedProperty diffusionProfileHash) { throw new InvalidOperationException(); } } }
UnityCsReference/Editor/Mono/AssetPipeline/SpeedTree/SpeedTreeImporterSettings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/AssetPipeline/SpeedTree/SpeedTreeImporterSettings.cs", "repo_id": "UnityCsReference", "token_count": 2736 }
284
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine.Bindings; namespace UnityEditorInternal { [NativeHeader("Editor/Src/AssetStore/AssetStoreCachePathManager.h")] internal partial class AssetStoreCachePathManager { [FreeFunction("AssetStoreCachePathManager::GetDefaultConfig")] public static extern CachePathConfig GetDefaultConfig(); [FreeFunction("AssetStoreCachePathManager::GetConfig")] public static extern CachePathConfig GetConfig(); [FreeFunction("AssetStoreCachePathManager::SetConfig")] public static extern ConfigStatus SetConfig(string newPath); [FreeFunction("AssetStoreCachePathManager::ResetConfig")] public static extern ConfigStatus ResetConfig(); } }
UnityCsReference/Editor/Mono/AssetStoreCachePathManager.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/AssetStoreCachePathManager.bindings.cs", "repo_id": "UnityCsReference", "token_count": 276 }
285
// 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; using UnityEngine; using UnityEditor; namespace UnityEditor { public class AudioCurveRendering { // This slight adjustment is needed to make sure that numerical imprecision doesn't suddenly snap to the wrong pixel (causing vertical gaps and overdrawn lines) private static float pixelEpsilon = 0.005f; public delegate float AudioCurveEvaluator(float x); public delegate float AudioCurveAndColorEvaluator(float x, out Color col); public delegate void AudioMinMaxCurveAndColorEvaluator(float x, out Color col, out float minValue, out float maxValue); public static readonly Color kAudioOrange = new Color(255 / 255f, 168 / 255f, 7 / 255f); // ------------- // Frame, background and clipping utils // ------------- // Returns the content rect (clipped) public static Rect BeginCurveFrame(Rect r) { DrawCurveBackground(r); // Frame is subtracted from rect r = DrawCurveFrame(r); // Content is clipped with group GUI.BeginGroup(r); return new Rect(0, 0, r.width, r.height); } public static void EndCurveFrame() { GUI.EndGroup(); } // Returns content rect public static Rect DrawCurveFrame(Rect r) { if (Event.current.type != EventType.Repaint) return r; EditorStyles.colorPickerBox.Draw(r, false, false, false, false); // Adjust rect for frame: colorPickerBox style has 1 px border r.x += 1f; r.y += 1f; r.width -= 2f; r.height -= 2f; return r; } public static void DrawCurveBackground(Rect r) { EditorGUI.DrawRect(r, new Color(0.3f, 0.3f, 0.3f)); } // ------------- // Curve rendering -- do not remove any of these, as they may be used by custom GUIs of native audio plugins // ------------- public static void DrawFilledCurve(Rect r, AudioCurveEvaluator eval, Color curveColor) { DrawFilledCurve( r, delegate(float x, out Color color) { color = curveColor; return eval(x); } ); } public static void DrawFilledCurve(Rect r, AudioCurveAndColorEvaluator eval) { if (Event.current.type != EventType.Repaint) return; HandleUtility.ApplyWireMaterial(); GL.Begin(GL.LINES); // Adjust by a half pixel to each side so that the transition covers a full pixel. // This is needed for very slowly rising edges. float pixelScale = (float)EditorGUIUtility.pixelsPerPoint; float pixelSize = 1.0f / pixelScale; float pixelHalfSize = 0.5f * pixelSize; float pixelWidth = Mathf.Ceil(r.width) * pixelScale; float startx = Mathf.Floor(r.x) + pixelEpsilon; float wx = 1.0f / (float)(pixelWidth - 1); float cy = r.height * 0.5f; float my = r.y + 0.5f * r.height; float y1 = r.y + r.height; Color color; float py = Mathf.Clamp(cy * eval(0.0f, out color), -cy, cy); for (int x = 0; x < pixelWidth; x++) { float nx = startx + x * pixelSize; float ny = Mathf.Clamp(cy * eval(x * wx, out color), -cy, cy); float e1 = Mathf.Min(ny, py) - pixelHalfSize; float e2 = Mathf.Max(ny, py) + pixelHalfSize; GL.Color(new Color(color.r, color.g, color.b, 0.0f)); AudioMixerDrawUtils.Vertex(nx, my - e2); GL.Color(color); AudioMixerDrawUtils.Vertex(nx, my - e1); AudioMixerDrawUtils.Vertex(nx, my - e1); AudioMixerDrawUtils.Vertex(nx, y1); py = ny; } GL.End(); } // Enforces minValue <= maxValue private static void Sort2(ref float minValue, ref float maxValue) { if (minValue > maxValue) { float tmp = minValue; minValue = maxValue; maxValue = tmp; } } public static void DrawMinMaxFilledCurve(Rect r, AudioMinMaxCurveAndColorEvaluator eval) { HandleUtility.ApplyWireMaterial(); DrawMinMaxFilledCurveInternal(r, eval); } internal static void DrawMinMaxFilledCurveInternal(Rect r, AudioMinMaxCurveAndColorEvaluator eval) { GL.Begin(GL.LINES); // Adjust by a half pixel to each side so that the transition covers a full pixel. // This is needed for very slowly rising edges. float pixelScale = (float)EditorGUIUtility.pixelsPerPoint; float pixelSize = 1.0f / pixelScale; float pixelHalfSize = 0.5f * pixelSize; float pixelWidth = Mathf.Ceil(r.width) * pixelScale; float startx = Mathf.Floor(r.x) + pixelEpsilon; float wx = 1.0f / (float)(pixelWidth - 1); float cy = r.height * 0.5f; float my = r.y + 0.5f * r.height; float minValue, maxValue; Color color; eval(0.0001f, out color, out minValue, out maxValue); Sort2(ref minValue, ref maxValue); float pyMax = my - cy * Mathf.Clamp(maxValue, -1.0f, 1.0f); float pyMin = my - cy * Mathf.Clamp(minValue, -1.0f, 1.0f); float y1 = r.y, y2 = r.y + r.height; for (int x = 0; x < pixelWidth; x++) { float nx = startx + x * pixelSize; eval(x * wx, out color, out minValue, out maxValue); Sort2(ref minValue, ref maxValue); Color edgeColor = new Color(color.r, color.g, color.b, 0.0f); float nyMax = my - cy * Mathf.Clamp(maxValue, -1.0f, 1.0f); float nyMin = my - cy * Mathf.Clamp(minValue, -1.0f, 1.0f); float a = Mathf.Clamp(Mathf.Min(nyMax, pyMax) - pixelHalfSize, y1, y2); float b = Mathf.Clamp(Mathf.Max(nyMax, pyMax) + pixelHalfSize, y1, y2); float c = Mathf.Clamp(Mathf.Min(nyMin, pyMin) - pixelHalfSize, y1, y2); float d = Mathf.Clamp(Mathf.Max(nyMin, pyMin) + pixelHalfSize, y1, y2); Sort2(ref a, ref c); Sort2(ref b, ref d); Sort2(ref a, ref b); Sort2(ref c, ref d); Sort2(ref b, ref c); GL.Color(edgeColor); AudioMixerDrawUtils.Vertex(nx, a); GL.Color(color); AudioMixerDrawUtils.Vertex(nx, b); AudioMixerDrawUtils.Vertex(nx, b); AudioMixerDrawUtils.Vertex(nx, c); AudioMixerDrawUtils.Vertex(nx, c); GL.Color(edgeColor); AudioMixerDrawUtils.Vertex(nx, d); pyMin = nyMin; pyMax = nyMax; } GL.End(); } public static void DrawSymmetricFilledCurve(Rect r, AudioCurveAndColorEvaluator eval) { if (Event.current.type != EventType.Repaint) return; HandleUtility.ApplyWireMaterial(); GL.Begin(GL.LINES); // Adjust by a half pixel to each side so that the transition covers a full pixel. // This is needed for very slowly rising edges. float pixelScale = (float)EditorGUIUtility.pixelsPerPoint; float pixelSize = 1.0f / pixelScale; float pixelHalfSize = 0.5f * pixelSize; float pixelWidth = Mathf.Ceil(r.width) * pixelScale; float startx = Mathf.Floor(r.x) + pixelEpsilon; float wx = 1.0f / (float)(pixelWidth - 1); float cy = r.height * 0.5f; float my = r.y + 0.5f * r.height; Color color; float py = Mathf.Clamp(cy * eval(0.0001f, out color), 0.0f, cy); for (int x = 0; x < pixelWidth; x++) { float nx = startx + x * pixelSize; float ny = Mathf.Clamp(cy * eval(x * wx, out color), 0.0f, cy); float e1 = Mathf.Max(Mathf.Min(ny, py) - pixelHalfSize, 0.0f); // Avoid self-intersection float e2 = Mathf.Min(Mathf.Max(ny, py) + pixelHalfSize, cy); Color edgeColor = new Color(color.r, color.g, color.b, 0.0f); GL.Color(edgeColor); AudioMixerDrawUtils.Vertex(nx, my - e2); GL.Color(color); AudioMixerDrawUtils.Vertex(nx, my - e1); AudioMixerDrawUtils.Vertex(nx, my - e1); AudioMixerDrawUtils.Vertex(nx, my + e1); AudioMixerDrawUtils.Vertex(nx, my + e1); GL.Color(edgeColor); AudioMixerDrawUtils.Vertex(nx, my + e2); py = ny; } GL.End(); } public static void DrawCurve(Rect r, AudioCurveEvaluator eval, Color curveColor) { if (Event.current.type != EventType.Repaint) return; HandleUtility.ApplyWireMaterial(); int numpoints = (int)Mathf.Ceil(r.width); float cy = r.height * 0.5f; float ws = 1.0f / (numpoints - 1); var line = GetPointCache(numpoints); for (int n = 0; n < numpoints; n++) { line[n].x = (int)n + r.x; line[n].y = cy - cy * eval(n * ws) + r.y; line[n].z = 0.0f; } GUI.BeginClip(r); Handles.color = curveColor; Handles.DrawAAPolyLine(3.0f, numpoints, line); GUI.EndClip(); } static Vector3[] s_PointCache; static Vector3[] GetPointCache(int numPoints) { if (s_PointCache == null || s_PointCache.Length != numPoints) { s_PointCache = new Vector3[numPoints]; } return s_PointCache; } // ------------- // Curve gradient rect // ------------- public static void DrawGradientRect(Rect r, Color c1, Color c2, float blend, bool horizontal) { if (Event.current.type != EventType.Repaint) return; HandleUtility.ApplyWireMaterial(); GL.Begin(GL.QUADS); if (horizontal) { GL.Color(new Color(c1.r, c1.g, c1.b, c1.a * blend)); GL.Vertex3(r.x, r.y, 0); GL.Vertex3(r.x + r.width, r.y, 0); GL.Color(new Color(c2.r, c2.g, c2.b, c2.a * blend)); GL.Vertex3(r.x + r.width, r.y + r.height, 0); GL.Vertex3(r.x, r.y + r.height, 0); } else { GL.Color(new Color(c1.r, c1.g, c1.b, c1.a * blend)); GL.Vertex3(r.x, r.y + r.height, 0); GL.Vertex3(r.x, r.y, 0); GL.Color(new Color(c2.r, c2.g, c2.b, c2.a * blend)); GL.Vertex3(r.x + r.width, r.y, 0); GL.Vertex3(r.x + r.width, r.y + r.height, 0); } GL.End(); } } }
UnityCsReference/Editor/Mono/Audio/Effects/AudioCurveRendering.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Audio/Effects/AudioCurveRendering.cs", "repo_id": "UnityCsReference", "token_count": 6069 }
286
// 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 UnityEditorInternal; using UnityEditor.Audio; namespace UnityEditor { internal partial class AudioMixerExposedParametersPopup : PopupWindowContent { // Shows pop up internal static void Popup(AudioMixerController controller, GUIStyle style, params GUILayoutOption[] options) { GUIContent content = GetButtonContent(controller); Rect buttonRect = GUILayoutUtility.GetRect(content, style, options); if (EditorGUI.DropdownButton(buttonRect, content, FocusType.Passive, style)) { PopupWindow.Show(buttonRect, new AudioMixerExposedParametersPopup(controller)); } } // Cache to prevent constructing string on every event static GUIContent m_ButtonContent = EditorGUIUtility.TrTextContent("", "Audio Mixer parameters can be exposed to scripting. Select an Audio Mixer Group, right click one of its properties in the Inspector and select 'Expose'."); static int m_LastNumExposedParams = -1; static GUIContent GetButtonContent(AudioMixerController controller) { if (controller.numExposedParameters != m_LastNumExposedParams) { m_ButtonContent.text = string.Format("Exposed Parameters ({0})", controller.numExposedParameters); m_LastNumExposedParams = controller.numExposedParameters; } return m_ButtonContent; } // private readonly AudioMixerExposedParameterView m_ExposedParametersView; AudioMixerExposedParametersPopup(AudioMixerController controller) { m_ExposedParametersView = new AudioMixerExposedParameterView(new ReorderableListWithRenameAndScrollView.State()); m_ExposedParametersView.OnMixerControllerChanged(controller); } public override void OnGUI(Rect rect) { m_ExposedParametersView.OnEvent(); m_ExposedParametersView.OnGUI(rect); } public override Vector2 GetWindowSize() { Vector2 size = m_ExposedParametersView.CalcSize(); size.x = Math.Max(size.x, 125f); size.y = Math.Max(size.y, 23f); return size; } } } // namespace
UnityCsReference/Editor/Mono/Audio/Mixer/GUI/AudioMixerExposedParametersPopup.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Audio/Mixer/GUI/AudioMixerExposedParametersPopup.cs", "repo_id": "UnityCsReference", "token_count": 968 }
287
// 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.Assertions; using UnityEngine.UIElements; namespace UnityEditor.Audio; static class UIToolkitUtilities { internal static VisualTreeAsset LoadUxml(string filePath) { var asset = EditorGUIUtility.Load(filePath) as VisualTreeAsset; Assert.IsNotNull(asset, $"Could not load UXML file from editor default resources at path: {filePath}."); return asset; } internal static StyleSheet LoadStyleSheet(string filePath) { var asset = EditorGUIUtility.Load(filePath) as StyleSheet; Assert.IsNotNull(asset, $"Could not load UXML file from editor default resources at path: {filePath}."); return asset; } internal static Texture2D LoadIcon(string filename) { var filePath = $"{Path.Combine("Icons", "Audio", filename)}@2x.png"; var asset = EditorGUIUtility.LoadIcon(filePath); Assert.IsNotNull(asset, $"Could not load icon from editor default resources at path: {filePath}."); return asset; } internal static T GetChildByName<T>(VisualElement parentElement, string childName) where T : VisualElement { var childElement = parentElement.Query<VisualElement>(childName).First(); Assert.IsNotNull(childElement, $"Could not find child element '{childName}' in visual tree of element '{parentElement.name}'."); var childElementCast = childElement as T; Assert.IsNotNull(childElementCast, $"Child element '{childName}' of '{parentElement.name}' is not of type {nameof(T)}"); return childElementCast; } internal static T GetChildByClassName<T>(VisualElement parentElement, string childClassName) where T : VisualElement { var childElement = parentElement.Query<VisualElement>(className: childClassName).First(); Assert.IsNotNull(childElement, $"Could not find child element '{childClassName}' in visual tree of element '{parentElement.name}'."); var childElementCast = childElement as T; Assert.IsNotNull(childElementCast, $"Child element '{childClassName}' of '{parentElement.name}' is not of type {nameof(T)}"); return childElementCast; } internal static T GetChildAtIndex<T>(VisualElement parentElement, int index) where T : VisualElement { var childElement = parentElement.ElementAt(index); Assert.IsNotNull(childElement, $"{parentElement.name} has no child element at '{index}."); var childElementCast = childElement as T; Assert.IsNotNull(childElementCast, $"Child element of '{parentElement.name}' at index {index} is not of type {nameof(T)}"); return childElementCast; } }
UnityCsReference/Editor/Mono/Audio/UIToolkitUtilities.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Audio/UIToolkitUtilities.cs", "repo_id": "UnityCsReference", "token_count": 995 }
288
// 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.Reflection; using UnityEngine; using System.Collections.Generic; using System.Linq; using UnityEditor.Build.Reporting; using UnityEditor.Profiling; using UnityEditor.Rendering; using UnityEngine.Scripting; using UnityEditor.AssetImporters; using UnityEngine.SceneManagement; namespace UnityEditor.Build { public interface IOrderedCallback { int callbackOrder { get; } } [Obsolete("Use IPreprocessBuildWithReport instead")] public interface IPreprocessBuild : IOrderedCallback { void OnPreprocessBuild(BuildTarget target, string path); } public abstract class BuildPlayerProcessor : IOrderedCallback { public virtual int callbackOrder => 0; public abstract void PrepareForBuild(BuildPlayerContext buildPlayerContext); } public interface IPreprocessBuildWithReport : IOrderedCallback { void OnPreprocessBuild(BuildReport report); } public interface IFilterBuildAssemblies : IOrderedCallback { string[] OnFilterAssemblies(BuildOptions buildOptions, string[] assemblies); } [Obsolete("Use IPostprocessBuildWithReport instead")] public interface IPostprocessBuild : IOrderedCallback { void OnPostprocessBuild(BuildTarget target, string path); } public interface IPostprocessBuildWithReport : IOrderedCallback { void OnPostprocessBuild(BuildReport report); } public interface IPostBuildPlayerScriptDLLs : IOrderedCallback { void OnPostBuildPlayerScriptDLLs(BuildReport report); } [Obsolete("Use IProcessSceneWithReport instead")] public interface IProcessScene : IOrderedCallback { void OnProcessScene(UnityEngine.SceneManagement.Scene scene); } public interface IProcessSceneWithReport : IOrderedCallback { void OnProcessScene(UnityEngine.SceneManagement.Scene scene, BuildReport report); } public interface IActiveBuildTargetChanged : IOrderedCallback { void OnActiveBuildTargetChanged(BuildTarget previousTarget, BuildTarget newTarget); } public interface IPreprocessShaders : IOrderedCallback { void OnProcessShader(Shader shader, ShaderSnippetData snippet, IList<ShaderCompilerData> data); } public interface IPreprocessComputeShaders : IOrderedCallback { void OnProcessComputeShader(ComputeShader shader, string kernelName, IList<ShaderCompilerData> data); } // This API lets you generate native plugins to be integrated into the player build, // during the incremental player build. The incremental player build platform implementations will know // how to consume these plugins and link them into the build. internal interface IGenerateNativePluginsForAssemblies : IOrderedCallback { // Arguments to the PrepareOnMainThread method public struct PrepareArgs { // The currently active build report. public BuildReport report { get; set; } } // Return value of the PrepareOnMainThread method public struct PrepareResult { // Any pathname in here will be considered an input file to the generated plugins; // Any changes to any of these files will trigger a rebuild of the plugins. public string[] additionalInputFiles { get; set; } // Message to be shown in the progress bar when the GenerateNativePluginsForAssemblies method is run. public string displayName { get; set; } } // Prepare method which is called on the main thread before the incremental player build starts. // Use this to do any work which must happen on the main thread, and to set up dependencies which must trigger a // rebuild of the generated plugins. public PrepareResult PrepareOnMainThread(PrepareArgs args); // Arguments to the GenerateNativePluginsForAssemblies method public struct GenerateArgs { // Path names to the managed assembly files on disk as built for the currently active player target public string[] assemblyFiles { get; set; } } // Return value of the GenerateNativePluginsForAssemblies method public struct GenerateResult { // Any pathname returned in this array will be treated as a plugin to be linked into the player public string[] generatedPlugins { get; set; } public string[] generatedSymbols { get; set; } } // Method to generate native plugins during the player build. This will be called on a thread by the incremental // player build pipeline to allow generating native plugins from editor code which will be linked into the player. // If the plugins have already be generated in a previous build, this will only be called if any of the input // files have changed. Input files are all assemblies (as specified in args.assemblyFiles) and all input files // returned by `PrepareOnMainThread` in `additionalInputFiles`. public GenerateResult GenerateNativePluginsForAssemblies(GenerateArgs args); } public interface IUnityLinkerProcessor : IOrderedCallback { string GenerateAdditionalLinkXmlFile(BuildReport report, UnityLinker.UnityLinkerBuildPipelineData data); } [Obsolete("The IIl2CppProcessor interface has been removed from Unity. Use IPostBuildPlayerScriptDLLs if you need to access player assemblies before il2cpp runs.", true)] public interface IIl2CppProcessor : IOrderedCallback { } internal static class BuildPipelineInterfaces { internal class Processors { #pragma warning disable 618 public List<IPreprocessBuild> buildPreprocessors; public List<IPostprocessBuild> buildPostprocessors; public List<IProcessScene> sceneProcessors; #pragma warning restore 618 public List<BuildPlayerProcessor> buildPlayerProcessors; public List<IPreprocessBuildWithReport> buildPreprocessorsWithReport; public List<IPostprocessBuildWithReport> buildPostprocessorsWithReport; public List<IProcessSceneWithReport> sceneProcessorsWithReport; public List<IFilterBuildAssemblies> filterBuildAssembliesProcessor; public List<IActiveBuildTargetChanged> buildTargetProcessors; public List<IPreprocessShaders> shaderProcessors; public List<IPreprocessComputeShaders> computeShaderProcessors; public List<IPostBuildPlayerScriptDLLs> buildPlayerScriptDLLProcessors; public List<IUnityLinkerProcessor> unityLinkerProcessors; public List<IGenerateNativePluginsForAssemblies> generateNativePluginsForAssembliesProcessors; } private static Processors m_Processors; internal static Processors processors { get { m_Processors = m_Processors ?? new Processors(); return m_Processors; } set { m_Processors = value; } } [Flags] internal enum BuildCallbacks { None = 0, BuildProcessors = 1, SceneProcessors = 2, BuildTargetProcessors = 4, FilterAssembliesProcessors = 8, ShaderProcessors = 16, BuildPlayerScriptDLLProcessors = 32, UnityLinkerProcessors = 64, GenerateNativePluginsForAssembliesProcessors = 128, ComputeShaderProcessors = 256 } //common comparer for all callback types internal static int CompareICallbackOrder(IOrderedCallback a, IOrderedCallback b) { return a.callbackOrder.CompareTo(b.callbackOrder); } static void AddToList<T>(object o, ref List<T> list) where T : class { T inst = o as T; if (inst == null) return; if (list == null) list = new List<T>(); list.Add(inst); } static void AddToListIfTypeImplementsInterface<T>(Type t, ref object o, ref List<T> list) where T : class { if (!ValidateType<T>(t)) return; if (o == null) o = Activator.CreateInstance(t); AddToList(o, ref list); } private class AttributeCallbackWrapper : IPostprocessBuildWithReport, IProcessSceneWithReport, IActiveBuildTargetChanged { internal int m_callbackOrder; internal MethodInfo m_method; public int callbackOrder { get { return m_callbackOrder; } } public AttributeCallbackWrapper(MethodInfo m) { m_callbackOrder = ((CallbackOrderAttribute)Attribute.GetCustomAttribute(m, typeof(CallbackOrderAttribute))).callbackOrder; m_method = m; } public void OnActiveBuildTargetChanged(BuildTarget previousTarget, BuildTarget newTarget) { m_method.Invoke(null, new object[] { previousTarget, newTarget }); } public void OnPostprocessBuild(BuildReport report) { m_method.Invoke(null, new object[] { report.summary.platform, report.summary.outputPath }); } public void OnProcessScene(UnityEngine.SceneManagement.Scene scene, BuildReport report) { m_method.Invoke(null, null); } } //this variable is reinitialized on domain reload so any calls to Init after a domain reload will set things up correctly static BuildCallbacks previousFlags = BuildCallbacks.None; [RequiredByNativeCode] internal static void InitializeBuildCallbacks(BuildCallbacks findFlags) { if (findFlags == previousFlags) return; CleanupBuildCallbacks(); previousFlags = findFlags; bool findBuildProcessors = (findFlags & BuildCallbacks.BuildProcessors) == BuildCallbacks.BuildProcessors; bool findSceneProcessors = (findFlags & BuildCallbacks.SceneProcessors) == BuildCallbacks.SceneProcessors; bool findTargetProcessors = (findFlags & BuildCallbacks.BuildTargetProcessors) == BuildCallbacks.BuildTargetProcessors; bool findFilterProcessors = (findFlags & BuildCallbacks.FilterAssembliesProcessors) == BuildCallbacks.FilterAssembliesProcessors; bool findShaderProcessors = (findFlags & BuildCallbacks.ShaderProcessors) == BuildCallbacks.ShaderProcessors; bool findComputeShaderProcessors = (findFlags & BuildCallbacks.ComputeShaderProcessors) == BuildCallbacks.ComputeShaderProcessors; bool findBuildPlayerScriptDLLsProcessors = (findFlags & BuildCallbacks.BuildPlayerScriptDLLProcessors) == BuildCallbacks.BuildPlayerScriptDLLProcessors; bool findUnityLinkerProcessors = (findFlags & BuildCallbacks.UnityLinkerProcessors) == BuildCallbacks.UnityLinkerProcessors; bool findGenerateNativePluginsForAssembliesProcessors = (findFlags & BuildCallbacks.GenerateNativePluginsForAssembliesProcessors) == BuildCallbacks.GenerateNativePluginsForAssembliesProcessors; var postProcessBuildAttributeParams = new Type[] { typeof(BuildTarget), typeof(string) }; foreach (var t in TypeCache.GetTypesDerivedFrom<IOrderedCallback>()) { if (t.IsAbstract || t.IsInterface) continue; // Defer creating the instance until we actually add it to one of the lists object instance = null; if (findBuildProcessors) { AddToListIfTypeImplementsInterface(t, ref instance, ref processors.buildPlayerProcessors); AddToListIfTypeImplementsInterface(t, ref instance, ref processors.buildPreprocessors); AddToListIfTypeImplementsInterface(t, ref instance, ref processors.buildPreprocessorsWithReport); AddToListIfTypeImplementsInterface(t, ref instance, ref processors.buildPostprocessors); AddToListIfTypeImplementsInterface(t, ref instance, ref processors.buildPostprocessorsWithReport); } if (findSceneProcessors) { AddToListIfTypeImplementsInterface(t, ref instance, ref processors.sceneProcessors); AddToListIfTypeImplementsInterface(t, ref instance, ref processors.sceneProcessorsWithReport); } if (findTargetProcessors) { AddToListIfTypeImplementsInterface(t, ref instance, ref processors.buildTargetProcessors); } if (findFilterProcessors) { AddToListIfTypeImplementsInterface(t, ref instance, ref processors.filterBuildAssembliesProcessor); } if (findUnityLinkerProcessors) { AddToListIfTypeImplementsInterface(t, ref instance, ref processors.unityLinkerProcessors); } if (findGenerateNativePluginsForAssembliesProcessors) { AddToListIfTypeImplementsInterface(t, ref instance, ref processors.generateNativePluginsForAssembliesProcessors); } if (findShaderProcessors) { AddToListIfTypeImplementsInterface(t, ref instance, ref processors.shaderProcessors); } if (findComputeShaderProcessors) { AddToListIfTypeImplementsInterface(t, ref instance, ref processors.computeShaderProcessors); } if (findBuildPlayerScriptDLLsProcessors) { AddToListIfTypeImplementsInterface(t, ref instance, ref processors.buildPlayerScriptDLLProcessors); } } if (findBuildProcessors) { foreach (var m in EditorAssemblies.GetAllMethodsWithAttribute<Callbacks.PostProcessBuildAttribute>()) if (ValidateMethod<Callbacks.PostProcessBuildAttribute>(m, postProcessBuildAttributeParams)) AddToList(new AttributeCallbackWrapper(m), ref processors.buildPostprocessorsWithReport); } if (findSceneProcessors) { foreach (var m in EditorAssemblies.GetAllMethodsWithAttribute<Callbacks.PostProcessSceneAttribute>()) if (ValidateMethod<Callbacks.PostProcessSceneAttribute>(m, Type.EmptyTypes)) AddToList(new AttributeCallbackWrapper(m), ref processors.sceneProcessorsWithReport); } processors.buildPlayerProcessors?.Sort(CompareICallbackOrder); if (processors.buildPreprocessors != null) processors.buildPreprocessors.Sort(CompareICallbackOrder); if (processors.buildPreprocessorsWithReport != null) processors.buildPreprocessorsWithReport.Sort(CompareICallbackOrder); if (processors.buildPostprocessors != null) processors.buildPostprocessors.Sort(CompareICallbackOrder); if (processors.buildPostprocessorsWithReport != null) processors.buildPostprocessorsWithReport.Sort(CompareICallbackOrder); if (processors.buildTargetProcessors != null) processors.buildTargetProcessors.Sort(CompareICallbackOrder); if (processors.sceneProcessors != null) processors.sceneProcessors.Sort(CompareICallbackOrder); if (processors.sceneProcessorsWithReport != null) processors.sceneProcessorsWithReport.Sort(CompareICallbackOrder); if (processors.filterBuildAssembliesProcessor != null) processors.filterBuildAssembliesProcessor.Sort(CompareICallbackOrder); if (processors.unityLinkerProcessors != null) processors.unityLinkerProcessors.Sort(CompareICallbackOrder); if (processors.generateNativePluginsForAssembliesProcessors != null) processors.generateNativePluginsForAssembliesProcessors.Sort(CompareICallbackOrder); if (processors.shaderProcessors != null) processors.shaderProcessors.Sort(CompareICallbackOrder); if (processors.computeShaderProcessors != null) processors.computeShaderProcessors.Sort(CompareICallbackOrder); if (processors.buildPlayerScriptDLLProcessors != null) processors.buildPlayerScriptDLLProcessors.Sort(CompareICallbackOrder); } internal static bool ValidateType<T>(Type t) { return (typeof(T).IsAssignableFrom(t) && t != typeof(AttributeCallbackWrapper)); } static bool ValidateMethod<T>(MethodInfo method, Type[] expectedArguments) { Type attribute = typeof(T); if (method.IsDefined(attribute, false)) { // Remove the `Attribute` from the name. if (!method.IsStatic) { string atributeName = attribute.Name.Replace("Attribute", ""); Debug.LogErrorFormat("Method {0} with {1} attribute must be static.", method.Name, atributeName); return false; } if (method.IsGenericMethod || method.IsGenericMethodDefinition) { string atributeName = attribute.Name.Replace("Attribute", ""); Debug.LogErrorFormat("Method {0} with {1} attribute cannot be generic.", method.Name, atributeName); return false; } var parameters = method.GetParameters(); bool signatureCorrect = parameters.Length == expectedArguments.Length; if (signatureCorrect) { // Check types match for (int i = 0; i < parameters.Length; ++i) { if (parameters[i].ParameterType != expectedArguments[i]) { signatureCorrect = false; break; } } } if (!signatureCorrect) { string atributeName = attribute.Name.Replace("Attribute", ""); string expectedArgumentsString = "static void " + method.Name + "("; for (int i = 0; i < expectedArguments.Length; ++i) { expectedArgumentsString += expectedArguments[i].Name; if (i != expectedArguments.Length - 1) expectedArgumentsString += ", "; } expectedArgumentsString += ")"; Debug.LogErrorFormat("Method {0} with {1} attribute does not have the correct signature, expected: {2}.", method.Name, atributeName, expectedArgumentsString); return false; } return true; } return false; } private static bool InvokeCallbackInterfacesPair<T1, T2>(List<T1> oneInterfaces, Action<T1> invocationOne, List<T2> twoInterfaces, Action<T2> invocationTwo, bool exitOnFailure) where T1 : IOrderedCallback where T2 : IOrderedCallback { if (oneInterfaces == null && twoInterfaces == null) return true; // We want to walk both interface lists and invoke the callbacks, but if we just did the whole of list 1 followed by the whole of list 2, the ordering would be wrong. // So, we have to walk both lists simultaneously, calling whichever callback has the lower ordering value IEnumerator<T1> e1 = (oneInterfaces != null) ? (IEnumerator<T1>)oneInterfaces.GetEnumerator() : null; IEnumerator<T2> e2 = (twoInterfaces != null) ? (IEnumerator<T2>)twoInterfaces.GetEnumerator() : null; if (e1 != null && !e1.MoveNext()) e1 = null; if (e2 != null && !e2.MoveNext()) e2 = null; while (e1 != null || e2 != null) { try { if (e1 != null && (e2 == null || e1.Current.callbackOrder < e2.Current.callbackOrder)) { var callback = e1.Current; if (!e1.MoveNext()) e1 = null; invocationOne(callback); } else if (e2 != null) { var callback = e2.Current; if (!e2.MoveNext()) e2 = null; invocationTwo(callback); } } catch (TargetInvocationException e) { // Note: Attribute based callbacks are called via reflection. // Exceptions in those calls are wrapped in TargetInvocationException Debug.LogException(e.InnerException); if (exitOnFailure) return false; } catch (Exception e) { Debug.LogException(e); if (exitOnFailure) return false; } } return true; } internal static void PreparePlayerBuild(BuildPlayerContext context) { foreach (var p in processors.buildPlayerProcessors ?? new List<BuildPlayerProcessor>()) p.PrepareForBuild(context); } [RequiredByNativeCode] internal static void OnBuildPreProcess(BuildReport report) { #pragma warning disable 618 InvokeCallbackInterfacesPair( processors.buildPreprocessors, bpp => bpp.OnPreprocessBuild(report.summary.platform, report.summary.outputPath), processors.buildPreprocessorsWithReport, bpp => bpp.OnPreprocessBuild(report), (report.summary.options & BuildOptions.StrictMode) != 0 || (report.summary.assetBundleOptions & BuildAssetBundleOptions.StrictMode) != 0); #pragma warning restore 618 } [RequiredByNativeCode] internal static void OnSceneProcess(UnityEngine.SceneManagement.Scene scene, BuildReport report) { #pragma warning disable 618 InvokeCallbackInterfacesPair( processors.sceneProcessors, spp => { using (new EditorPerformanceMarker($"{spp.GetType().Name}.{nameof(spp.OnProcessScene)}", spp.GetType()).Auto()) spp.OnProcessScene(scene); }, processors.sceneProcessorsWithReport, spp => { using (new EditorPerformanceMarker($"{spp.GetType().Name}.{nameof(spp.OnProcessScene)}", spp.GetType()).Auto()) spp.OnProcessScene(scene, report); }, report && ((report.summary.options & BuildOptions.StrictMode) != 0 || (report.summary.assetBundleOptions & BuildAssetBundleOptions.StrictMode) != 0)); #pragma warning restore 618 } [RequiredByNativeCode] internal static Hash128 OnSceneProcess_HashVersion() { Hash128 hashVersion = new Hash128(); Type versionAttrribute = typeof(BuildCallbackVersionAttribute); #pragma warning disable 618 if (processors.sceneProcessors != null) { foreach (IProcessScene processor in processors.sceneProcessors) { Type processorType = processor.GetType(); hashVersion.Append(processorType.AssemblyQualifiedName); BuildCallbackVersionAttribute attribute = Attribute.GetCustomAttribute(processorType, versionAttrribute, false) as BuildCallbackVersionAttribute; hashVersion.Append(attribute != null ? attribute.Version : 1); } } #pragma warning restore 618 if (processors.sceneProcessorsWithReport != null) { foreach (IProcessSceneWithReport processor in processors.sceneProcessorsWithReport) { Type processorType = processor.GetType(); hashVersion.Append(processorType.AssemblyQualifiedName); BuildCallbackVersionAttribute attribute = Attribute.GetCustomAttribute(processorType, versionAttrribute, false) as BuildCallbackVersionAttribute; hashVersion.Append(attribute != null ? attribute.Version : 1); } } return hashVersion; } [RequiredByNativeCode] internal static void OnBuildPostProcess(BuildReport report) { #pragma warning disable 618 InvokeCallbackInterfacesPair( processors.buildPostprocessors, bpp => bpp.OnPostprocessBuild(report.summary.platform, report.summary.outputPath), processors.buildPostprocessorsWithReport, bpp => bpp.OnPostprocessBuild(report), (report.summary.options & BuildOptions.StrictMode) != 0 || (report.summary.assetBundleOptions & BuildAssetBundleOptions.StrictMode) != 0); #pragma warning restore 618 } [RequiredByNativeCode] internal static void OnActiveBuildTargetChanged(BuildTarget previousPlatform, BuildTarget newPlatform) { if (processors.buildTargetProcessors != null) { foreach (IActiveBuildTargetChanged abtc in processors.buildTargetProcessors) { try { abtc.OnActiveBuildTargetChanged(previousPlatform, newPlatform); } catch (Exception e) { Debug.LogException(e); } } } } [RequiredByNativeCode] internal static ShaderCompilerData[] OnPreprocessShaders(Shader shader, ShaderSnippetData snippet, ShaderCompilerData[] data) { var dataList = data.ToList(); if (processors.shaderProcessors != null) { foreach (IPreprocessShaders abtc in processors.shaderProcessors) { abtc.OnProcessShader(shader, snippet, dataList); } } return dataList.ToArray(); } [RequiredByNativeCode] internal static ShaderCompilerData[] OnPreprocessComputeShaders(ComputeShader shader, string kernelName, ShaderCompilerData[] data) { var dataList = data.ToList(); if (processors.computeShaderProcessors != null) { foreach (IPreprocessComputeShaders abtc in processors.computeShaderProcessors) { try { abtc.OnProcessComputeShader(shader, kernelName, dataList); } catch (Exception e) { Debug.LogException(e); } } } return dataList.ToArray(); } [RequiredByNativeCode] internal static bool HasOnPostBuildPlayerScriptDLLs() { return (processors.buildPlayerScriptDLLProcessors != null && processors.buildPlayerScriptDLLProcessors.Any()); } [RequiredByNativeCode] internal static void OnPostBuildPlayerScriptDLLs(BuildReport report) { if (processors.buildPlayerScriptDLLProcessors != null) { foreach (var step in processors.buildPlayerScriptDLLProcessors) { try { step.OnPostBuildPlayerScriptDLLs(report); } catch (Exception e) { Debug.LogException(e); if ((report.summary.options & BuildOptions.StrictMode) != 0 || (report.summary.assetBundleOptions & BuildAssetBundleOptions.StrictMode) != 0) return; } } } } [RequiredByNativeCode] internal static string[] FilterAssembliesIncludedInBuild(BuildOptions buildOptions, string[] assemblies) { if (processors.filterBuildAssembliesProcessor == null) { return assemblies; } string[] startAssemblies = assemblies; string[] filteredAssemblies = assemblies; foreach (var filteredAssembly in processors.filterBuildAssembliesProcessor) { int assemblyCount = filteredAssemblies.Length; filteredAssemblies = filteredAssembly.OnFilterAssemblies(buildOptions, filteredAssemblies); if (filteredAssemblies.Length > assemblyCount) { throw new Exception("More Assemblies in the list than delivered. Only filtering, not adding extra assemblies"); } } if (!filteredAssemblies.All(x => startAssemblies.Contains(x))) { throw new Exception("New Assembly names are in the list. Only filtering are allowed"); } return filteredAssemblies; } [RequiredByNativeCode] internal static void CleanupBuildCallbacks() { processors.buildTargetProcessors = null; processors.buildPlayerProcessors = null; processors.buildPreprocessors = null; processors.buildPostprocessors = null; processors.sceneProcessors = null; processors.buildPreprocessorsWithReport = null; processors.buildPostprocessorsWithReport = null; processors.sceneProcessorsWithReport = null; processors.filterBuildAssembliesProcessor = null; processors.unityLinkerProcessors = null; processors.generateNativePluginsForAssembliesProcessors = null; processors.shaderProcessors = null; processors.computeShaderProcessors = null; processors.buildPlayerScriptDLLProcessors = null; previousFlags = BuildCallbacks.None; } } }
UnityCsReference/Editor/Mono/BuildPipeline/BuildPipelineInterfaces.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/BuildPipeline/BuildPipelineInterfaces.cs", "repo_id": "UnityCsReference", "token_count": 13624 }
289
// 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.UnityLinker { /// <summary> /// Data exposed during IRunUnityLinker callbacks /// </summary> public sealed class UnityLinkerBuildPipelineData { public readonly BuildTarget target; [Obsolete("For platforms using the new incremental build pipeline, inputDirectory will no longer contain any files", false)] public readonly string inputDirectory; public UnityLinkerBuildPipelineData(BuildTarget target, string inputDirectory) { this.target = target; #pragma warning disable 618 this.inputDirectory = inputDirectory; #pragma warning restore } } }
UnityCsReference/Editor/Mono/BuildPipeline/UnityLinker/UnityLinkerBuildPipelineData.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/BuildPipeline/UnityLinker/UnityLinkerBuildPipelineData.cs", "repo_id": "UnityCsReference", "token_count": 279 }
290
// 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 TargetAttributes = UnityEditor.BuildTargetDiscovery.TargetAttributes; namespace UnityEditor.Build.Profile { [Serializable] internal sealed class SharedPlatformSettings: BuildProfilePlatformSettingsBase { internal const string k_SettingWindowsDevicePortalAddress = "windowsDevicePortalAddress"; internal const string k_SettingWindowsDevicePortalUsername = "windowsDevicePortalUsername"; internal const string k_SettingWindowsDevicePortalPassword = "windowsDevicePortalPassword"; internal const string k_SettingForceInstallation = "forceInstallation"; internal const string k_SettingiOSXcodeBuildConfig = "iOSXcodeBuildConfig"; internal const string k_SettingSymlinkSources = "symlinkSources"; internal const string k_SettingPreferredXcode = "preferredXcode"; internal const string k_SettingSymlinkTrampoline = "symlinkTrampoline"; internal const string k_SettingRemoteDeviceInfo = "remoteDeviceInfo"; internal const string k_SettingRemoteDeviceAddress = "remoteDeviceAddress"; internal const string k_SettingRemoteDeviceUsername = "remoteDeviceUsername"; internal const string k_SettingRemoteDeviceExports = "remoteDeviceExports"; internal const string k_SettingPathOnRemoteDevice = "pathOnRemoteDevice"; [SerializeField] string m_WindowsDevicePortalAddress = string.Empty; [SerializeField] string m_WindowsDevicePortalUsername = string.Empty; string m_WindowsDevicePortalPassword = string.Empty; [SerializeField] bool m_ForceInstallation = false; [SerializeField] XcodeBuildConfig m_iOSXcodeBuildConfig = XcodeBuildConfig.Release; [SerializeField] bool m_SymlinkSources = false; [SerializeField] string m_PreferredXcode = string.Empty; [SerializeField] bool m_SymlinkTrampoline = false; [SerializeField] bool m_RemoteDeviceInfo = false; [SerializeField] string m_RemoteDeviceAddress = string.Empty; [SerializeField] string m_RemoteDeviceUsername = string.Empty; [SerializeField] string m_RemoteDeviceExports = string.Empty; [SerializeField] string m_PathOnRemoteDevice = string.Empty; internal protected override bool development { get => base.development; set { if (base.development != value) { base.development = value; SyncSharedSettings(k_SettingDevelopment); } } } internal protected override bool connectProfiler { get => base.connectProfiler; set { if (base.connectProfiler != value) { base.connectProfiler = value; SyncSharedSettings(k_SettingConnectProfiler); } } } internal protected override bool buildWithDeepProfilingSupport { get => base.buildWithDeepProfilingSupport; set { if (base.buildWithDeepProfilingSupport != value) { base.buildWithDeepProfilingSupport = value; SyncSharedSettings(k_SettingBuildWithDeepProfilingSupport); } } } internal protected override bool allowDebugging { get => base.allowDebugging; set { if (base.allowDebugging != value) { base.allowDebugging = value; SyncSharedSettings(k_SettingAllowDebugging); } } } internal protected override bool waitForManagedDebugger { get => base.waitForManagedDebugger; set { if (base.waitForManagedDebugger != value) { base.waitForManagedDebugger = value; SyncSharedSettings(k_SettingWaitForManagedDebugger); } } } internal protected override int managedDebuggerFixedPort { get => base.managedDebuggerFixedPort; set { if (base.managedDebuggerFixedPort != value) { base.managedDebuggerFixedPort = value; SyncSharedSettings(k_SettingManagedDebuggerFixedPort); } } } internal protected override bool explicitNullChecks { get => base.explicitNullChecks; set { if (base.explicitNullChecks != value) { base.explicitNullChecks = value; SyncSharedSettings(k_SettingExplicitNullChecks); } } } internal protected override bool explicitDivideByZeroChecks { get => base.explicitDivideByZeroChecks; set { if (base.explicitDivideByZeroChecks != value) { base.explicitDivideByZeroChecks = value; SyncSharedSettings(k_SettingExplicitDivideByZeroChecks); } } } internal protected override bool explicitArrayBoundsChecks { get => base.explicitArrayBoundsChecks; set { if (base.explicitArrayBoundsChecks != value) { base.explicitArrayBoundsChecks = value; SyncSharedSettings(k_SettingExplicitArrayBoundsChecks); } } } internal override Compression compressionType { get => base.compressionType; set { if (base.compressionType != value) { base.compressionType = value; SyncSharedSettings(k_SettingCompressionType); } } } internal protected override bool installInBuildFolder { get => base.installInBuildFolder; set { if (base.installInBuildFolder != value) { base.installInBuildFolder = value; SyncSharedSettings(k_SettingInstallInBuildFolder); } } } public string windowsDevicePortalAddress { get => m_WindowsDevicePortalAddress; set { if (m_WindowsDevicePortalAddress != value) { m_WindowsDevicePortalAddress = value; SyncSharedSettings(k_SettingWindowsDevicePortalAddress); } } } public string windowsDevicePortalUsername { get => m_WindowsDevicePortalUsername; set { if (m_WindowsDevicePortalUsername != value) { m_WindowsDevicePortalUsername = value; SyncSharedSettings(k_SettingWindowsDevicePortalUsername); } } } public string windowsDevicePortalPassword { get => m_WindowsDevicePortalPassword; set { if (m_WindowsDevicePortalPassword != value) { m_WindowsDevicePortalPassword = value; SyncSharedSettings(k_SettingWindowsDevicePortalPassword); } } } public bool forceInstallation { get => m_ForceInstallation; set { if (m_ForceInstallation != value) { m_ForceInstallation = value; SyncSharedSettings(k_SettingForceInstallation); } } } public XcodeBuildConfig iOSXcodeBuildConfig { get => m_iOSXcodeBuildConfig; set { if (m_iOSXcodeBuildConfig != value) { m_iOSXcodeBuildConfig = value; SyncSharedSettings(k_SettingiOSXcodeBuildConfig); } } } public bool symlinkSources { get => m_SymlinkSources; set { if (m_SymlinkSources != value) { m_SymlinkSources = value; SyncSharedSettings(k_SettingSymlinkSources); } } } public string preferredXcode { get => m_PreferredXcode; set { if (m_PreferredXcode != value) { m_PreferredXcode = value; SyncSharedSettings(k_SettingPreferredXcode); } } } public bool symlinkTrampoline { get => m_SymlinkTrampoline; set { if (m_SymlinkTrampoline != value) { m_SymlinkTrampoline = value; SyncSharedSettings(k_SettingSymlinkTrampoline); } } } public bool remoteDeviceInfo { get => m_RemoteDeviceInfo; set { if (m_RemoteDeviceInfo != value) { m_RemoteDeviceInfo = value; SyncSharedSettings(k_SettingRemoteDeviceInfo); } } } public string remoteDeviceAddress { get => m_RemoteDeviceAddress; set { if (m_RemoteDeviceAddress != value) { m_RemoteDeviceAddress = value; SyncSharedSettings(k_SettingRemoteDeviceAddress); } } } public string remoteDeviceUsername { get => m_RemoteDeviceUsername; set { if (m_RemoteDeviceUsername != value) { m_RemoteDeviceUsername = value; SyncSharedSettings(k_SettingRemoteDeviceUsername); } } } public string remoteDeviceExports { get => m_RemoteDeviceExports; set { if (m_RemoteDeviceExports != value) { m_RemoteDeviceExports = value; SyncSharedSettings(k_SettingRemoteDeviceExports); } } } public string pathOnRemoteDevice { get => m_PathOnRemoteDevice; set { if (m_PathOnRemoteDevice != value) { m_PathOnRemoteDevice = value; SyncSharedSettings(k_SettingPathOnRemoteDevice); } } } public override string GetSharedSetting(string name) { return name switch { k_SettingWindowsDevicePortalPassword => windowsDevicePortalPassword, _ => null, }; } void SyncSharedSettings(string name) { var classicProfiles = BuildProfileContext.instance.classicPlatformProfiles; foreach (var profile in classicProfiles) { var platformSettingsBase = profile.platformBuildProfile; if (platformSettingsBase == null) continue; switch (name) { case k_SettingDevelopment: platformSettingsBase.development = development; break; case k_SettingConnectProfiler: platformSettingsBase.connectProfiler = connectProfiler; break; case k_SettingBuildWithDeepProfilingSupport: platformSettingsBase.buildWithDeepProfilingSupport = buildWithDeepProfilingSupport; break; case k_SettingAllowDebugging: platformSettingsBase.allowDebugging = allowDebugging; break; case k_SettingWaitForManagedDebugger: platformSettingsBase.waitForManagedDebugger = waitForManagedDebugger; break; case k_SettingManagedDebuggerFixedPort: platformSettingsBase.managedDebuggerFixedPort = managedDebuggerFixedPort; break; case k_SettingExplicitNullChecks: platformSettingsBase.explicitNullChecks = explicitNullChecks; break; case k_SettingExplicitDivideByZeroChecks: platformSettingsBase.explicitDivideByZeroChecks = explicitDivideByZeroChecks; break; case k_SettingExplicitArrayBoundsChecks: platformSettingsBase.explicitArrayBoundsChecks = explicitArrayBoundsChecks; break; case k_SettingCompressionType: { var isStandalone = BuildTargetDiscovery.PlatformHasFlag(profile.buildTarget, TargetAttributes.IsStandalonePlatform); if (isStandalone) { platformSettingsBase.compressionType = compressionType; } break; } case k_SettingInstallInBuildFolder: platformSettingsBase.installInBuildFolder = installInBuildFolder; break; case k_SettingWindowsDevicePortalAddress: platformSettingsBase.SetSharedSetting(k_SettingWindowsDevicePortalAddress, windowsDevicePortalAddress); break; case k_SettingWindowsDevicePortalUsername: platformSettingsBase.SetSharedSetting(k_SettingWindowsDevicePortalUsername, windowsDevicePortalUsername); break; case k_SettingWindowsDevicePortalPassword: platformSettingsBase.SetSharedSetting(k_SettingWindowsDevicePortalPassword, windowsDevicePortalPassword); break; case k_SettingForceInstallation: platformSettingsBase.SetSharedSetting(k_SettingForceInstallation, forceInstallation.ToString().ToLower()); break; case k_SettingiOSXcodeBuildConfig: platformSettingsBase.SetSharedSetting(k_SettingiOSXcodeBuildConfig, iOSXcodeBuildConfig.ToString()); break; case k_SettingSymlinkSources: platformSettingsBase.SetSharedSetting(k_SettingSymlinkSources, symlinkSources.ToString().ToLower()); break; case k_SettingPreferredXcode: platformSettingsBase.SetSharedSetting(k_SettingPreferredXcode, preferredXcode); break; case k_SettingSymlinkTrampoline: platformSettingsBase.SetSharedSetting(k_SettingSymlinkTrampoline, symlinkTrampoline.ToString().ToLower()); break; case k_SettingRemoteDeviceInfo: platformSettingsBase.SetSharedSetting(k_SettingRemoteDeviceInfo, remoteDeviceInfo.ToString().ToLower()); break; case k_SettingRemoteDeviceAddress: platformSettingsBase.SetSharedSetting(k_SettingRemoteDeviceAddress, remoteDeviceAddress); break; case k_SettingRemoteDeviceUsername: platformSettingsBase.SetSharedSetting(k_SettingRemoteDeviceUsername, remoteDeviceUsername); break; case k_SettingRemoteDeviceExports: platformSettingsBase.SetSharedSetting(k_SettingRemoteDeviceExports, remoteDeviceExports); break; case k_SettingPathOnRemoteDevice: platformSettingsBase.SetSharedSetting(k_SettingPathOnRemoteDevice, pathOnRemoteDevice); break; } } } } }
UnityCsReference/Editor/Mono/BuildProfile/SharedPlatformSettings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/BuildProfile/SharedPlatformSettings.cs", "repo_id": "UnityCsReference", "token_count": 8945 }
291
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using UnityEngine.Categorization; using Unity.Collections; namespace UnityEditor.Categorization { /* Sorting API that rely on DisplayCategory and DisplaySubCategory */ internal interface ICategorizable { Type type { get; } } interface IOrdering { string name { get; } int order { get; } } //Need to be a class to prevent loop definition with leaf that can cause issue when loading type through reflection internal class Category<T> : IEnumerable<T>, IOrdering where T : ICategorizable, IOrdering { public List<T> content { get; private set; } public string name { get; private set; } public int order { get; private set; } public Type type => content.Count > 0 ? content[0].type : null; public T this[int i] => content[i]; public int count => content.Count; public Category(string name, int order) { content = new(); this.name = name; this.order = order; } public void Add(T newElement, IComparer<T> comparer) => content.AddSorted(newElement, comparer); public IEnumerator<T> GetEnumerator() => content.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => content.GetEnumerator(); } internal struct LeafElement<T> : IOrdering, ICategorizable where T : ICategorizable { public T data { get; private set; } public static implicit operator T(LeafElement<T> leaftElement) => leaftElement.data; public string name { get; private set; } public int order { get; private set; } public Category<LeafElement<T>> parent { get; private set; } public Type type => typeof(T); public LeafElement(T data, string name, int order, Category<LeafElement<T>> parent) { this.data = data; this.name = name; this.order = order; this.parent = parent; } } internal static class CategorizeHelper { struct OrderingComparer<T> : IComparer<T> where T : IOrdering { public int Compare(T a, T b) { var order = a.order.CompareTo(b.order); if (order != 0) return order; return a.name.CompareTo(b.name); } } internal static List<Category<LeafElement<T>>> SortByCategory<T>(this List<T> list) where T : ICategorizable { var categories = new Dictionary<string, Category<LeafElement<T>>>(); var result = new List<Category<LeafElement<T>>>(); var comparerLeaf = new OrderingComparer<LeafElement<T>>(); var comparerCategory = new OrderingComparer<Category<LeafElement<T>>>(); foreach(var entry in list) { var type = entry.type; CategoryInfoAttribute categoryInfo = type.GetCustomAttribute<CategoryInfoAttribute>(); ElementInfoAttribute displayInfo = type.GetCustomAttribute<ElementInfoAttribute>(); int categoryOrder = categoryInfo?.Order ?? int.MaxValue; int inCategoryOrder = displayInfo?.Order ?? int.MaxValue; string categoryName = categoryInfo?.Name // Keep compatibility with previous used attribute for 23.3LTS ?? type.GetCustomAttribute<System.ComponentModel.CategoryAttribute>()?.Category; string name = displayInfo?.Name ?? ObjectNames.NicifyVariableName(type.Name); categoryName ??= name; Category<LeafElement<T>> category; if (!categories.TryGetValue(categoryName, out category)) { category = new Category<LeafElement<T>>(categoryName, categoryOrder); categories[categoryName] = category; result.AddSorted(category, comparerCategory); } category.Add(new LeafElement<T>(entry, name, inCategoryOrder, category), comparerLeaf); } return result; } } }
UnityCsReference/Editor/Mono/Categorize.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Categorize.cs", "repo_id": "UnityCsReference", "token_count": 1913 }
292
// 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.Scripting; namespace UnityEditor.Collaboration { internal class CollabTesting { [Flags] public enum AsyncState { NotWaiting = 0, WaitForJobComplete, WaitForChannelMessageHandled } private static IEnumerator<AsyncState> _enumerator = null; private static Action _runAfter = null; private static AsyncState _nextState = AsyncState.NotWaiting; public static Func<IEnumerable<AsyncState>> Tick { set { _enumerator = value().GetEnumerator(); } } public static Action AfterRun { set { _runAfter = value; } } public static bool IsRunning { get { return _enumerator != null; } } public static void OnJobsCompleted() { OnAsyncSignalReceived(AsyncState.WaitForJobComplete); } [RequiredByNativeCode] public static void OnChannelMessageHandled() { OnAsyncSignalReceived(AsyncState.WaitForChannelMessageHandled); } private static void OnAsyncSignalReceived(AsyncState stateToRemove) { if ((_nextState & stateToRemove) == 0) return; _nextState &= ~stateToRemove; if (_nextState == AsyncState.NotWaiting) Execute(); } public static void Execute() { if (_enumerator == null) return; try { if (!_enumerator.MoveNext()) End(); else _nextState = _enumerator.Current; } catch (Exception) { Debug.LogError("Something Went wrong with the test framework itself"); throw; } } public static void End() { if (_enumerator != null) { _runAfter(); _enumerator = null; } } } }
UnityCsReference/Editor/Mono/Collab/CollabTesting.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Collab/CollabTesting.cs", "repo_id": "UnityCsReference", "token_count": 1143 }
293
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEditorInternal; using UnityEngine.Bindings; namespace UnityEditor { // Exposed as internal, editor-only, because we only need it do make a custom inspector [NativeClass(null)] [ExcludeFromPreset] internal sealed class AudioManager : ProjectSettingsBase { private AudioManager() {} } // Exposed as internal, editor-only, because we only need it do make a custom inspector [NativeClass(null)] internal sealed class Physics2DSettings : ProjectSettingsBase { private Physics2DSettings() {} } // Exposed as internal, editor-only, because we only need it do make a custom inspector [NativeClass(null)] [ExcludeFromPreset] internal sealed class MonoManager : ProjectSettingsBase { private MonoManager() {} } // Exposed as internal, editor-only, because we only need it do make a custom inspector [NativeClass(null)] [ExcludeFromPreset] internal sealed class VFXManager : ProjectSettingsBase { private VFXManager() { } [SettingsProvider] internal static SettingsProvider CreateProjectSettingsProvider() { if (!UnityEngine.VFX.VFXManager.activateVFX) return null; var provider = AssetSettingsProvider.CreateProviderFromAssetPath( "Project/VFX", "ProjectSettings/VFXManager.asset", SettingsProvider.GetSearchKeywordsFromPath("ProjectSettings/VFXManager.asset")); return provider; } } // Exposed as internal, editor-only, because we only need it do make a custom inspector [NativeClass(null)] internal sealed class InputManager : ProjectSettingsBase { private InputManager() {} [SettingsProvider] internal static SettingsProvider CreateProjectSettingsProvider() { // The new input system adds objects to InputManager.asset. This means we can't use AssetSettingsProvider.CreateProviderFromAssetPath // as it will load *all* objects at that path and try to create an editor for it. // NOTE: When the input system package is uninstalled, InputManager.asset will contain serialized MonoBehaviour objects for which // the C# classes are no longer available. They will thus not load correctly and appear as null entries. var obj = AssetDatabase.LoadAssetAtPath<InputManager>("ProjectSettings/InputManager.asset"); if (obj != null && obj.name == "InputManager") { var provider = AssetSettingsProvider.CreateProviderFromObject("Project/Input Manager", obj, SettingsProvider.GetSearchKeywordsFromPath("ProjectSettings/InputManager.asset")); return provider; } return null; } } [CustomEditor(typeof(InputManager))] internal sealed class InputManagerEditor : Editor { public override void OnInspectorGUI() { if (PlayerSettings.GetDisableOldInputManagerSupport()) EditorGUILayout.HelpBox("This is where you can configure the controls to use with the UnityEngine.Input API. But you have switched input handling to \"Input System Package\" in your Player Settings. The Input Manager will not be used.", MessageType.Error); else EditorGUILayout.HelpBox("This is where you can configure the controls to use with the UnityEngine.Input API. Consider using the new Input System Package instead.", MessageType.Info); DrawDefaultInspector(); EditorGUILayout.HelpBox("Physical Keys enables keyboard language layout independent mapping of key codes to physical keys. For example, 'q' will be the key to the right of the tab key no matter which (if any) key on the keyboard currently generates a 'q' character.", MessageType.Info); } } // Exposed as internal, editor-only, because we only need it do make a custom inspector [NativeClass(null)] internal sealed class TimeManager : ProjectSettingsBase { private TimeManager() {} } // Exposed as internal, editor-only, because we only need it do make a custom inspector [NativeClass(null)] internal sealed class MemorySettings : ProjectSettingsBase { private MemorySettings() {} } // Exposed as internal, editor-only, because we only need it do make a custom inspector [NativeClass(null)] internal sealed class UnityConnectSettings : ProjectSettingsBase { private UnityConnectSettings() {} } [NativeConditional("ENABLE_CLUSTERINPUT")] internal sealed class ClusterInputSettings { private ClusterInputSettings() {} } }
UnityCsReference/Editor/Mono/CustomInspectorStubs.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/CustomInspectorStubs.cs", "repo_id": "UnityCsReference", "token_count": 1681 }
294
// 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; using static UnityEditorInternal.InternalEditorUtility; namespace UnityEditor { /// <summary> /// An utility class that provides Dynamic Hints' functionalities /// </summary> internal static class DynamicHintUtility { internal static string Serialize(DynamicHintContent hint) { return $"[Custom Tooltip]<type>{hint.GetType().AssemblyQualifiedName}</type><content>{JsonUtility.ToJson(hint)}</content>"; } internal static DynamicHintContent Deserialize(string hint) { if (!hint.StartsWith("[Custom Tooltip]")) { return null; } int typeStart = hint.IndexOf("<type>", StringComparison.InvariantCulture) + "<type>".Length; int typeLength = hint.IndexOf("</type>", StringComparison.InvariantCulture) - typeStart; if (typeStart < 0 || typeLength < 0) { return null; } var rawType = hint.Substring(typeStart, typeLength); var type = Type.GetType(rawType); int contentStart = hint.IndexOf("<content>", StringComparison.InvariantCulture) + "<content>".Length; int contentLength = hint.IndexOf("</content>", StringComparison.InvariantCulture) - contentStart; if (contentStart < 0 || contentLength < 0) { return null; } var content = hint.Substring(contentStart, contentLength); return JsonUtility.FromJson(content, type) as DynamicHintContent; } /// <summary> /// Loads the StyleSheet that is usually applied to DynamicHints that show how a tool or property works. /// </summary> /// <returns>The StyleSheet</returns> internal static StyleSheet GetDefaultDynamicHintStyleSheet() { return EditorGUIUtility.Load("StyleSheets/DynamicHints/DynamicHintCommon.uss") as StyleSheet; } /// <summary> /// Loads the StyleSheet that is usually applied to DynamicHints that represent data about the components of an instance of an object. /// </summary> /// <returns>The StyleSheet</returns> internal static StyleSheet GetDefaultInstanceDynamicHintStyleSheet() { return EditorGUIUtility.Load("StyleSheets/DynamicHints/InstanceDynamicHintCommon.uss") as StyleSheet; } /// <summary> /// Closes the current DynamicHint being displayed /// </summary> public static void CloseCurrentHint() { TooltipView.Close(); } /// <summary> /// Draws a hint at a specific position of the screen. /// </summary> /// <param name="hint">The content of the hint</param> /// <param name="rect">The rect where the hint will be drawn. The top-left corner of the hint will start at the X coordinate</param> public static void DrawHintAt(DynamicHintContent hint, Rect rect) { TooltipView.s_ForceExtensionOfNextDynamicHint = true; TooltipView.Show(hint.ToTooltipString(), rect); } /// <summary> /// Draws a hint next to an object in the Hierarchy, if it exists and the Hierarchy is visible. /// </summary> /// <param name="hint">The content of the hint</param> /// <param name="objectInHierarchy">The object the hint will be drawn next to</param> public static void DrawHintNextToHierarchyObject(DynamicHintContent hint, GameObject objectInHierarchy) { if (!EditorWindow.HasOpenInstances<SceneHierarchyWindow>()) { return; } EditorWindow.FocusWindowIfItsOpen<SceneHierarchyWindow>(); Rect rectOfObject = GetRectOfObjectInHierarchy(objectInHierarchy, out bool objectWasFound); if (!objectWasFound) { return; } AdaptRectToHierarchy(out Rect rectOfHint, GUIUtility.GUIToScreenPoint(new Vector2(rectOfObject.x, rectOfObject.y)), rectOfObject); DrawHintAt(hint, rectOfHint); } /// <summary> /// Draws a hint next to a visible asset in the Project Window. /// </summary> /// <param name="hint">The content of hint tooltip</param> /// <param name="objectToFind">The object the hint will be drawn next to</param> public static void DrawHintNextToProjectAsset(DynamicHintContent hint, UnityEngine.Object objectToFind) { if (!EditorWindow.HasOpenInstances<ProjectBrowser>()) { return; } EditorWindow.FocusWindowIfItsOpen<ProjectBrowser>(); Rect rectOfObject = GetRectOfObjectInProjectExplorer(objectToFind, out bool objectWasFound); if (!objectWasFound) { return; } AdaptRectToProjectWindow(out Rect rectOfHint, GUIUtility.GUIToScreenPoint(new Vector2(rectOfObject.x, rectOfObject.y))); DrawHintAt(hint, rectOfHint); } /// <summary> /// Draws a hint next to a visible field in the Inspector. /// </summary> /// <param name="hint">The content of the hint</param> /// <param name="fieldPathInClass">The path of the field within the class</param> /// <param name="targetType">The type of the class that contains the field</param> public static void DrawHintNextToInspectorField(DynamicHintContent hint, string fieldPathInClass, Type targetType) { if (!EditorWindow.HasOpenInstances<InspectorWindow>()) { return; } EditorWindow.FocusWindowIfItsOpen<InspectorWindow>(); Rect rectOfObject = GetRectOfFieldInInspector(fieldPathInClass, targetType, out bool objectWasFound); if (!objectWasFound) { return; } AdaptRectToInspector(out Rect rectOfHint, GUIUtility.GUIToScreenPoint(new Vector2(rectOfObject.x, rectOfObject.y))); DrawHintAt(hint, rectOfHint); } /// <summary> /// Draws a hint at a Rect, if the mouse is in it. /// </summary> /// <param name="hint">The hint to draw</param> /// <param name="tooltipRect">The rect where the hint will be drawn</param> internal static void DrawMouseTooltip(DynamicHintContent hint, Rect tooltipRect) { GUIStyle.SetMouseTooltip(hint.ToTooltipString(), tooltipRect); } internal static void DrawHint(Rect hintTriggerRect, Vector2 mousePosition, AssetReference assetReference) { if (!hintTriggerRect.Contains(mousePosition) || !GUIClip.visibleRect.Contains(mousePosition)) { return; } string assetPath = AssetDatabase.GUIDToAssetPath(assetReference.guid); var assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPath); if (assetType == null) //this means the object or its base script has been deleted and is "Missing" { return; } var hintGenerators = TypeCache.GetMethodsWithAttribute<DynamicHintGeneratorAttribute>(); if (assetType.IsSubclassOf(typeof(ScriptableObject))) { DynamicHintContent hint = GetDynamicHintContentOf(hintGenerators, assetType, assetPath); if (hint != null) { DrawMouseTooltip(hint, hintTriggerRect); } return; } if (assetType == typeof(GameObject)) { /* GameObjects can have multiple components with custom tooltips * so for now we'll just display the first one. * If needed, we could: * 1) Implement a "priority system" (like OrderedCallbacks) * 2) Display one big tooltip made up with all elements from custom tooltip */ GameObject assetGameObject = (GetLoadedObjectFromInstanceID(assetReference.instanceID) as GameObject); if (!assetGameObject) { /* this seems to happen non-deterministically at project startup depending of what the user is hovering when the editor opens, * or while the user is scrolling a list of objects and hovers one of them casually, even if the object hovered is actually a * GameObject. * */ return; } foreach (var component in assetGameObject.GetComponents<Component>()) { if (component == null) { continue; } //this means its script has been deleted and is "Missing" DynamicHintContent hint = GetDynamicHintContentOf(hintGenerators, component.GetType(), string.Empty, component); if (hint == null) { continue; } DrawMouseTooltip(hint, hintTriggerRect); return; } } } static DynamicHintContent GetDynamicHintContentOf(TypeCache.MethodCollection hintGenerators, Type targetType, string assetPath = "", Component targetAsComponent = null) { foreach (var hintGenerator in hintGenerators) { foreach (var attribute in hintGenerator.GetCustomAttributes(typeof(DynamicHintGeneratorAttribute), false)) { if (targetType == (attribute as DynamicHintGeneratorAttribute).m_Type) { var target = targetAsComponent ? targetAsComponent : AssetDatabase.LoadMainAssetAtPath(assetPath); if (target) { return hintGenerator.Invoke(null, new[] { (object)target }) as DynamicHintContent; } } } } return null; } static Rect GetRectOfObjectInHierarchy(GameObject objectToFind, out bool found) { return GetRectOfObjectInGUIView(nameof(SceneHierarchyWindow), objectToFind, out found); } static Rect GetRectOfObjectInProjectExplorer(UnityEngine.Object objectToFind, out bool found) { return GetRectOfObjectInGUIView(nameof(ProjectBrowser), objectToFind, out found); } static Rect GetRectOfFieldInInspector(string fieldPathInClass, Type targetType, out bool found) { string viewName = nameof(InspectorWindow); var allViews = new List<GUIView>(); GUIViewDebuggerHelper.GetViews(allViews); var propertyInstructions = new List<IMGUIPropertyInstruction>(32); foreach (var view in allViews) { if (view.GetViewName() != viewName) { continue; } //todo: we should have a way to reference the window without using its name GUIViewDebuggerHelper.DebugWindow(view); view.RepaintImmediately(); GUIViewDebuggerHelper.GetPropertyInstructions(propertyInstructions); var targetTypeName = targetType.AssemblyQualifiedName; foreach (var instruction in propertyInstructions) //todo: we should have a way to reference hierarchy objects without using their names { if (instruction.targetTypeName == targetTypeName && instruction.path == fieldPathInClass) { found = true; return instruction.rect; } } var drawInstructions = new List<IMGUIDrawInstruction>(32); GUIViewDebuggerHelper.GetDrawInstructions(drawInstructions); // Property instruction not found // Let's see if we can find any of the ancestor instructions to allow the user to unfold Rect regionRect = new Rect(); found = FindAncestorPropertyRegion(fieldPathInClass, targetTypeName, drawInstructions, propertyInstructions, ref regionRect); return regionRect; } found = false; return Rect.zero; } /// <summary> /// Gets the field path of the parameter, relative to the class in which it is declared /// </summary> /// <param name="field"></param> /// <returns>The field path of the parameter, relative to the class in which it is declared</returns> public static string GetFieldPathInClass(object field) { if (field == null) { return string.Empty; } Type fieldType = field.GetType(); string typeAsString = fieldType.ToString(); bool isArray = typeAsString.EndsWithIgnoreCaseFast("[]]"); if (isArray) { return fieldType.GetProperties()[0].Name + ".Array.size"; } return fieldType.GetProperties()[0].Name; } /* todo: the following method seems to behave differently for properties representing Arrays, compared to how it behaves for non-array properties. * What happens is that regionRect becomes the "wrong side" of the property in the inspector */ static bool FindAncestorPropertyRegion(string propertyPath, string targetTypeName, List<IMGUIDrawInstruction> drawInstructions, List<IMGUIPropertyInstruction> propertyInstructions, ref Rect regionRect) { while (true) { // Remove last component of property path var lastIndexOfDelimiter = propertyPath.LastIndexOf("."); if (lastIndexOfDelimiter < 1) { // No components left, give up return false; } propertyPath = propertyPath.Substring(0, lastIndexOfDelimiter); foreach (var instruction in propertyInstructions) { if (instruction.targetTypeName != targetTypeName || instruction.path != propertyPath) { continue; } regionRect = instruction.rect; // The property rect itself does not contain the foldout arrow // Expand region to include all draw instructions for this property var unifiedInstructions = new List<IMGUIInstruction>(128); GUIViewDebuggerHelper.GetUnifiedInstructions(unifiedInstructions); var collectDrawInstructions = false; var propertyBeginLevel = 0; foreach (var unifiedInstruction in unifiedInstructions) { if (collectDrawInstructions) { if (unifiedInstruction.level <= propertyBeginLevel) { break; } if (unifiedInstruction.type != InstructionType.kStyleDraw) { continue; } var drawRect = drawInstructions[unifiedInstruction.typeInstructionIndex].rect; if (drawRect.xMin < regionRect.xMin) { regionRect.xMin = drawRect.xMin; } if (drawRect.yMin < regionRect.yMin) { regionRect.yMin = drawRect.yMin; } if (drawRect.xMax > regionRect.xMax) { regionRect.xMax = drawRect.xMax; } if (drawRect.yMax > regionRect.yMax) { regionRect.yMax = drawRect.yMax; } } else { if (unifiedInstruction.type != InstructionType.kPropertyBegin) { continue; } var propertyInstruction = propertyInstructions[unifiedInstruction.typeInstructionIndex]; if (propertyInstruction.targetTypeName == targetTypeName && propertyInstruction.path == propertyPath) { collectDrawInstructions = true; propertyBeginLevel = unifiedInstruction.level; } } } return true; } } } static Rect GetRectOfObjectInGUIView(string viewName, UnityEngine.Object objectToFind, out bool found) { var allViews = new List<GUIView>(); GUIViewDebuggerHelper.GetViews(allViews); var drawInstructions = new List<IMGUIDrawInstruction>(32); foreach (var view in allViews) { if (view.GetViewName() != viewName) { continue; } //todo: we should have a way to reference the window without using its name GUIViewDebuggerHelper.DebugWindow(view); view.RepaintImmediately(); GUIViewDebuggerHelper.GetDrawInstructions(drawInstructions); foreach (var drawInstruction in drawInstructions) //todo: we should have a way to reference hierarchy objects without using their names { //If we can reference the object represented by the draw instruction, we can find it like this /*if (drawInstruction.usedGUIContent.representedObject != null) { if (drawInstruction.usedGUIContent.representedObject == objectToFind) { found = true; return drawInstruction.rect; } }*/ if (drawInstruction.usedGUIContent.text != objectToFind.name) { continue; } found = true; return drawInstruction.rect; } found = false; return Rect.zero; } found = false; return Rect.zero; } static void AdaptRectToHierarchy(out Rect rectOfHint, Vector2 screenPositionOfObject, Rect rectOfObject) { rectOfHint = new Rect(); rectOfHint.x = screenPositionOfObject.x + rectOfObject.width; rectOfHint.y = screenPositionOfObject.y; rectOfHint.width = 0; rectOfHint.height = 0; } static void AdaptRectToInspector(out Rect rectOfHint, Vector2 screenPositionOfObject) { rectOfHint = new Rect(); rectOfHint.x = screenPositionOfObject.x; rectOfHint.y = screenPositionOfObject.y; rectOfHint.width = 0; rectOfHint.height = 0; } static void AdaptRectToProjectWindow(out Rect rectOfHint, Vector2 screenPositionOfObject) { const int offsetForImprovedPositioning = 200; rectOfHint = new Rect(); rectOfHint.x = screenPositionOfObject.x + offsetForImprovedPositioning; rectOfHint.y = screenPositionOfObject.y; rectOfHint.width = 0; rectOfHint.height = 0; } } }
UnityCsReference/Editor/Mono/DynamicHints/DynamicHintUtility.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/DynamicHints/DynamicHintUtility.cs", "repo_id": "UnityCsReference", "token_count": 9045 }
295
// 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 RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute; using UnityEngine; using UnityEngine.Rendering; using UnityEditor.Build; namespace UnityEditor.Rendering { public enum ShaderQuality { Low, Medium, High, } public struct AlbedoSwatchInfo { public string name; public Color color; public float minLuminance; public float maxLuminance; } public enum BatchRendererGroupStrippingMode { KeepIfEntitiesGraphics = 0, StripAll, KeepAll } [StructLayout(LayoutKind.Sequential)] public struct TierSettings { public ShaderQuality standardShaderQuality; public CameraHDRMode hdrMode; public bool reflectionProbeBoxProjection; public bool reflectionProbeBlending; public bool hdr; public bool detailNormalMap; public bool cascadedShadowMaps; public bool prefer32BitShadowMaps; public bool enableLPPV; public bool semitransparentShadows; public RenderingPath renderingPath; public RealtimeGICPUUsage realtimeGICPUUsage; } public sealed partial class EditorGraphicsSettings { // Use the version with NamedBuildTarget passed instead. // [Obsolete("Use SetTierSettings() instead (UnityUpgradable) -> SetTierSettings(*)", false)] public static void SetTierSettings(BuildTargetGroup target, GraphicsTier tier, TierSettings settings) { if (settings.renderingPath == RenderingPath.UsePlayerSettings) throw new ArgumentException("TierSettings.renderingPath must be actual rendering path (not UsePlayerSettings)", "settings"); SetTierSettingsImpl(target, tier, settings); MakeTierSettingsAutomatic(target, tier, false); OnUpdateTierSettings(target, true); } public static void SetTierSettings(NamedBuildTarget target, GraphicsTier tier, TierSettings settings) => SetTierSettings(target.ToBuildTargetGroup(), tier, settings); } // // deprecated // [Obsolete("Use TierSettings instead (UnityUpgradable) -> UnityEditor.Rendering.TierSettings", false)] [StructLayout(LayoutKind.Sequential)] public struct PlatformShaderSettings { [MarshalAs(UnmanagedType.I1)] public bool cascadedShadowMaps; [MarshalAs(UnmanagedType.I1)] public bool reflectionProbeBoxProjection; [MarshalAs(UnmanagedType.I1)] public bool reflectionProbeBlending; public ShaderQuality standardShaderQuality; } public sealed partial class EditorGraphicsSettings { [Obsolete("Use GetTierSettings() instead (UnityUpgradable) -> GetTierSettings(*)", false)] public static PlatformShaderSettings GetShaderSettingsForPlatform(BuildTargetGroup target, ShaderHardwareTier tier) { TierSettings ts = GetTierSettings(target, (GraphicsTier)tier); PlatformShaderSettings pss = new PlatformShaderSettings(); pss.cascadedShadowMaps = ts.cascadedShadowMaps; pss.standardShaderQuality = ts.standardShaderQuality; pss.reflectionProbeBoxProjection = ts.reflectionProbeBoxProjection; pss.reflectionProbeBlending = ts.reflectionProbeBlending; return pss; } [Obsolete("Use SetTierSettings() instead (UnityUpgradable) -> SetTierSettings(*)", false)] public static void SetShaderSettingsForPlatform(BuildTargetGroup target, ShaderHardwareTier tier, PlatformShaderSettings settings) { // we want to preserve TierSettings members that are absent from PlatformShaderSettings TierSettings ts = GetTierSettings(target, (GraphicsTier)tier); ts.standardShaderQuality = settings.standardShaderQuality; ts.cascadedShadowMaps = settings.cascadedShadowMaps; ts.reflectionProbeBoxProjection = settings.reflectionProbeBoxProjection; ts.reflectionProbeBlending = settings.reflectionProbeBlending; SetTierSettings(target, (GraphicsTier)tier, ts); } [Obsolete("Use GraphicsTier instead of ShaderHardwareTier enum", false)] public static TierSettings GetTierSettings(BuildTargetGroup target, ShaderHardwareTier tier) { return GetTierSettings(target, (GraphicsTier)tier); } [Obsolete("Use GraphicsTier instead of ShaderHardwareTier enum", false)] public static void SetTierSettings(BuildTargetGroup target, ShaderHardwareTier tier, TierSettings settings) { SetTierSettings(target, (GraphicsTier)tier, settings); } } }
UnityCsReference/Editor/Mono/EditorGraphicsSettings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/EditorGraphicsSettings.cs", "repo_id": "UnityCsReference", "token_count": 1952 }
296
// 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; // wrapper class to provide similar interface as old settings. old: UnityEditor.EditorUserBuildSettings.selectedEmbeddedLinuxArchitecture ... new: UnityEditor.EditorUserBuildSettings.EmbeddedLinux.architecture namespace UnityEditor { [NativeType(Header = "Editor/Src/EditorUserBuildSettings.h")] [Obsolete("EmbeddedLinuxArchitecture is deprecated. Use EmbeddedArchitecture. (UnityUpgradable) -> EmbeddedArchitecture", false)] public enum EmbeddedLinuxArchitecture { [UnityEngine.InspectorName("Arm64")] Arm64 = EmbeddedArchitecture.Arm64, [System.Obsolete("Arm32 has been removed in 2023.2")] Arm32 = EmbeddedArchitecture.Arm32, [UnityEngine.InspectorName("X64")] X64 = EmbeddedArchitecture.X64, [System.Obsolete("X86 has been removed in 2023.2")] X86 = EmbeddedArchitecture.X86, } public partial class EditorUserBuildSettings { #pragma warning disable 0618 [Obsolete("EditorUserBuildSettings.selectedEmbeddedLinuxArchitecture is deprecated. EmbeddedLinux.Settings.architecture instead. (UnityUpgradable) -> [UnityEditor.EmbeddedLinux.Extensions] UnityEditor.EmbeddedLinux.Settings.architecture", false)] public static extern EmbeddedLinuxArchitecture selectedEmbeddedLinuxArchitecture { [NativeMethod("GetSelectedEmbeddedLinuxArchitecture")] get; [NativeMethod("SetSelectedEmbeddedLinuxArchitecture")] set; } #pragma warning restore 0618 } }
UnityCsReference/Editor/Mono/EditorUserBuildSettingsEmbeddedLinux.deprecated.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/EditorUserBuildSettingsEmbeddedLinux.deprecated.cs", "repo_id": "UnityCsReference", "token_count": 624 }
297
// 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 { // Holds a flag set. Can be used with enum flags. // Has semantic value in separating a single value of an enum versus the flag set [Serializable] internal struct FlagSet<T> where T : IConvertible { private ulong m_Flags; public bool HasFlags(T flags) { return (m_Flags & Convert.ToUInt64(flags)) != 0; } public void SetFlags(T flags, bool value) { if (value) m_Flags |= Convert.ToUInt64(flags); else m_Flags &= ~Convert.ToUInt64(flags); } public FlagSet(T flags) { m_Flags = Convert.ToUInt64(flags); } public static implicit operator FlagSet<T>(T flags) {return new FlagSet<T>(flags); } } }
UnityCsReference/Editor/Mono/FlagSet.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/FlagSet.cs", "repo_id": "UnityCsReference", "token_count": 430 }
298
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using Unity.Jobs; using UnityEngine.Rendering; namespace UnityEngine.LightTransport { namespace PostProcessing { public interface IProbePostProcessor : IDisposable { // Initialize the post processor. bool Initialize(IDeviceContext context); // Convolve spherical radiance to irradiance. bool ConvolveRadianceToIrradiance(IDeviceContext context, BufferSlice<SphericalHarmonicsL2> radianceIn, BufferSlice<SphericalHarmonicsL2> irradianceOut, int probeCount); // Unity expects the following of the irradiance SH coefficients: // 1) For L0 and L1, they must have the SH standard normalization terms folded into them (to avoid doing this multiplication in shader). // 2) They must be divided by Pi for historical reasons. // 3) L1 terms must be in yzx order (rather than standard xyz). // This is flipped back in GetShaderConstantsFromNormalizedSH before passed to shader. bool ConvertToUnityFormat(IDeviceContext context, BufferSlice<SphericalHarmonicsL2> irradianceIn, BufferSlice<SphericalHarmonicsL2> irradianceOut, int probeCount); // Add two sets of SH coefficients together. bool AddSphericalHarmonicsL2(IDeviceContext context, BufferSlice<SphericalHarmonicsL2> A, BufferSlice<SphericalHarmonicsL2> B, BufferSlice<SphericalHarmonicsL2> sum, int probeCount); // Uniformly scale all SH coefficients. bool ScaleSphericalHarmonicsL2(IDeviceContext context, BufferSlice<SphericalHarmonicsL2> shIn, BufferSlice<SphericalHarmonicsL2> shOut, int probeCount, float scale); // Spherical Harmonics windowing can be used to reduce ringing artifacts. bool WindowSphericalHarmonicsL2(IDeviceContext context, BufferSlice<SphericalHarmonicsL2> shIn, BufferSlice<SphericalHarmonicsL2> shOut, int probeCount); // Spherical Harmonics de-ringing can be used to reduce ringing artifacts. bool DeringSphericalHarmonicsL2(IDeviceContext context, BufferSlice<SphericalHarmonicsL2> shIn, BufferSlice<SphericalHarmonicsL2> shOut, int probeCount); } struct SH { // Notation: // [L00: DC] // [L1-1: x] [L10: y] [L11: z] // [L2-2: xy] [L2-1: yz] [L20: zz] [L21: xz] [L22: xx - yy] // Underscores are meant as a minus sign in the variable names below. public const int L00 = 0; public const int L1_1 = 1; public const int L10 = 2; public const int L11 = 3; public const int L2_2 = 4; public const int L2_1 = 5; public const int L20 = 6; public const int L21 = 7; public const int L22 = 8; // Number of coefficients in the SH L2 basis. public const int L2_CoeffCount = 9; } struct SphericalRadianceToIrradiance { // aHat is from https://cseweb.ucsd.edu/~ravir/papers/envmap/envmap.pdf and is used to convert spherical radiance to irradiance. public const float aHat0 = 3.1415926535897932384626433832795028841971693993751058209749445923f; // π public const float aHat1 = 2.0943951023931954923084289221863352561314462662500705473166297282f; // 2π/3 public const float aHat2 = 0.785398f; // π/4 (see equation 8). } //[BurstCompile] // TODO: Use burst once it is supported in the editor or we move to a package. struct ConvolveJob : IJobParallelFor { [ReadOnly] public NativeSlice<SphericalHarmonicsL2> Radiances; [WriteOnly] public NativeSlice<SphericalHarmonicsL2> Irradiances; public void Execute(int probeIdx) { SphericalHarmonicsL2 radiance = Radiances[probeIdx]; var irradiance = new SphericalHarmonicsL2(); for (int rgb = 0; rgb < 3; rgb++) { irradiance[rgb, SH.L00] = radiance[rgb, SH.L00] * SphericalRadianceToIrradiance.aHat0; irradiance[rgb, SH.L1_1] = radiance[rgb, SH.L1_1] * SphericalRadianceToIrradiance.aHat1; irradiance[rgb, SH.L10] = radiance[rgb, SH.L10] * SphericalRadianceToIrradiance.aHat1; irradiance[rgb, SH.L11] = radiance[rgb, SH.L11] * SphericalRadianceToIrradiance.aHat1; irradiance[rgb, SH.L2_2] = radiance[rgb, SH.L2_2] * SphericalRadianceToIrradiance.aHat2; irradiance[rgb, SH.L2_1] = radiance[rgb, SH.L2_1] * SphericalRadianceToIrradiance.aHat2; irradiance[rgb, SH.L20] = radiance[rgb, SH.L20] * SphericalRadianceToIrradiance.aHat2; irradiance[rgb, SH.L21] = radiance[rgb, SH.L21] * SphericalRadianceToIrradiance.aHat2; irradiance[rgb, SH.L22] = radiance[rgb, SH.L22] * SphericalRadianceToIrradiance.aHat2; }; Irradiances[probeIdx] = irradiance; } } //[BurstCompile] // TODO: Use burst once it is supported in the editor or we move to a package. struct UnityfyJob : IJobParallelFor { [ReadOnly] public NativeSlice<SphericalHarmonicsL2> IrradianceIn; [WriteOnly] public NativeSlice<SphericalHarmonicsL2> IrradianceOut; public void Execute(int probeIdx) { float shY0Normalization = Mathf.Sqrt(1.0f / Mathf.PI) / 2.0f; float shY1Normalization = Mathf.Sqrt(3.0f / Mathf.PI) / 2.0f; float shY2_2Normalization = Mathf.Sqrt(15.0f / Mathf.PI) / 2.0f; float shY2_1Normalization = shY2_2Normalization; float shY20Normalization = Mathf.Sqrt(5.0f / Mathf.PI) / 4.0f; float shY21Normalization = shY2_2Normalization; float shY22Normalization = Mathf.Sqrt(15.0f / Mathf.PI) / 4.0f; SphericalHarmonicsL2 irradiance = IrradianceIn[probeIdx]; var output = new SphericalHarmonicsL2(); for (int rgb = 0; rgb < 3; ++rgb) { // L0 output[rgb, SH.L00] = irradiance[rgb, SH.L00]; output[rgb, SH.L00] *= shY0Normalization; // 1) output[rgb, SH.L00] /= Mathf.PI; // 2) // L1 output[rgb, SH.L1_1] = irradiance[rgb, SH.L10]; // 3) output[rgb, SH.L1_1] *= shY1Normalization; // 1) output[rgb, SH.L1_1] /= Mathf.PI; // 3 ) output[rgb, SH.L10] = irradiance[rgb, SH.L11]; // 3) output[rgb, SH.L10] *= shY1Normalization; // 1) output[rgb, SH.L10] /= Mathf.PI; // 2) output[rgb, SH.L11] = irradiance[rgb, SH.L1_1]; // 3) output[rgb, SH.L11] *= shY1Normalization; // 1) output[rgb, SH.L11] /= Mathf.PI; // 2) // L2 output[rgb, SH.L2_2] = irradiance[rgb, SH.L2_2]; output[rgb, SH.L2_2] *= shY2_2Normalization; // 1) output[rgb, SH.L2_2] /= Mathf.PI; // 2) output[rgb, SH.L2_1] = irradiance[rgb, SH.L2_1]; output[rgb, SH.L2_1] *= shY2_1Normalization; // 1) output[rgb, SH.L2_1] /= Mathf.PI; // 2) output[rgb, SH.L20] = irradiance[rgb, SH.L20]; output[rgb, SH.L20] *= shY20Normalization; // 1) output[rgb, SH.L20] /= Mathf.PI; // 2) output[rgb, SH.L21] = irradiance[rgb, SH.L21]; output[rgb, SH.L21] *= shY21Normalization; // 1) output[rgb, SH.L21] /= Mathf.PI; // 2) output[rgb, SH.L22] = irradiance[rgb, SH.L22]; output[rgb, SH.L22] *= shY22Normalization; // 1) output[rgb, SH.L22] /= Mathf.PI; // 2) } IrradianceOut[probeIdx] = output; } } //[BurstCompile] // TODO: Use burst once it is supported in the editor or we move to a package. struct AddSHJob : IJobParallelFor { [ReadOnly] public NativeSlice<SphericalHarmonicsL2> A; [ReadOnly] public NativeSlice<SphericalHarmonicsL2> B; [WriteOnly] public NativeSlice<SphericalHarmonicsL2> Sum; public void Execute(int probeIdx) { Sum[probeIdx] = A[probeIdx] + B[probeIdx]; } } //[BurstCompile] // TODO: Use burst once it is supported in the editor or we move to a package. struct ScaleSHJob : IJobParallelFor { [ReadOnly] public NativeSlice<SphericalHarmonicsL2> Input; [ReadOnly] public float Scale; [WriteOnly] public NativeSlice<SphericalHarmonicsL2> Scaled; public void Execute(int probeIdx) { Scaled[probeIdx] = Input[probeIdx] * Scale; } } //[BurstCompile] // TODO: Use burst once it is supported in the editor or we move to a package. struct WindowSHJob : IJobParallelFor { [ReadOnly] public NativeSlice<SphericalHarmonicsL2> Input; [WriteOnly] public NativeSlice<SphericalHarmonicsL2> Windowed; public void Execute(int probeIdx) { // Windowing constants from WindowDirectSH in SHDering.cpp float[] extraWindow = new float[] { 1.0f, 0.922066f, 0.731864f }; // Apply windowing: Essentially SHConv3 times the window constants SphericalHarmonicsL2 sh = Input[probeIdx]; for (int coefficientIndex = 0; coefficientIndex < SH.L2_CoeffCount; ++coefficientIndex) { float window; if (coefficientIndex == 0) window = extraWindow[0]; else if (coefficientIndex < 4) window = extraWindow[1]; else window = extraWindow[2]; sh[0, coefficientIndex] *= window; sh[1, coefficientIndex] *= window; sh[2, coefficientIndex] *= window; } Windowed[probeIdx] = sh; } } //[BurstCompile] // TODO: Use burst once it is supported in the editor or we move to a package. struct DeringSHJob : IJobParallelFor { [ReadOnly] public NativeSlice<SphericalHarmonicsL2> Input; [WriteOnly] public NativeSlice<SphericalHarmonicsL2> Output; public void Execute(int probeIdx) { SphericalHarmonicsL2 sh = Input[probeIdx]; SphericalHarmonicsL2 output = new SphericalHarmonicsL2(); unsafe { var shInputPtr = (SphericalHarmonicsL2*)UnsafeUtility.AddressOf(ref sh); var shOutputPtr = (SphericalHarmonicsL2*)UnsafeUtility.AddressOf(ref output); bool result = WintermuteContext.DeringSphericalHarmonicsL2Internal(shInputPtr, shOutputPtr, 1); Debug.Assert(result); } Output[probeIdx] = output; } } public class ReferenceProbePostProcessor : IProbePostProcessor { public bool Initialize(IDeviceContext context) { return true; } public bool ConvolveRadianceToIrradiance(IDeviceContext context, BufferSlice<SphericalHarmonicsL2> radianceIn, BufferSlice<SphericalHarmonicsL2> irradianceOut, int probeCount) { Debug.Assert(context is ReferenceContext, "Expected ReferenceContext but got something else."); if (context is not ReferenceContext refContext) return false; NativeArray<byte> radianceNativeArray = refContext.GetNativeArray(radianceIn.Id); NativeArray<byte> irradianceNativeArray = refContext.GetNativeArray(irradianceOut.Id); NativeArray<SphericalHarmonicsL2> Radiances = radianceNativeArray.Reinterpret<SphericalHarmonicsL2>(1); NativeArray<SphericalHarmonicsL2> Irradiances = irradianceNativeArray.Reinterpret<SphericalHarmonicsL2>(1); for (int probeIdx = 0; probeIdx < probeCount; ++probeIdx) { SphericalHarmonicsL2 radiance = Radiances[probeIdx]; var irradiance = new SphericalHarmonicsL2(); for (int rgb = 0; rgb < 3; rgb++) { irradiance[rgb, SH.L00] = radiance[rgb, SH.L00] * SphericalRadianceToIrradiance.aHat0; irradiance[rgb, SH.L1_1] = radiance[rgb, SH.L1_1] * SphericalRadianceToIrradiance.aHat1; irradiance[rgb, SH.L10] = radiance[rgb, SH.L10] * SphericalRadianceToIrradiance.aHat1; irradiance[rgb, SH.L11] = radiance[rgb, SH.L11] * SphericalRadianceToIrradiance.aHat1; irradiance[rgb, SH.L2_2] = radiance[rgb, SH.L2_2] * SphericalRadianceToIrradiance.aHat2; irradiance[rgb, SH.L2_1] = radiance[rgb, SH.L2_1] * SphericalRadianceToIrradiance.aHat2; irradiance[rgb, SH.L20] = radiance[rgb, SH.L20] * SphericalRadianceToIrradiance.aHat2; irradiance[rgb, SH.L21] = radiance[rgb, SH.L21] * SphericalRadianceToIrradiance.aHat2; irradiance[rgb, SH.L22] = radiance[rgb, SH.L22] * SphericalRadianceToIrradiance.aHat2; }; Irradiances[probeIdx] = irradiance; } return true; } public bool ConvertToUnityFormat(IDeviceContext context, BufferSlice<SphericalHarmonicsL2> irradianceIn, BufferSlice<SphericalHarmonicsL2> irradianceOut, int probeCount) { Debug.Assert(context is ReferenceContext, "Expected ReferenceContext but got something else."); if (context is not ReferenceContext refContext) return false; float shY0Normalization = Mathf.Sqrt(1.0f / Mathf.PI) / 2.0f; float shY1Normalization = Mathf.Sqrt(3.0f / Mathf.PI) / 2.0f; float shY2_2Normalization = Mathf.Sqrt(15.0f / Mathf.PI) / 2.0f; float shY2_1Normalization = shY2_2Normalization; float shY20Normalization = Mathf.Sqrt(5.0f / Mathf.PI) / 4.0f; float shY21Normalization = shY2_2Normalization; float shY22Normalization = Mathf.Sqrt(15.0f / Mathf.PI) / 4.0f; NativeArray<byte> irradianceInNativeArray = refContext.GetNativeArray(irradianceIn.Id); NativeArray<byte> irradianceOutNativeArray = refContext.GetNativeArray(irradianceOut.Id); NativeArray<SphericalHarmonicsL2> IrradianceIn = irradianceInNativeArray.Reinterpret<SphericalHarmonicsL2>(1); NativeArray<SphericalHarmonicsL2> IrradianceOut = irradianceOutNativeArray.Reinterpret<SphericalHarmonicsL2>(1); for (int probeIdx = 0; probeIdx < probeCount; ++probeIdx) { SphericalHarmonicsL2 irradiance = IrradianceIn[probeIdx]; var output = new SphericalHarmonicsL2(); for (int rgb = 0; rgb < 3; ++rgb) { // L0 output[rgb, SH.L00] = irradiance[rgb, SH.L00]; output[rgb, SH.L00] *= shY0Normalization; // 1) output[rgb, SH.L00] /= Mathf.PI; // 2) // L1 output[rgb, SH.L1_1] = irradiance[rgb, SH.L10]; // 3) output[rgb, SH.L1_1] *= shY1Normalization; // 1) output[rgb, SH.L1_1] /= Mathf.PI; // 3 ) output[rgb, SH.L10] = irradiance[rgb, SH.L11]; // 3) output[rgb, SH.L10] *= shY1Normalization; // 1) output[rgb, SH.L10] /= Mathf.PI; // 2) output[rgb, SH.L11] = irradiance[rgb, SH.L1_1]; // 3) output[rgb, SH.L11] *= shY1Normalization; // 1) output[rgb, SH.L11] /= Mathf.PI; // 2) // L2 output[rgb, SH.L2_2] = irradiance[rgb, SH.L2_2]; output[rgb, SH.L2_2] *= shY2_2Normalization; // 1) output[rgb, SH.L2_2] /= Mathf.PI; // 2) output[rgb, SH.L2_1] = irradiance[rgb, SH.L2_1]; output[rgb, SH.L2_1] *= shY2_1Normalization; // 1) output[rgb, SH.L2_1] /= Mathf.PI; // 2) output[rgb, SH.L20] = irradiance[rgb, SH.L20]; output[rgb, SH.L20] *= shY20Normalization; // 1) output[rgb, SH.L20] /= Mathf.PI; // 2) output[rgb, SH.L21] = irradiance[rgb, SH.L21]; output[rgb, SH.L21] *= shY21Normalization; // 1) output[rgb, SH.L21] /= Mathf.PI; // 2) output[rgb, SH.L22] = irradiance[rgb, SH.L22]; output[rgb, SH.L22] *= shY22Normalization; // 1) output[rgb, SH.L22] /= Mathf.PI; // 2) } IrradianceOut[probeIdx] = output; } return true; } public bool AddSphericalHarmonicsL2(IDeviceContext context, BufferSlice<SphericalHarmonicsL2> a, BufferSlice<SphericalHarmonicsL2> b, BufferSlice<SphericalHarmonicsL2> sum, int probeCount) { Debug.Assert(context is ReferenceContext, "Expected ReferenceContext but got something else."); if (context is not ReferenceContext refContext) return false; NativeArray<byte> A = refContext.GetNativeArray(a.Id); NativeArray<byte> B = refContext.GetNativeArray(b.Id); NativeArray<byte> Sum = refContext.GetNativeArray(sum.Id); NativeArray<SphericalHarmonicsL2> shA = A.Reinterpret<SphericalHarmonicsL2>(1); NativeArray<SphericalHarmonicsL2> shB = B.Reinterpret<SphericalHarmonicsL2>(1); NativeArray<SphericalHarmonicsL2> shSum = Sum.Reinterpret<SphericalHarmonicsL2>(1); for (int probeIdx = 0; probeIdx < probeCount; ++probeIdx) { shSum[probeIdx] = shA[probeIdx] + shB[probeIdx]; } return true; } public bool ScaleSphericalHarmonicsL2(IDeviceContext context, BufferSlice<SphericalHarmonicsL2> shIn, BufferSlice<SphericalHarmonicsL2> shOut, int probeCount, float scale) { Debug.Assert(context is ReferenceContext, "Expected ReferenceContext but got something else."); if (context is not ReferenceContext refContext) return false; NativeArray<byte> sh = refContext.GetNativeArray(shIn.Id); NativeArray<byte> output = refContext.GetNativeArray(shOut.Id); NativeArray<SphericalHarmonicsL2> shInput = sh.Reinterpret<SphericalHarmonicsL2>(1); NativeArray<SphericalHarmonicsL2> shOutput = output.Reinterpret<SphericalHarmonicsL2>(1); for (int probeIdx = 0; probeIdx < probeCount; ++probeIdx) { shOutput[probeIdx] = shInput[probeIdx] * scale; } return true; } public bool WindowSphericalHarmonicsL2(IDeviceContext context, BufferSlice<SphericalHarmonicsL2> shIn, BufferSlice<SphericalHarmonicsL2> shOut, int probeCount) { Debug.Assert(context is ReferenceContext, "Expected ReferenceContext but got something else."); if (context is not ReferenceContext refContext) return false; NativeArray<byte> A = refContext.GetNativeArray(shIn.Id); NativeArray<byte> B = refContext.GetNativeArray(shOut.Id); NativeArray<SphericalHarmonicsL2> shA = A.Reinterpret<SphericalHarmonicsL2>(1); NativeArray<SphericalHarmonicsL2> shB = B.Reinterpret<SphericalHarmonicsL2>(1); // Windowing constants from WindowDirectSH in SHDering.cpp float[] extraWindow = new float[] { 1.0f, 0.922066f, 0.731864f }; // Apply windowing function to SH coefficients. for (int probeIdx = 0; probeIdx < probeCount; ++probeIdx) { // Apply windowing: Essentially SHConv3 times the window constants SphericalHarmonicsL2 sh = shA[probeIdx]; for (int coefficientIndex = 0; coefficientIndex < SH.L2_CoeffCount; ++coefficientIndex) { float window; if (coefficientIndex == 0) window = extraWindow[0]; else if (coefficientIndex < 4) window = extraWindow[1]; else window = extraWindow[2]; sh[0, coefficientIndex] *= window; sh[1, coefficientIndex] *= window; sh[2, coefficientIndex] *= window; } shB[probeIdx] = sh; } return true; } public bool DeringSphericalHarmonicsL2(IDeviceContext context, BufferSlice<SphericalHarmonicsL2> shIn, BufferSlice<SphericalHarmonicsL2> shOut, int probeCount) { Debug.Assert(context is ReferenceContext, "Expected ReferenceContext but got something else."); if (context is not ReferenceContext refContext) return false; NativeArray<byte> inputSh = refContext.GetNativeArray(shIn.Id); NativeArray<byte> outputSh = refContext.GetNativeArray(shOut.Id); NativeArray<SphericalHarmonicsL2> shInput = inputSh.Reinterpret<SphericalHarmonicsL2>(1); NativeArray<SphericalHarmonicsL2> shOutput = outputSh.Reinterpret<SphericalHarmonicsL2>(1); unsafe { for (int probeIdx = 0; probeIdx < probeCount; ++probeIdx) { SphericalHarmonicsL2 sh = shInput[probeIdx]; SphericalHarmonicsL2 output = new SphericalHarmonicsL2(); var shInputPtr = (SphericalHarmonicsL2*)UnsafeUtility.AddressOf(ref sh); var shOutputPtr = (SphericalHarmonicsL2*)UnsafeUtility.AddressOf(ref output); bool result = WintermuteContext.DeringSphericalHarmonicsL2Internal(shInputPtr, shOutputPtr, 1); Debug.Assert(result); shOutput[probeIdx] = output; } } return true; } public void Dispose() { } } internal class WintermuteProbePostProcessor : IProbePostProcessor { public bool Initialize(IDeviceContext context) { return true; } public bool ConvolveRadianceToIrradiance(IDeviceContext context, BufferSlice<SphericalHarmonicsL2> radianceIn, BufferSlice<SphericalHarmonicsL2> irradianceOut, int probeCount) { Debug.Assert(context is WintermuteContext, "Expected WintermuteContext but got something else."); if (context is not WintermuteContext wmContext) return false; NativeArray<byte> radianceInNativeArray = wmContext.GetNativeArray(radianceIn.Id); NativeArray<byte> irradianceOutNativeArray = wmContext.GetNativeArray(irradianceOut.Id); var job = new ConvolveJob { Radiances = radianceInNativeArray.Reinterpret<SphericalHarmonicsL2>(1), Irradiances = irradianceOutNativeArray.Reinterpret<SphericalHarmonicsL2>(1) }; JobHandle jobHandle = job.Schedule(probeCount, 64); jobHandle.Complete(); return true; } public bool ConvertToUnityFormat(IDeviceContext context, BufferSlice<SphericalHarmonicsL2> irradianceIn, BufferSlice<SphericalHarmonicsL2> irradianceOut, int probeCount) { Debug.Assert(context is WintermuteContext, "Expected WintermuteContext but got something else."); if (context is not WintermuteContext wmContext) return false; NativeArray<byte> irradianceInNativeArray = wmContext.GetNativeArray(irradianceIn.Id); NativeArray<byte> irradianceOutNativeArray = wmContext.GetNativeArray(irradianceOut.Id); var job = new UnityfyJob { IrradianceIn = irradianceInNativeArray.Reinterpret<SphericalHarmonicsL2>(1), IrradianceOut = irradianceOutNativeArray.Reinterpret<SphericalHarmonicsL2>(1) }; JobHandle jobHandle = job.Schedule(probeCount, 64); jobHandle.Complete(); return true; } public bool AddSphericalHarmonicsL2(IDeviceContext context, BufferSlice<SphericalHarmonicsL2> a, BufferSlice<SphericalHarmonicsL2> b, BufferSlice<SphericalHarmonicsL2> sum, int probeCount) { Debug.Assert(context is WintermuteContext, "Expected WintermuteContext but got something else."); if (context is not WintermuteContext wmContext) return false; NativeArray<byte> A = wmContext.GetNativeArray(a.Id); NativeArray<byte> B = wmContext.GetNativeArray(b.Id); NativeArray<byte> Sum = wmContext.GetNativeArray(sum.Id); var job = new AddSHJob { A = A.Reinterpret<SphericalHarmonicsL2>(1), B = B.Reinterpret<SphericalHarmonicsL2>(1), Sum = Sum.Reinterpret<SphericalHarmonicsL2>(1) }; JobHandle jobHandle = job.Schedule(probeCount, 64); jobHandle.Complete(); return true; } public bool ScaleSphericalHarmonicsL2(IDeviceContext context, BufferSlice<SphericalHarmonicsL2> shIn, BufferSlice<SphericalHarmonicsL2> shOut, int probeCount, float scale) { Debug.Assert(context is WintermuteContext, "Expected WintermuteContext but got something else."); if (context is not WintermuteContext wmContext) return false; NativeArray<byte> input = wmContext.GetNativeArray(shIn.Id); NativeArray<byte> output = wmContext.GetNativeArray(shOut.Id); var job = new ScaleSHJob { Input = input.Reinterpret<SphericalHarmonicsL2>(1), Scale = scale, Scaled = output.Reinterpret<SphericalHarmonicsL2>(1) }; JobHandle jobHandle = job.Schedule(probeCount, 64); jobHandle.Complete(); return true; } public bool WindowSphericalHarmonicsL2(IDeviceContext context, BufferSlice<SphericalHarmonicsL2> shIn, BufferSlice<SphericalHarmonicsL2> shOut, int probeCount) { Debug.Assert(context is WintermuteContext, "Expected WintermuteContext but got something else."); if (context is not WintermuteContext wmContext) return false; NativeArray<byte> A = wmContext.GetNativeArray(shIn.Id); NativeArray<byte> B = wmContext.GetNativeArray(shOut.Id); var job = new WindowSHJob { Input = A.Reinterpret<SphericalHarmonicsL2>(1), Windowed = B.Reinterpret<SphericalHarmonicsL2>(1) }; JobHandle jobHandle = job.Schedule(probeCount, 64); jobHandle.Complete(); return true; } public bool DeringSphericalHarmonicsL2(IDeviceContext context, BufferSlice<SphericalHarmonicsL2> shIn, BufferSlice<SphericalHarmonicsL2> shOut, int probeCount) { Debug.Assert(context is WintermuteContext, "Expected WintermuteContext but got something else."); if (context is not WintermuteContext wmContext) return false; NativeArray<byte> A = wmContext.GetNativeArray(shIn.Id); NativeArray<byte> B = wmContext.GetNativeArray(shOut.Id); var job = new DeringSHJob { Input = A.Reinterpret<SphericalHarmonicsL2>(1), Output = B.Reinterpret<SphericalHarmonicsL2>(1) }; JobHandle jobHandle = job.Schedule(probeCount, 64); jobHandle.Complete(); return true; } public void Dispose() { } } public class RadeonRaysProbePostProcessor : IProbePostProcessor { private const int sizeofSphericalHarmonicsL2 = 27 * sizeof(float); public bool Initialize(IDeviceContext context) { Debug.Assert(context is RadeonRaysContext, "Expected RadeonRaysContext but got something else."); var rrContext = context as RadeonRaysContext; return RadeonRaysContext.InitializePostProcessingInternal(rrContext); } public bool ConvolveRadianceToIrradiance(IDeviceContext context, BufferSlice<SphericalHarmonicsL2> radianceIn, BufferSlice<SphericalHarmonicsL2> irradianceOut, int probeCount) { Debug.Assert(context is RadeonRaysContext, "Expected RadeonRaysContext but got something else."); if (context is not RadeonRaysContext rrContext) return false; return RadeonRaysContext.ConvolveRadianceToIrradianceInternal(rrContext, radianceIn.Id, irradianceOut.Id, probeCount); } public bool ConvertToUnityFormat(IDeviceContext context, BufferSlice<SphericalHarmonicsL2> irradianceIn, BufferSlice<SphericalHarmonicsL2> irradianceOut, int probeCount) { Debug.Assert(context is RadeonRaysContext, "Expected RadeonRaysContext but got something else."); if (context is not RadeonRaysContext rrContext) return false; return RadeonRaysContext.ConvertToUnityFormatInternal(rrContext, irradianceIn.Id, irradianceOut.Id, probeCount); } public bool AddSphericalHarmonicsL2(IDeviceContext context, BufferSlice<SphericalHarmonicsL2> a, BufferSlice<SphericalHarmonicsL2> b, BufferSlice<SphericalHarmonicsL2> sum, int probeCount) { Debug.Assert(context is RadeonRaysContext, "Expected RadeonRaysContext but got something else."); if (context is not RadeonRaysContext rrContext) return false; return RadeonRaysContext.AddSphericalHarmonicsL2Internal(rrContext, a.Id, b.Id, sum.Id, probeCount); } public bool ScaleSphericalHarmonicsL2(IDeviceContext context, BufferSlice<SphericalHarmonicsL2> shIn, BufferSlice<SphericalHarmonicsL2> shOut, int probeCount, float scale) { Debug.Assert(context is RadeonRaysContext, "Expected RadeonRaysContext but got something else."); if (context is not RadeonRaysContext rrContext) return false; return RadeonRaysContext.ScaleSphericalHarmonicsL2Internal(rrContext, shIn.Id, shOut.Id, probeCount, scale); } public bool WindowSphericalHarmonicsL2(IDeviceContext context, BufferSlice<SphericalHarmonicsL2> shIn, BufferSlice<SphericalHarmonicsL2> shOut, int probeCount) { Debug.Assert(context is RadeonRaysContext, "Expected RadeonRaysContext but got something else."); if (context is not RadeonRaysContext rrContext) return false; return RadeonRaysContext.WindowSphericalHarmonicsL2Internal(rrContext, shIn.Id, shOut.Id, probeCount); } public bool DeringSphericalHarmonicsL2(IDeviceContext context, BufferSlice<SphericalHarmonicsL2> shIn, BufferSlice<SphericalHarmonicsL2> shOut, int probeCount) { // Read back from GPU memory into CPU memory. using var shInputBuffer = new NativeArray<SphericalHarmonicsL2>(probeCount, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); using var shOutputBuffer = new NativeArray<SphericalHarmonicsL2>(probeCount, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); EventID eventId = context.ReadBuffer(shIn, shInputBuffer); bool flushResult = context.Flush(); Debug.Assert(flushResult, "Failed to flush context."); bool waitResult = context.Wait(eventId); Debug.Assert(waitResult, "Failed to read SH from context."); // Currently windowing is done on CPU since the algorithm is not GPU friendly. // Since we aren't attempting to port this to GPU, we are using the jobified CPU version. var job = new DeringSHJob { Input = shInputBuffer, Output = shOutputBuffer }; JobHandle jobHandle = job.Schedule(probeCount, 64); jobHandle.Complete(); // Write back to GPU. eventId = context.WriteBuffer(shOut, shOutputBuffer); waitResult = context.Wait(eventId); Debug.Assert(waitResult, "Failed to write SH to context."); return true; } public void Dispose() { } } } }
UnityCsReference/Editor/Mono/GI/PostProcessing.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GI/PostProcessing.bindings.cs", "repo_id": "UnityCsReference", "token_count": 17643 }
299
// 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 { public sealed partial class EditorGUI { internal static bool ButtonWithRotatedIcon(Rect rect, GUIContent guiContent, float iconAngle, bool mouseDownButton, GUIStyle style) { // Button with text and background (no icon - it's rendered separately below) bool buttonPressed; if (mouseDownButton) buttonPressed = DropdownButton(rect, GUIContent.Temp(guiContent.text, guiContent.tooltip), FocusType.Passive, style); else buttonPressed = GUI.Button(rect, GUIContent.Temp(guiContent.text, guiContent.tooltip), style); // Icon (rendered left of text) if (Event.current.type == EventType.Repaint && guiContent.image != null) { Vector2 iconSize = EditorGUIUtility.GetIconSize(); if (iconSize == Vector2.zero) { iconSize.x = iconSize.y = rect.height - style.padding.vertical; } const float spaceBetweenIconAndText = 3f; const float spaceBetweenIconAndTop = 3f; Rect iconRect = new Rect(rect.x + style.padding.left - spaceBetweenIconAndText - iconSize.x, rect.y + style.padding.top + spaceBetweenIconAndTop, iconSize.x, iconSize.y); if (iconAngle == 0f) { GUI.DrawTexture(iconRect, guiContent.image); } else { Matrix4x4 prevMatrix = GUI.matrix; GUIUtility.RotateAroundPivot(iconAngle, iconRect.center); GUI.DrawTexture(iconRect, guiContent.image); GUI.matrix = prevMatrix; } } return buttonPressed; } } // Ensure to call Clear() before setting a instance to null to prevent mem leaking // due to CallbackController using a delegate for update calls (if not de-registering this // delegate, it will keep the instance from being gc'ed) internal class ButtonWithAnimatedIconRotation { readonly CallbackController m_CallbackController; // used for continuous repaints readonly Func<float> m_AngleCallback; readonly bool m_MouseDownButton; public ButtonWithAnimatedIconRotation(Func<float> angleCallback, Action repaintCallback, float repaintsPerSecond, bool mouseDownButton) { m_CallbackController = new CallbackController(repaintCallback, repaintsPerSecond); m_AngleCallback = angleCallback; m_MouseDownButton = mouseDownButton; } public bool OnGUI(Rect rect, GUIContent guiContent, bool animate, GUIStyle style) { if (animate && !m_CallbackController.active) m_CallbackController.Start(); if (!animate && m_CallbackController.active) m_CallbackController.Stop(); float iconAngle = animate ? m_AngleCallback() : 0f; return EditorGUI.ButtonWithRotatedIcon(rect, guiContent, iconAngle, m_MouseDownButton, style); } public void Clear() { m_CallbackController.Stop(); } } }
UnityCsReference/Editor/Mono/GUI/ButtonWithAnimatedIcon.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUI/ButtonWithAnimatedIcon.cs", "repo_id": "UnityCsReference", "token_count": 1482 }
300
// 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 System.Collections; using UnityEditor; using UnityEditorInternal; namespace UnityEditor { internal class EditorUpdateWindow : EditorWindow { [RequiredByNativeCode] static void ShowEditorErrorWindow(string errorString) { LoadResources(); EditorUpdateWindow w = ShowWindow(); w.s_ErrorString = errorString; w.s_HasConnectionError = true; w.s_HasUpdate = false; } [RequiredByNativeCode] static void ShowEditorUpdateWindow(string latestVersionString, string latestVersionMessage, string updateURL) { LoadResources(); EditorUpdateWindow w = ShowWindow(); w.s_LatestVersionString = latestVersionString; w.s_LatestVersionMessage = latestVersionMessage; w.s_UpdateURL = updateURL; w.s_HasConnectionError = false; w.s_HasUpdate = updateURL.Length > 0; } private static EditorUpdateWindow ShowWindow() { return EditorWindow.GetWindowWithRect(typeof(EditorUpdateWindow), new Rect(100, 100, 570, 400), true, s_Title.text) as EditorUpdateWindow; } private static GUIContent s_UnityLogo; private static GUIContent s_Title; private static GUIContent s_TextHasUpdate, s_TextUpToDate; private static GUIContent s_CheckForNewUpdatesText; [SerializeField] private string s_ErrorString; [SerializeField] private string s_LatestVersionString; [SerializeField] private string s_LatestVersionMessage; [SerializeField] private string s_UpdateURL; [SerializeField] private bool s_HasUpdate; [SerializeField] private bool s_HasConnectionError; private static bool s_ShowAtStartup; private Vector2 m_ScrollPos; private static void LoadResources() { if (s_UnityLogo != null) return; s_ShowAtStartup = EditorPrefs.GetBool("EditorUpdateShowAtStartup", true); s_Title = EditorGUIUtility.TrTextContent("Unity Editor Update Check"); s_UnityLogo = EditorGUIUtility.IconContent("UnityLogo"); s_TextHasUpdate = EditorGUIUtility.TrTextContent("There is a new version of the Unity Editor available for download.\n\nCurrently installed version is {0}\nNew version is {1}"); s_TextUpToDate = EditorGUIUtility.TrTextContent("The Unity Editor is up to date. Currently installed version is {0}"); s_CheckForNewUpdatesText = EditorGUIUtility.TrTextContent("Check for Updates"); } public void OnGUI() { LoadResources(); GUILayout.BeginVertical(); GUILayout.Space(10); GUI.Box(new Rect(13, 8, s_UnityLogo.image.width, s_UnityLogo.image.height), s_UnityLogo, GUIStyle.none); GUILayout.Space(5); GUILayout.BeginHorizontal(); GUILayout.Space(120); GUILayout.BeginVertical(); if (s_HasConnectionError) { GUILayout.Label(s_ErrorString, "WordWrappedLabel", GUILayout.Width(405)); } else if (s_HasUpdate) { GUILayout.Label(string.Format(s_TextHasUpdate.text, InternalEditorUtility.GetFullUnityVersion(), s_LatestVersionString), "WordWrappedLabel", GUILayout.Width(300)); GUILayout.Space(20); m_ScrollPos = EditorGUILayout.BeginScrollView(m_ScrollPos, GUILayout.Width(405), GUILayout.Height(200)); GUILayout.Label(s_LatestVersionMessage, "WordWrappedLabel"); EditorGUILayout.EndScrollView(); GUILayout.Space(20); GUILayout.BeginHorizontal(); if (GUILayout.Button("Download new version", GUILayout.Width(200))) Help.BrowseURL(s_UpdateURL); if (GUILayout.Button("Skip new version", GUILayout.Width(200))) { EditorPrefs.SetString("EditorUpdateSkipVersionString", s_LatestVersionString); Close(); } GUILayout.EndHorizontal(); } else { GUILayout.Label(string.Format(s_TextUpToDate.text, Application.unityVersion), "WordWrappedLabel", GUILayout.Width(405)); } GUILayout.EndVertical(); GUILayout.EndHorizontal(); GUILayout.Space(8); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(GUILayout.Height(20)); GUILayout.FlexibleSpace(); GUI.changed = false; s_ShowAtStartup = GUILayout.Toggle(s_ShowAtStartup, s_CheckForNewUpdatesText); if (GUI.changed) EditorPrefs.SetBool("EditorUpdateShowAtStartup", s_ShowAtStartup); GUILayout.Space(10); GUILayout.EndHorizontal(); GUILayout.EndVertical(); } } } // namespace
UnityCsReference/Editor/Mono/GUI/EditorUpdateWindow.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUI/EditorUpdateWindow.cs", "repo_id": "UnityCsReference", "token_count": 2416 }
301
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using System; using System.Globalization; namespace UnityEditor { // State for when we're dragging a knob. internal class KnobState { public float dragStartPos; public float dragStartValue; public bool isDragging; public bool isEditing; } public sealed partial class EditorGUILayout { public static float Knob(Vector2 knobSize, float value, float minValue, float maxValue, string unit, Color backgroundColor, Color activeColor, bool showValue, params GUILayoutOption[] options) { Rect r = s_LastRect = GetControlRect(false, knobSize.y, options); return EditorGUI.Knob(r, knobSize, value, minValue, maxValue, unit, backgroundColor, activeColor, showValue, GUIUtility.GetControlID("Knob".GetHashCode(), FocusType.Passive, r)); } } public sealed partial class EditorGUI { internal struct KnobContext { readonly Rect position; readonly Vector2 knobSize; readonly float currentValue; readonly float start; readonly float end; readonly string unit; readonly Color activeColor; readonly Color backgroundColor; readonly bool showValue; readonly int id; private const int kPixelRange = 250; public KnobContext(Rect position, Vector2 knobSize, float currentValue, float start, float end, string unit, Color backgroundColor, Color activeColor, bool showValue, int id) { this.position = position; this.knobSize = knobSize; this.currentValue = currentValue; this.start = start; this.end = end; this.unit = unit; this.activeColor = activeColor; this.backgroundColor = backgroundColor; this.showValue = showValue; this.id = id; } public float Handle() { if (KnobState().isEditing && CurrentEventType() != EventType.Repaint) return DoKeyboardInput(); switch (CurrentEventType()) { case EventType.MouseDown: return OnMouseDown(); case EventType.MouseDrag: return OnMouseDrag(); case EventType.MouseUp: return OnMouseUp(); case EventType.Repaint: return OnRepaint(); } return currentValue; } private EventType CurrentEventType() { return CurrentEvent().type; } private bool IsEmptyKnob() { return start == end; } private Event CurrentEvent() { return Event.current; } private float Clamp(float value) { return Mathf.Clamp(value, MinValue(), MaxValue()); } private float ClampedCurrentValue() { return Clamp(currentValue); } private float MaxValue() { return Mathf.Max(start, end); } private float MinValue() { return Mathf.Min(start, end); } private float GetCurrentValuePercent() { return (ClampedCurrentValue() - MinValue()) / (MaxValue() - MinValue()); } private float MousePosition() { return CurrentEvent().mousePosition.y - position.y; } private bool WasDoubleClick() { return CurrentEventType() == EventType.MouseDown && CurrentEvent().clickCount == 2; } private float ValuesPerPixel() { return kPixelRange / (MaxValue() - MinValue()); } private KnobState KnobState() { return (KnobState)GUIUtility.GetStateObject(typeof(KnobState), id); } private void StartDraggingWithValue(float dragStartValue) { var state = KnobState(); state.dragStartPos = MousePosition(); state.dragStartValue = dragStartValue; state.isDragging = true; } private float OnMouseDown() { // if the click is outside this control, just bail out... if (!position.Contains(CurrentEvent().mousePosition) || KnobState().isEditing || IsEmptyKnob()) return currentValue; GUIUtility.hotControl = id; if (WasDoubleClick()) { KnobState().isEditing = true; } else { // Record where we're dragging from, so the user can get back. StartDraggingWithValue(ClampedCurrentValue()); } CurrentEvent().Use(); return currentValue; } private float OnMouseDrag() { if (GUIUtility.hotControl != id) return currentValue; var state = KnobState(); if (!state.isDragging) return currentValue; GUI.changed = true; CurrentEvent().Use(); // Recalculate the value from the mouse position. this has the side effect that values are relative to the // click point - no matter where inside the trough the original value was. Also means user can get back original value // if he drags back to start position. float deltaPos = state.dragStartPos - MousePosition(); var newValue = state.dragStartValue + (deltaPos / ValuesPerPixel()); return Clamp(newValue); } private float OnMouseUp() { if (GUIUtility.hotControl == id) { CurrentEvent().Use(); GUIUtility.hotControl = 0; KnobState().isDragging = false; } return currentValue; } private void PrintValue() { Rect textRect = new Rect(position.x + knobSize.x / 2 - 8, position.y + knobSize.y / 2 - 8, position.width, 20); string value = currentValue.ToString("0.##", CultureInfo.InvariantCulture.NumberFormat); //FIXME: This needs to be done so it can handle any range types. GUI.Label(textRect, value + " " + unit); } private float DoKeyboardInput() { GUI.SetNextControlName("KnobInput"); GUI.FocusControl("KnobInput"); EditorGUI.BeginChangeCheck(); Rect inputRect = new Rect(position.x + knobSize.x / 2 - 6, position.y + knobSize.y / 2 - 7, position.width, 20); //FIXME: Hack GUIStyle style = GUIStyle.none; style.normal.textColor = new Color(.703f, .703f, .703f, 1.0f); style.fontStyle = FontStyle.Normal; string newStr = EditorGUI.DelayedTextField(inputRect, currentValue.ToString("0.##", CultureInfo.InvariantCulture.NumberFormat), style); if (EditorGUI.EndChangeCheck() && !String.IsNullOrEmpty(newStr)) { KnobState().isEditing = false; float newValue; if (float.TryParse(newStr, out newValue) && newValue != currentValue) { return Clamp(newValue); } } return currentValue; } private static Material knobMaterial; static void CreateKnobMaterial() { if (!knobMaterial) { // use a regular IMGUI content shader Shader shader = AssetDatabase.GetBuiltinExtraResource(typeof(Shader), "Internal-GUITextureClip.shader") as Shader; knobMaterial = new Material(shader); knobMaterial.hideFlags = HideFlags.HideAndDontSave; knobMaterial.mainTexture = EditorGUIUtility.FindTexture("KnobCShape"); knobMaterial.name = "Knob Material"; if (knobMaterial.mainTexture == null) Debug.Log("Did not find 'KnobCShape'"); } } Vector3 GetUVForPoint(Vector3 point) { Vector3 uv = new Vector3( (point.x - position.x) / knobSize.x, (point.y - position.y - knobSize.y) / -knobSize.y // we need to flip uv over Y otherwise image is upside-down ); return uv; } void VertexPointWithUV(Vector3 point) { GL.TexCoord(GetUVForPoint(point)); GL.Vertex(point); } private void DrawValueArc(float angle) { if (Event.current.type != EventType.Repaint) return; CreateKnobMaterial(); Vector3 center = new Vector3(position.x + knobSize.x / 2, position.y + knobSize.y / 2, 0); Vector3 centerRight = new Vector3(position.x + knobSize.x, position.y + knobSize.y / 2, 0); Vector3 bottomRight = new Vector3(position.x + knobSize.x, position.y + knobSize.y, 0); Vector3 bottomleft = new Vector3(position.x, position.y + knobSize.y, 0); Vector3 topLeft = new Vector3(position.x, position.y, 0); Vector3 topRight = new Vector3(position.x + knobSize.x, position.y, 0); Vector3 lastCorner = bottomRight; knobMaterial.SetPass(0); //Background GL.Begin(GL.QUADS); GL.Color(backgroundColor); VertexPointWithUV(topLeft); VertexPointWithUV(topRight); VertexPointWithUV(bottomRight); VertexPointWithUV(bottomleft); GL.End(); //Forground GL.Begin(GL.TRIANGLES); GL.Color(activeColor * (GUI.enabled ? 1.0f : 0.5f)); if (angle > 0.0f) { VertexPointWithUV(center); VertexPointWithUV(centerRight); VertexPointWithUV(bottomRight); lastCorner = bottomRight; if (angle > (Mathf.PI / 2.0f)) { VertexPointWithUV(center); VertexPointWithUV(bottomRight); VertexPointWithUV(bottomleft); lastCorner = bottomleft; if (angle > Mathf.PI) { VertexPointWithUV(center); VertexPointWithUV(bottomleft); VertexPointWithUV(topLeft); lastCorner = topLeft; } } if (angle == (Mathf.PI * (3.0f / 2.0f))) { VertexPointWithUV(center); VertexPointWithUV(topLeft); VertexPointWithUV(topRight); VertexPointWithUV(center); VertexPointWithUV(topRight); VertexPointWithUV(centerRight); } else { //Project the last segment onto the square and draw it. Vector3 projection; float adjustedAngle = angle + Mathf.PI / 4.0f; if (angle < Mathf.PI / 2.0f) projection = bottomRight + new Vector3((knobSize.y / 2 * Mathf.Tan(Mathf.PI / 2.0f - adjustedAngle)) - knobSize.x / 2, 0, 0); else if (angle < Mathf.PI) projection = bottomleft + new Vector3(0, (knobSize.x / 2 * Mathf.Tan(Mathf.PI - adjustedAngle)) - knobSize.y / 2, 0); else projection = topLeft + new Vector3(-(knobSize.y / 2 * Mathf.Tan((Mathf.PI * 3.0f / 2.0f) - adjustedAngle)) + knobSize.x / 2, 0, 0); VertexPointWithUV(center); VertexPointWithUV(lastCorner); VertexPointWithUV(projection); } } GL.End(); } private float OnRepaint() { DrawValueArc(GetCurrentValuePercent() * Mathf.PI * (3.0f / 2.0f)); if (KnobState().isEditing) return DoKeyboardInput(); if (showValue) PrintValue(); return currentValue; } } // Show text, fixed Size input internal static float Knob(Rect position, Vector2 knobSize, float currentValue, float start, float end, string unit, Color backgroundColor, Color activeColor, bool showValue, int id) { return new KnobContext(position, knobSize, currentValue, start, end, unit, backgroundColor, activeColor, showValue, id).Handle(); } internal static float OffsetKnob(Rect position, float currentValue, float start, float end, float median, string unit, Color backgroundColor, Color activeColor, GUIStyle knob, int id) { ///@TODO Implement return 0f; } } }
UnityCsReference/Editor/Mono/GUI/Knob.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUI/Knob.cs", "repo_id": "UnityCsReference", "token_count": 7515 }
302
// 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 UnityEditor.IMGUI.Controls; using UnityEditor.Utils; using UnityEngine; using UnityEditorInternal; using UnityEditor.Experimental; namespace UnityEditor { internal class PackageImportTreeView { TreeViewController m_TreeView; List<PackageImportTreeViewItem> m_Selection = new List<PackageImportTreeViewItem>(); static readonly bool s_UseFoldouts = true; public enum EnabledState { Disabled = -1, None = 0, All = 1, Mixed = 2 } private PackageImport m_PackageImport; public ImportPackageItem[] packageItems { get { return m_PackageImport.packageItems; } } public PackageImportTreeView(PackageImport packageImport, TreeViewState treeViewState, Rect startRect) { m_PackageImport = packageImport; m_TreeView = new TreeViewController(m_PackageImport, treeViewState); var dataSource = new PackageImportTreeViewDataSource(m_TreeView, this); var gui = new PackageImportTreeViewGUI(m_TreeView, this); m_TreeView.Init(startRect, dataSource, gui, null); m_TreeView.ReloadData(); m_TreeView.selectionChangedCallback += SelectionChanged; gui.itemWasToggled += ItemWasToggled; ComputeEnabledStateForFolders(); } void ComputeEnabledStateForFolders() { var root = m_TreeView.data.root as PackageImportTreeViewItem; var done = new HashSet<PackageImportTreeViewItem>(); done.Add(root); // Dont compute for root: mark it as done RecursiveComputeEnabledStateForFolders(root, done); } void RecursiveComputeEnabledStateForFolders(PackageImportTreeViewItem pitem, HashSet<PackageImportTreeViewItem> done) { if (pitem.item != null && !pitem.item.isFolder) return; // Depth first recursion to allow parent folders be dependant on child folders // Recurse if (pitem.hasChildren) { foreach (var child in pitem.children) { RecursiveComputeEnabledStateForFolders(child as PackageImportTreeViewItem, done); } } else if (pitem.item.isFolder) { // since the folder is empty, we don't need to set the enabled check depending of it's children done.Add(pitem); } // Now do logic if (!done.Contains(pitem)) { EnabledState amount = GetFolderChildrenEnabledState(pitem); pitem.enableState = amount; // If 'item' is mixed then all of its parents will also be mixed if (amount == EnabledState.Mixed) { done.Add(pitem); var current = pitem.parent as PackageImportTreeViewItem; while (current != null) { if (!done.Contains(current)) { current.enableState = EnabledState.Mixed; done.Add(current); } current = current.parent as PackageImportTreeViewItem; } } } } bool ItemShouldBeConsideredForEnabledCheck(PackageImportTreeViewItem pitem) { // Not even an item if (pitem == null) return false; // item was a folder that had to be created // in this treeview. if (pitem.item == null) return true; // item is disabled if (pitem.enableState == EnabledState.Disabled) return false; var item = pitem.item; // Its a package asset or its changed if (item.projectAsset || !(item.isFolder || item.assetChanged)) return false; return true; } EnabledState GetFolderChildrenEnabledState(PackageImportTreeViewItem folder) { if (folder.item != null && !folder.item.isFolder) Debug.LogError("Should be a folder item!"); if (!folder.hasChildren) return EnabledState.None; // item is disabled if none of its children can be considered for enabled check EnabledState amount = EnabledState.Disabled; int i = 0; for (; i < folder.children.Count; ++i) { // We dont want to consider project assets in this calculation as they are // ignored var firstValidChild = folder.children[i] as PackageImportTreeViewItem; if (ItemShouldBeConsideredForEnabledCheck(firstValidChild)) { amount = firstValidChild.enableState; break; } } ++i; for (; i < folder.children.Count; ++i) { // We dont want to consider project assets in this calculation as they are // ignored var childItem = folder.children[i] as PackageImportTreeViewItem; if (ItemShouldBeConsideredForEnabledCheck(childItem)) { if (amount != childItem.enableState) { amount = EnabledState.Mixed; break; } } } return amount; } void SelectionChanged(int[] selectedIDs) { // Cache selected tree view items (from ids) m_Selection = new List<PackageImportTreeViewItem>(); var visibleItems = m_TreeView.data.GetRows(); foreach (var visibleItem in visibleItems) { if (selectedIDs.Contains(visibleItem.id)) { var pitem = visibleItem as PackageImportTreeViewItem; if (pitem != null) m_Selection.Add(pitem); } } // Show preview on selection var selectedItem = m_Selection[0].item; if (m_Selection.Count == 1 && selectedItem != null && !string.IsNullOrEmpty(selectedItem.previewPath)) { var gui = m_TreeView.gui as PackageImportTreeViewGUI; gui.showPreviewForID = m_Selection[0].id; } else { PopupWindowWithoutFocus.Hide(); } } public void OnWindowResized() { if (PopupWindowWithoutFocus.IsVisible()) PopupWindowWithoutFocus.Hide(); } public void OnGUI(Rect rect) { // Remove preview popup on mouse scroll wheel events if (Event.current.type == EventType.ScrollWheel) PopupWindowWithoutFocus.Hide(); int keyboardControlID = GUIUtility.GetControlID(FocusType.Keyboard); m_TreeView.OnGUI(rect, keyboardControlID); // Keyboard space toggles selection enabledness if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Space && m_Selection != null && m_Selection.Count > 0 && GUIUtility.keyboardControl == keyboardControlID) { var pitem = m_Selection[0]; if (pitem != null) { EnabledState newEnabled = (pitem.enableState == EnabledState.None) ? EnabledState.All : EnabledState.None; pitem.enableState = newEnabled; ItemWasToggled(m_Selection[0]); } Event.current.Use(); } } public void SetAllEnabled(EnabledState state) { EnableChildrenRecursive(m_TreeView.data.root, state); ComputeEnabledStateForFolders(); } void ItemWasToggled(PackageImportTreeViewItem pitem) { if (m_Selection.Count <= 1) { EnableChildrenRecursive(pitem, pitem.enableState); } else { foreach (var childPItem in m_Selection) { childPItem.enableState = pitem.enableState; } } ComputeEnabledStateForFolders(); } void EnableChildrenRecursive(TreeViewItem parentItem, EnabledState state) { if (!parentItem.hasChildren) return; foreach (TreeViewItem tvitem in parentItem.children) { var pitem = tvitem as PackageImportTreeViewItem; pitem.enableState = state; EnableChildrenRecursive(pitem, state); } } // Item private class PackageImportTreeViewItem : TreeViewItem { public ImportPackageItem item { get; set; } public EnabledState enableState { get { return m_EnableState; } set { // We only want to set the enabled state if the item // is not a project asset. if (item == null || !item.projectAsset) { m_EnableState = value; if (item != null) item.enabledStatus = (int)value; } } } public PackageImportTreeViewItem(ImportPackageItem itemIn, int id, int depth, TreeViewItem parent, string displayName) : base(id, depth, parent, displayName) { item = itemIn; if (item == null) m_EnableState = EnabledState.All; else m_EnableState = (EnabledState)item.enabledStatus; } private EnabledState m_EnableState; } // Gui private class PackageImportTreeViewGUI : TreeViewGUI { internal static class Constants { public static Texture2D folderIcon = EditorGUIUtility.FindTexture(EditorResources.folderIconName); public static GUIContent badgeNew = EditorGUIUtility.TrIconContent("PackageBadgeNew", "This is a new asset."); public static GUIContent badgeOverride = EditorGUIUtility.TrIconContent("PackageBadgeOverride", "This project setting will be overridden!"); public static GUIContent badgeWarnPathConflict = EditorGUIUtility.TrIconContent("console.warnicon", "Warning: File exists in project, but with different GUID. Will override existing asset which may be undesired."); public static GUIContent badgeChange = EditorGUIUtility.TrIconContent("playLoopOff", "This asset is new or has changed."); public static GUIStyle paddinglessStyle; static Constants() { paddinglessStyle = new GUIStyle(); paddinglessStyle.padding = new RectOffset(0, 0, 0, 0); } } public Action<PackageImportTreeViewItem> itemWasToggled; public int showPreviewForID { get; set; } private PackageImportTreeView m_PackageImportView; protected float k_FoldoutWidth = 12f; public PackageImportTreeViewGUI(TreeViewController treeView, PackageImportTreeView view) : base(treeView) { m_PackageImportView = view; k_BaseIndent = 4f; if (!s_UseFoldouts) k_FoldoutWidth = 0f; } override public void OnRowGUI(Rect rowRect, TreeViewItem tvItem, int row, bool selected, bool focused) { k_IndentWidth = 18; k_FoldoutWidth = 18; const float k_ToggleWidth = 18f; var pitem = tvItem as PackageImportTreeViewItem; var item = pitem.item; bool repainting = Event.current.type == EventType.Repaint; // 0. Selection row rect if (selected && repainting) selectionStyle.Draw(rowRect, false, false, true, focused); bool validItem = (item != null); bool isDisabled = (item != null) ? item.enabledStatus == (int)EnabledState.Disabled : false; bool isFolder = (item != null) ? item.isFolder : true; bool assetChanged = (item != null) ? item.assetChanged : false; bool pathConflict = (item != null) ? item.pathConflict : false; bool GUIDOverride = (item != null) ? item.existingAssetPath != string.Empty && item.existingAssetPath != item.destinationAssetPath : false; bool exists = (item != null) ? item.exists : true; bool projectAsset = (item != null) ? item.projectAsset : false; // 1. Foldout if (m_TreeView.data.IsExpandable(tvItem)) DoFoldout(rowRect, tvItem, row); // 2. Toggle only for items that are actually in the package. Rect toggleRect = new Rect(k_BaseIndent + tvItem.depth * indentWidth + k_FoldoutWidth, rowRect.y, k_ToggleWidth, rowRect.height); if ((isFolder && !projectAsset) || (validItem && !projectAsset && assetChanged)) DoToggle(pitem, toggleRect); using (new EditorGUI.DisabledScope(!validItem || projectAsset)) { // 3. Icon & Text Rect contentRect = new Rect(toggleRect.xMax, rowRect.y, rowRect.width, rowRect.height); DoIconAndText(tvItem, contentRect, selected, focused); // 4. Preview popup DoPreviewPopup(pitem, rowRect); // 4. Warning about file/GUID clashing. if (!isDisabled && repainting && validItem) { if (pathConflict) { Rect labelRect = new Rect(rowRect.xMax - 58, rowRect.y, rowRect.height, rowRect.height); EditorGUIUtility.SetIconSize(new Vector2(rowRect.height, rowRect.height)); GUI.Label(labelRect, Constants.badgeWarnPathConflict, Constants.paddinglessStyle); EditorGUIUtility.SetIconSize(Vector2.zero); } else if (GUIDOverride) { Rect labelRect = new Rect(rowRect.xMax - 58, rowRect.y, rowRect.height, rowRect.height); EditorGUIUtility.SetIconSize(new Vector2(rowRect.height, rowRect.height)); GUIContent badgeWarnGUIDConflict = EditorGUIUtility.TrIconContent("console.warnicon", "Warning: A file exists in this project with the same GUID. This Asset being imported will be assigned a new GUID. References to the asset being imported in other imported Assets will be replaced with a reference to: " + item.existingAssetPath); GUI.Label(labelRect, badgeWarnGUIDConflict, Constants.paddinglessStyle); EditorGUIUtility.SetIconSize(Vector2.zero); } } // 5. Optional badge ("New") if (!isDisabled && repainting && validItem && !(exists || pathConflict)) { // FIXME: Need to enable tooltips here. Texture badge = Constants.badgeNew.image; Rect labelRect = new Rect(rowRect.xMax - badge.width - 6, rowRect.y, badge.width, badge.height); GUI.Label(labelRect, Constants.badgeNew, Constants.paddinglessStyle); } // 7. Show what stuff has changed if (!isDisabled && repainting && validItem && (exists || pathConflict) && assetChanged) { if (PackageImportWizard.instance.IsProjectSettingStep) { Texture badge = Constants.badgeOverride.image; Rect labelRect = new Rect(rowRect.xMax - badge.width - 6, rowRect.y, badge.width, badge.height); GUI.Label(labelRect, Constants.badgeOverride, Constants.paddinglessStyle); } else { Texture badge = Constants.badgeChange.image; Rect labelRect = new Rect(rowRect.xMax - badge.width - 6, rowRect.y, rowRect.height, rowRect.height); GUI.Label(labelRect, Constants.badgeChange, Constants.paddinglessStyle); } } } } static void Toggle(ImportPackageItem[] items, PackageImportTreeViewItem pitem, Rect toggleRect) { bool enabled = (int)pitem.enableState > 0; bool isFolder = (pitem.item == null) || pitem.item.isFolder; GUIStyle style = EditorStyles.toggle; bool setMixed = isFolder && (pitem.enableState == EnabledState.Mixed); if (setMixed) style = EditorStyles.toggleMixed; if (isFolder && (pitem.enableState == EnabledState.Disabled)) GUI.enabled = false; bool newEnabled = GUI.Toggle(toggleRect, enabled, GUIContent.none, style); if (newEnabled != enabled) pitem.enableState = newEnabled ? EnabledState.All : EnabledState.None; GUI.enabled = true; } void DoToggle(PackageImportTreeViewItem pitem, Rect toggleRect) { // Toggle on/off EditorGUI.BeginChangeCheck(); Toggle(m_PackageImportView.packageItems, pitem, toggleRect); if (EditorGUI.EndChangeCheck()) { // Only change selection if we already have single selection (Keep multi-selection when toggling) if (m_TreeView.GetSelection().Length <= 1 || !m_TreeView.GetSelection().Contains(pitem.id)) { m_TreeView.SetSelection(new int[] { pitem.id }, false); m_TreeView.NotifyListenersThatSelectionChanged(); } if (itemWasToggled != null) itemWasToggled(pitem); Event.current.Use(); } } void DoPreviewPopup(PackageImportTreeViewItem pitem, Rect rowRect) { var item = pitem.item; if (item != null) { // Ensure preview is shown when clicking on an already selected item (the preview might have been closed) if (Event.current.type == EventType.MouseDown && rowRect.Contains(Event.current.mousePosition) && !PopupWindowWithoutFocus.IsVisible()) showPreviewForID = pitem.id; // Show preview if (pitem.id == showPreviewForID && Event.current.type != EventType.Layout) { showPreviewForID = 0; if (!string.IsNullOrEmpty(item.previewPath)) { Texture2D preview = PackageImport.GetPreview(item.previewPath); Rect buttonRect = rowRect; buttonRect.width = EditorGUIUtility.currentViewWidth; PopupWindowWithoutFocus.Show(buttonRect, new PreviewPopup(preview), new[] { PopupLocation.Right, PopupLocation.Left, PopupLocation.Below }); } } } } void DoIconAndText(TreeViewItem item, Rect contentRect, bool selected, bool focused) { EditorGUIUtility.SetIconSize(new Vector2(k_IconWidth, k_IconWidth)); // If not set we see icons scaling down if text is being cropped lineStyle = Styles.lineStyle; lineStyle.padding.left = 0; // padding could have been set by other tree views contentRect.height += 5; // with the default row height, underscore and lower parts of characters like g, p, etc. were not visible if (Event.current.type == EventType.Repaint) lineStyle.Draw(contentRect, GUIContent.Temp(item.displayName, GetIconForItem(item)), false, false, selected, focused); EditorGUIUtility.SetIconSize(Vector2.zero); } protected override Texture GetIconForItem(TreeViewItem tvItem) { var ourItem = tvItem as PackageImportTreeViewItem; var item = ourItem.item; // Indefined items are always folders. if (item == null || item.isFolder) { return Constants.folderIcon; } // We are using this TreeViewGUI when importing and exporting a package, so handle both situations: // Exporting a package can use cached icons (icons we generate on import) Texture cachedIcon = AssetDatabase.GetCachedIcon(item.destinationAssetPath); if (cachedIcon != null) return cachedIcon; // Importing a package have to use icons based on file extension return InternalEditorUtility.GetIconForFile(item.destinationAssetPath); } protected override void RenameEnded() { } } // Datasource private class PackageImportTreeViewDataSource : TreeViewDataSource { private PackageImportTreeView m_PackageImportView; private const string k_RootTreeItemName = "InvisibleAssetsFolder"; public PackageImportTreeViewDataSource(TreeViewController treeView, PackageImportTreeView view) : base(treeView) { m_PackageImportView = view; rootIsCollapsable = false; showRootItem = false; } public override bool IsRenamingItemAllowed(TreeViewItem item) { return false; } public override bool IsExpandable(TreeViewItem item) { if (!s_UseFoldouts) return false; return base.IsExpandable(item); } public override void FetchData() { int rootDepth = -1; // -1 so its children will have 0 depth m_RootItem = new PackageImportTreeViewItem(null, k_RootTreeItemName.GetHashCode(), rootDepth, null, k_RootTreeItemName); bool initExpandedState = true; if (initExpandedState) m_TreeView.state.expandedIDs.Add(m_RootItem.id); ImportPackageItem[] items = m_PackageImportView.packageItems; Dictionary<string, TreeViewItem> treeViewFolders = new Dictionary<string, TreeViewItem>(); for (int i = 0; i < items.Length; i++) { var item = items[i]; if (PackageImport.HasInvalidCharInFilePath(item.destinationAssetPath)) continue; // Do not add invalid paths (we already warn the user with a dialog in PackageImport.cs) string filename = Path.GetFileName(item.destinationAssetPath).ConvertSeparatorsToUnity(); string folderPath = Path.GetDirectoryName(item.destinationAssetPath).ConvertSeparatorsToUnity(); // Ensure folders. This is for when installed packages have been moved to other folders. TreeViewItem targetFolder; treeViewFolders.TryGetValue(folderPath, out targetFolder); if (targetFolder == null) { targetFolder = EnsureFolderPath(folderPath, treeViewFolders, initExpandedState); } // Add file to folder if (targetFolder != null) { int id = item.destinationAssetPath.GetHashCode(); var newItem = new PackageImportTreeViewItem(item, id, targetFolder.depth + 1, targetFolder, filename); targetFolder.AddChild(newItem); if (initExpandedState) m_TreeView.state.expandedIDs.Add(id); // We need to ensure that the folder is available for // EnsureFolderPath on subsequent iterations. if (item.isFolder) treeViewFolders[item.destinationAssetPath] = newItem; } } if (initExpandedState) m_TreeView.state.expandedIDs.Sort(); } TreeViewItem EnsureFolderPath(string folderPath, Dictionary<string, TreeViewItem> treeViewFolders, bool initExpandedState) { //We're in the root folder, so just return the root item as the parent. if (folderPath == "") return m_RootItem; // Does folder path exist? int id = folderPath.GetHashCode(); TreeViewItem item = TreeViewUtility.FindItem(id, m_RootItem); if (item != null) { return item; } // Add folders as needed string[] splitPath = folderPath.Split('/'); string currentPath = ""; TreeViewItem currentItem = m_RootItem; int folderDepth = -1; // Will be incremented to the right depth in the loop. for (int depth = 0; depth < splitPath.Length; ++depth) { string folder = splitPath[depth]; if (currentPath != "") currentPath += '/'; currentPath += folder; // Dont create a 'Assets' folder (we already have that as a hidden root) if (depth == 0 && currentPath == "Assets") continue; // Only increment the folder depth if we are past the root "Assets" folder. ++folderDepth; id = currentPath.GetHashCode(); TreeViewItem foundItem; if (treeViewFolders.TryGetValue(currentPath, out foundItem)) { currentItem = foundItem; } else { // If we do not have a tree view item for this folder we create one var folderItem = new PackageImportTreeViewItem(null, id, folderDepth, currentItem, folder); // Add to children array of the parent currentItem.AddChild(folderItem); currentItem = folderItem; // Auto expand all folder items if (initExpandedState) m_TreeView.state.expandedIDs.Add(id); // For faster finding of folders treeViewFolders[currentPath] = folderItem; } } return currentItem; } } class PreviewPopup : PopupWindowContent { readonly Texture2D m_Preview; readonly Vector2 kPreviewSize = new Vector2(128f, 128f); public PreviewPopup(Texture2D preview) { m_Preview = preview; } public override void OnGUI(Rect rect) { PackageImport.DrawTexture(rect, m_Preview, false); } public override Vector2 GetWindowSize() { return kPreviewSize; } } } }
UnityCsReference/Editor/Mono/GUI/PackageImportTreeView.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUI/PackageImportTreeView.cs", "repo_id": "UnityCsReference", "token_count": 14588 }
303
// 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 StructPropertyGUILayout { internal static void GenericStruct(SerializedProperty property, params GUILayoutOption[] options) { float height = EditorGUI.kStructHeaderLineHeight + EditorGUI.kSingleLineHeight * GetChildrenCount(property); Rect rect = GUILayoutUtility.GetRect(EditorGUILayout.kLabelFloatMinW, EditorGUILayout.kLabelFloatMaxW, height, height, EditorStyles.layerMaskField, options); StructPropertyGUI.GenericStruct(rect, property); } internal static int GetChildrenCount(SerializedProperty property) { int count = 0; SerializedProperty iterator = property.Copy(); var end = iterator.GetEndProperty(); while (!SerializedProperty.EqualContents(iterator, end)) { count++; iterator.NextVisible(true); } return count; } } internal class StructPropertyGUI { static class Styles { public static readonly GUIStyle sectionLabel = new GUIStyle(EditorStyles.label) { alignment = TextAnchor.UpperLeft }; } internal static void GenericStruct(Rect position, SerializedProperty property) { GUI.Label(EditorGUI.IndentedRect(position), property.displayName, Styles.sectionLabel); position.y += EditorGUI.kStructHeaderLineHeight; DoChildren(position, property); } private static void DoChildren(Rect position, SerializedProperty property) { position.height = EditorGUI.kSingleLineHeight; EditorGUI.indentLevel++; SerializedProperty iterator = property.Copy(); var end = iterator.GetEndProperty(); iterator.NextVisible(true); while (!SerializedProperty.EqualContents(iterator, end)) { EditorGUI.PropertyField(position, iterator); position.y += EditorGUI.kSingleLineHeight; if (!iterator.NextVisible(false)) break; } EditorGUI.indentLevel--; EditorGUILayout.Space(); } } }
UnityCsReference/Editor/Mono/GUI/StructPropertyGUI.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUI/StructPropertyGUI.cs", "repo_id": "UnityCsReference", "token_count": 1067 }
304
// 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; // The TreeView requires implementations from the following three interfaces: // ITreeViewDataSource: Should handle data fetching, build the tree/data structure and hold expanded state // ITreeViewGUI: Should handle visual representation of TreeView and input handling // ITreeViewDragging Should handle dragging, temp expansion of items, allow/disallow dropping // The TreeView handles: Navigation, Item selection and initiates dragging namespace UnityEditor.IMGUI.Controls { // Represents a complete data tree internal interface ITreeViewDataSource { void OnInitialize(); // Return root of tree TreeViewItem root { get; } // For data sources where GetRows() might be an expensive operation int rowCount { get; } // Reload data void ReloadData(); void InitIfNeeded(); // Find Item by id TreeViewItem FindItem(int id); // Get current row of an item (using the current expanded state in TreeViewState) // Returns -1 if not found int GetRow(int id); // Check rowCount before requesting TreeViewItem GetItem(int row); // Get the flattened tree of visible items. If possible use GetItem(int row) instead IList<TreeViewItem> GetRows(); bool IsRevealed(int id); void RevealItem(int id); void RevealItems(int[] ids); // Expand / collapse interface // The DataSource has the interface for this because it should be able to rebuild // tree when expanding void SetExpandedWithChildren(TreeViewItem item, bool expand); void SetExpanded(TreeViewItem item, bool expand); bool IsExpanded(TreeViewItem item); bool IsExpandable(TreeViewItem item); void SetExpandedWithChildren(int id, bool expand); int[] GetExpandedIDs(); void SetExpandedIDs(int[] ids); bool SetExpanded(int id, bool expand); bool IsExpanded(int id); // Selection bool CanBeMultiSelected(TreeViewItem item); bool CanBeParent(TreeViewItem item); List<int> GetNewSelection(TreeViewItem clickedItem, TreeViewSelectState selectState); // Renaming bool IsRenamingItemAllowed(TreeViewItem item); void InsertFakeItem(int id, int parentID, string name, Texture2D icon); void RemoveFakeItem(); bool HasFakeItem(); // Search void OnSearchChanged(); } } // namespace UnityEditor
UnityCsReference/Editor/Mono/GUI/TreeView/ITreeViewDataSource.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUI/TreeView/ITreeViewDataSource.cs", "repo_id": "UnityCsReference", "token_count": 964 }
305
// 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.Assertions; namespace UnityEditor.IMGUI.Controls { // Abstract base class for common dragging behavior // Usage: // - Override StartDrag // - Override DoDrag // Features: // - Expands items with children on hover (after ca 0.7 seconds) // internal abstract class TreeViewDragging : ITreeViewDragging { protected TreeViewController m_TreeView; protected class DropData { public int[] expandedArrayBeforeDrag; public int lastControlID = -1; public int dropTargetControlID = -1; public int rowMarkerControlID = -1; public int ancestorControlID; public double expandItemBeginTimer; public Vector2 expandItemBeginPosition; public float insertionMarkerYPosition; public TreeViewItem insertRelativeToSibling; public void ClearPerEventState() { dropTargetControlID = -1; rowMarkerControlID = -1; ancestorControlID = -1; insertionMarkerYPosition = -1f; insertRelativeToSibling = null; } } public enum DropPosition { Upon = 0, Below = 1, Above = 2 } protected DropData m_DropData = new DropData(); const double k_DropExpandTimeout = 0.7; static class Constants { public const string GetInsertionIndexNotFound = "Did not find targetItem,; should be a child of parentItem"; } public TreeViewDragging(TreeViewController treeView) { m_TreeView = treeView; } virtual public void OnInitialize() { } public int GetDropTargetControlID() { return m_DropData.dropTargetControlID; } public int GetRowMarkerControlID() { return m_DropData.rowMarkerControlID; } public int GetAncestorControlID() { return m_DropData.ancestorControlID; } public bool drawRowMarkerAbove { get; set; } public float insertionMarkerYPosition { get { return m_DropData.insertionMarkerYPosition; } } public TreeViewItem insertRelativeToSibling { get { return m_DropData.insertRelativeToSibling; } } public Func<int> getIndentLevelForMouseCursor; public virtual bool CanStartDrag(TreeViewItem targetItem, List<int> draggedItemIDs, Vector2 mouseDownPosition) { return true; } // This method is called from TreeView when a drag is started // Client should setup the drag data public abstract void StartDrag(TreeViewItem draggedItem, List<int> draggedItemIDs); // This method is called from within DragElement when it has determined what is the parent item of the current targetItem // (This depends on if dropPosition is above, below or upon) // Implemented by client code to decide what should happen when the drag is e.g performed (e.g change the backend state of the tree view) // Notes on arguments: // When hovering outside any items: target and parent is null, dropPos is invalid // If parentItem and targetItem is the same then insert as first child of parent, dropPos is invalid // If parentItem and targetItem is different then use dropPos to insert dragged items relative to targetItem // parentItem can be null when root is visible and hovering above or below the root // if targetItem is null then parent can be null if root is visible // if targetitem is null then parent might be valid if root is hidden public abstract DragAndDropVisualMode DoDrag(TreeViewItem parentItem, TreeViewItem targetItem, bool perform, DropPosition dropPosition); protected float GetDropBetweenHalfHeight(TreeViewItem item, Rect itemRect) { return m_TreeView.data.CanBeParent(item) ? m_TreeView.gui.halfDropBetweenHeight : itemRect.height * 0.5f; } void GetPreviousAndNextItemsIgnoringDraggedItems(int targetRow, DropPosition dropPosition, out TreeViewItem previousItem, out TreeViewItem nextItem) { if (dropPosition != DropPosition.Above && dropPosition != DropPosition.Below) throw new ArgumentException("Invalid argument: " + dropPosition); previousItem = nextItem = null; int curPrevRow = (dropPosition == DropPosition.Above) ? targetRow - 1 : targetRow; int curNextRow = (dropPosition == DropPosition.Above) ? targetRow : targetRow + 1; while (curPrevRow >= 0) { var curPreviousItem = m_TreeView.data.GetItem(curPrevRow); if (!m_TreeView.IsDraggingItem(curPreviousItem)) { previousItem = curPreviousItem; break; } curPrevRow--; } while (curNextRow < m_TreeView.data.rowCount) { var curNextItem = m_TreeView.data.GetItem(curNextRow); if (!m_TreeView.IsDraggingItem(curNextItem)) { nextItem = curNextItem; break; } curNextRow++; } } internal void HandleSiblingInsertionAtAvailableDepthsAndChangeTargetIfNeeded(ref TreeViewItem targetItem, int targetItemRow, ref DropPosition dropPosition, int cursorDepth, out bool didChangeTargetToAncestor) { if (dropPosition != DropPosition.Above && dropPosition != DropPosition.Below) throw new ArgumentException("Invalid argument: " + dropPosition); didChangeTargetToAncestor = false; TreeViewItem prevItem, nextItem; GetPreviousAndNextItemsIgnoringDraggedItems(targetItemRow, dropPosition, out prevItem, out nextItem); if (prevItem == null) return; // Above first row so keep targetItem bool hoveringBetweenExpandedParentAndFirstChild = prevItem.hasChildren && m_TreeView.data.IsExpanded(prevItem.id); int minDepth = nextItem != null ? nextItem.depth : 0; int maxDepth = prevItem.depth + (hoveringBetweenExpandedParentAndFirstChild ? 1 : 0); // Change targetItem and dropPosition targetItem = prevItem; dropPosition = DropPosition.Below; if (maxDepth <= minDepth) { if (hoveringBetweenExpandedParentAndFirstChild) { targetItem = prevItem.children[0]; dropPosition = DropPosition.Above; } return; // The nextItem is a descendant of previous item so keep targetItem } if (cursorDepth >= maxDepth) { if (hoveringBetweenExpandedParentAndFirstChild) { targetItem = prevItem.children[0]; dropPosition = DropPosition.Above; } return; // No need to change targetItem if same or higher depth } // Search through parents for a new target that matches the cursor var target = targetItem; while (target.depth > minDepth) { if (target.depth == cursorDepth) break; target = target.parent; } didChangeTargetToAncestor = target != targetItem; // Change to new targetItem targetItem = target; } protected bool TryGetDropPosition(TreeViewItem item, Rect itemRect, int row, out DropPosition dropPosition) { Vector2 currentMousePos = Event.current.mousePosition; if (itemRect.Contains(currentMousePos)) { float dropBetweenHalfHeight = GetDropBetweenHalfHeight(item, itemRect); if (currentMousePos.y >= itemRect.yMax - dropBetweenHalfHeight) dropPosition = DropPosition.Below; else if (currentMousePos.y <= itemRect.yMin + dropBetweenHalfHeight) dropPosition = DropPosition.Above; else dropPosition = DropPosition.Upon; return true; } else { // Check overlap with next item (if any) float nextOverlap = m_TreeView.gui.halfDropBetweenHeight; int nextRow = row + 1; if (nextRow < m_TreeView.data.rowCount) { Rect nextRect = m_TreeView.gui.GetRowRect(nextRow, itemRect.width); bool nextCanBeParent = m_TreeView.data.CanBeParent(m_TreeView.data.GetItem(nextRow)); if (nextCanBeParent) nextOverlap = m_TreeView.gui.halfDropBetweenHeight; else nextOverlap = nextRect.height * 0.5f; } Rect nextOverlapRect = itemRect; nextOverlapRect.y = itemRect.yMax; nextOverlapRect.height = nextOverlap; if (nextOverlapRect.Contains(currentMousePos)) { dropPosition = DropPosition.Below; return true; } // Check overlap above first item if (row == 0) { Rect overlapUpwards = itemRect; overlapUpwards.yMin -= m_TreeView.gui.halfDropBetweenHeight; overlapUpwards.height = m_TreeView.gui.halfDropBetweenHeight; if (overlapUpwards.Contains(currentMousePos)) { dropPosition = DropPosition.Above; return true; } } } dropPosition = DropPosition.Below; return false; } // This method is called from TreeView and handles: // - Where the dragged items are dropped (above, below or upon) // - Auto expansion of collapsed items when hovering over them // - Setting up the render markers for drop location (horizontal lines) // 'targetItem' is null when not hovering over any target Item, if so the rest of the arguments are invalid public virtual bool DragElement(TreeViewItem targetItem, Rect targetItemRect, int row) { bool perform = Event.current.type == EventType.DragPerform; // Are we dragging outside any items if (targetItem == null) { // If so clear any drop markers if (m_DropData != null) { m_DropData.ClearPerEventState(); } // And let client decide what happens when dragging outside items DragAndDrop.visualMode = DoDrag(null, null, perform, DropPosition.Below); if (DragAndDrop.visualMode != DragAndDropVisualMode.None && perform) FinalizeDragPerformed(true); return false; } DropPosition dropPosition; if (!TryGetDropPosition(targetItem, targetItemRect, row, out dropPosition)) return false; TreeViewItem parentItem = null; TreeViewItem dropRelativeToItem = targetItem; bool didChangeTargetToAncestor = false; DropPosition originalDropPosition = dropPosition; switch (dropPosition) { case DropPosition.Upon: // Parent change: Client must decide what happens when dropping upon: e.g: insert last or first in child list parentItem = dropRelativeToItem; break; case DropPosition.Below: case DropPosition.Above: // Sibling change if (getIndentLevelForMouseCursor != null) { int cursorDepth = getIndentLevelForMouseCursor(); HandleSiblingInsertionAtAvailableDepthsAndChangeTargetIfNeeded(ref dropRelativeToItem, row, ref dropPosition, cursorDepth, out didChangeTargetToAncestor); } else { if (dropPosition == DropPosition.Below && m_TreeView.data.IsExpanded(dropRelativeToItem) && dropRelativeToItem.hasChildren) { // When hovering between an expanded parent and its first child then make sure we change state to match that dropPosition = DropPosition.Above; dropRelativeToItem = dropRelativeToItem.children[0]; } } parentItem = dropRelativeToItem.parent; break; default: Debug.LogError("Unhandled enum. Report a bug."); break; } if (perform) { DragAndDropVisualMode mode = DragAndDropVisualMode.None; // Try Drop upon target item if (dropPosition == DropPosition.Upon) mode = DoDrag(dropRelativeToItem, dropRelativeToItem, true, dropPosition); // Drop between items if (mode == DragAndDropVisualMode.None && parentItem != null) { mode = DoDrag(parentItem, dropRelativeToItem, true, dropPosition); } // Finalize drop if (mode != DragAndDropVisualMode.None) { FinalizeDragPerformed(false); } else { DragCleanup(true); m_TreeView.NotifyListenersThatDragEnded(null, false); } } else // DragUpdate { if (m_DropData == null) m_DropData = new DropData(); m_DropData.ClearPerEventState(); // Try drop on top of items if (dropPosition == DropPosition.Upon) { int itemControlID = TreeViewController.GetItemControlID(dropRelativeToItem); HandleAutoExpansion(itemControlID, dropRelativeToItem, targetItemRect); var mode = DoDrag(dropRelativeToItem, dropRelativeToItem, false, dropPosition); if (mode != DragAndDropVisualMode.None) { m_DropData.dropTargetControlID = itemControlID; DragAndDrop.visualMode = mode; } } // Drop between items else if (dropRelativeToItem != null && parentItem != null) { var mode = DoDrag(parentItem, dropRelativeToItem, false, dropPosition); if (mode != DragAndDropVisualMode.None) { drawRowMarkerAbove = dropPosition == DropPosition.Above; m_DropData.rowMarkerControlID = TreeViewController.GetItemControlID(dropRelativeToItem); m_DropData.insertionMarkerYPosition = originalDropPosition == DropPosition.Above ? targetItemRect.y : targetItemRect.yMax; m_DropData.insertRelativeToSibling = dropRelativeToItem; if (didChangeTargetToAncestor) { m_DropData.ancestorControlID = TreeViewController.GetItemControlID(dropRelativeToItem); } DragAndDrop.visualMode = mode; } } } Event.current.Use(); return true; } void FinalizeDragPerformed(bool revertExpanded) { string undoActionName = "Drag and Drop Multiple Objects"; DragCleanup(revertExpanded); DragAndDrop.AcceptDrag(); List<UnityEngine.Object> objs = new List<UnityEngine.Object>(DragAndDrop.objectReferences); // TODO, what about when dragging non objects... bool draggedItemsFromOwnTreeView = true; if (objs.Count > 0 && objs[0] != null && TreeViewUtility.FindItemInList(objs[0].GetInstanceID(), m_TreeView.data.GetRows()) == null) draggedItemsFromOwnTreeView = false; int[] newSelection = new int[objs.Count]; for (int i = 0; i < objs.Count; ++i) { if (objs[i] == null) continue; newSelection[i] = (objs[i].GetInstanceID()); } m_TreeView.NotifyListenersThatDragEnded(newSelection, draggedItemsFromOwnTreeView); if (objs.Count == 1) undoActionName = "Drag and Drop " + objs[0].name; Undo.SetCurrentGroupName(undoActionName); } protected virtual void HandleAutoExpansion(int itemControlID, TreeViewItem targetItem, Rect targetItemRect) { Vector2 currentMousePos = Event.current.mousePosition; // Handle auto expansion float targetItemIndent = m_TreeView.gui.GetContentIndent(targetItem); float betweenHalfHeight = GetDropBetweenHalfHeight(targetItem, targetItemRect); Rect indentedContentRect = new Rect(targetItemRect.x + targetItemIndent, targetItemRect.y + betweenHalfHeight, targetItemRect.width - targetItemIndent, targetItemRect.height - betweenHalfHeight * 2); bool hoveringOverIndentedContent = indentedContentRect.Contains(currentMousePos); if (itemControlID != m_DropData.lastControlID || !hoveringOverIndentedContent || m_DropData.expandItemBeginPosition != currentMousePos) { m_DropData.lastControlID = itemControlID; m_DropData.expandItemBeginTimer = Time.realtimeSinceStartup; m_DropData.expandItemBeginPosition = currentMousePos; } bool expandTimerExpired = Time.realtimeSinceStartup - m_DropData.expandItemBeginTimer > k_DropExpandTimeout; bool mayExpand = hoveringOverIndentedContent && expandTimerExpired; // Auto open folders we are about to drag into if (targetItem != null && mayExpand && targetItem.hasChildren && !m_TreeView.data.IsExpanded(targetItem)) { // Store the expanded array prior to drag so we can revert it with a delay later if (m_DropData.expandedArrayBeforeDrag == null) { List<int> expandedIDs = GetCurrentExpanded(); m_DropData.expandedArrayBeforeDrag = expandedIDs.ToArray(); } m_TreeView.data.SetExpanded(targetItem, true); m_DropData.expandItemBeginTimer = Time.realtimeSinceStartup; m_DropData.lastControlID = 0; } } public virtual void DragCleanup(bool revertExpanded) { if (m_DropData != null) { if (m_DropData.expandedArrayBeforeDrag != null && revertExpanded) { RestoreExpanded(new List<int>(m_DropData.expandedArrayBeforeDrag)); } m_DropData = new DropData(); } } public List<int> GetCurrentExpanded() { var visibleItems = m_TreeView.data.GetRows(); List<int> expandedIDs = (from item in visibleItems where m_TreeView.data.IsExpanded(item) select item.id).ToList(); return expandedIDs; } // We assume that we can only have expanded items during dragging public void RestoreExpanded(List<int> ids) { var visibleItems = m_TreeView.data.GetRows(); foreach (TreeViewItem item in visibleItems) m_TreeView.data.SetExpanded(item, ids.Contains(item.id)); } internal static int GetInsertionIndex(TreeViewItem parentItem, TreeViewItem targetItem, DropPosition dropPosition) { if (parentItem == null) return -1; int insertionIndex; if (parentItem == targetItem) { // Let user decide what index item should be added to when dropping upon insertionIndex = -1; Assert.AreEqual(DropPosition.Upon, dropPosition); } else { int index = parentItem.children.IndexOf(targetItem); if (index >= 0) { if (dropPosition == DropPosition.Below) insertionIndex = index + 1; else insertionIndex = index; } else { Debug.LogError(Constants.GetInsertionIndexNotFound); insertionIndex = -1; } } return insertionIndex; } } } // namespace UnityEditor
UnityCsReference/Editor/Mono/GUI/TreeView/TreeViewDragging.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUI/TreeView/TreeViewDragging.cs", "repo_id": "UnityCsReference", "token_count": 10276 }
306
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Globalization; using UnityEngine; namespace UnityEditor { internal class VerticalGrid { int m_Columns = 1; int m_Rows; float m_Height; float m_HorizontalSpacing; public int columns { get {return m_Columns; } } public int rows { get {return m_Rows; } } public float height { get {return m_Height; } } public float horizontalSpacing { get {return m_HorizontalSpacing; } } // Adjust grid values public float fixedWidth { get; set; } public Vector2 itemSize { get; set; } public float verticalSpacing { get; set; } // spacing between each row of items public float minHorizontalSpacing { get; set; } // minimum spacing between each column in grid public float topMargin { get; set; } public float bottomMargin { get; set; } public float rightMargin { get; set; } public float leftMargin { get; set; } public float fixedHorizontalSpacing {get; set; } public bool useFixedHorizontalSpacing {get; set; } // Call after setting parameters above and before using CalcRect public void InitNumRowsAndColumns(int itemCount, int maxNumRows) { if (useFixedHorizontalSpacing) { // Set columns (with an excess of 1 fixedHorizontalSpacing) m_Columns = CalcColumns(); // Set horizontal spacing m_HorizontalSpacing = fixedHorizontalSpacing; // Set rows m_Rows = Mathf.Min(maxNumRows, CalcRows(itemCount)); // Set height m_Height = m_Rows * (itemSize.y + verticalSpacing) - verticalSpacing + topMargin + bottomMargin; } else // center columns { // Set columns (with an excess of 1 minHorizontalSpacing) m_Columns = CalcColumns(); // Set horizontal spacing m_HorizontalSpacing = Mathf.Max(0f, (fixedWidth - (m_Columns * itemSize.x + leftMargin + rightMargin)) / (m_Columns)); // Set rows m_Rows = Mathf.Min(maxNumRows, CalcRows(itemCount)); if (m_Rows == 1) m_HorizontalSpacing = minHorizontalSpacing; // Set height m_Height = m_Rows * (itemSize.y + verticalSpacing) - verticalSpacing + topMargin + bottomMargin; } } public int CalcColumns() { float horizontalSpacing = useFixedHorizontalSpacing ? fixedHorizontalSpacing : minHorizontalSpacing; int cols = (int)Mathf.Floor((fixedWidth - leftMargin - rightMargin) / (itemSize.x + horizontalSpacing)); cols = Mathf.Max(cols, 1); return cols; } public int CalcRows(int itemCount) { int t = (int)Mathf.Ceil(itemCount / (float)CalcColumns()); if (t < 0) return int.MaxValue; return t; } public Rect CalcRect(int itemIdx, float yOffset) { float row = Mathf.Floor(itemIdx / columns); float column = itemIdx - row * columns; if (useFixedHorizontalSpacing) { return new Rect(leftMargin + column * (itemSize.x + fixedHorizontalSpacing), row * (itemSize.y + verticalSpacing) + topMargin + yOffset, itemSize.x, itemSize.y); } else { return new Rect(leftMargin + horizontalSpacing * 0.5f + column * (itemSize.x + horizontalSpacing), row * (itemSize.y + verticalSpacing) + topMargin + yOffset, itemSize.x, itemSize.y); } } public int GetMaxVisibleItems(float height) { int visibleRows = (int)Mathf.Ceil((height - topMargin - bottomMargin) / (itemSize.y + verticalSpacing)); return visibleRows * columns; } public bool IsVisibleInScrollView(float scrollViewHeight, float scrollPos, float gridStartY, int maxIndex, out int startIndex, out int endIndex) { startIndex = endIndex = 0; // In grid coordinates float scrollViewStart = scrollPos; float scrollViewEnd = scrollPos + scrollViewHeight; float offsetY = gridStartY + topMargin; // Entirely below view if (offsetY > scrollViewEnd) return false; // Entirely above view if (offsetY + height < scrollViewStart) return false; float itemHeightAndSpacing = itemSize.y + verticalSpacing; // startRow can be negative if grid is starting in the middle of the view int startRow = Mathf.FloorToInt((scrollViewStart - offsetY) / itemHeightAndSpacing); startIndex = startRow * columns; startIndex = Mathf.Clamp(startIndex, 0, maxIndex); // endRow can be negative if grid is starting in the middle of the view int endRow = Mathf.FloorToInt((scrollViewEnd - offsetY) / itemHeightAndSpacing); endIndex = (endRow + 1) * columns - 1; endIndex = Mathf.Clamp(endIndex, 0, maxIndex); return true; } public override string ToString() { return UnityString.Format("VerticalGrid: rows {0}, columns {1}, fixedWidth {2}, itemSize {3}", rows, columns, fixedWidth, itemSize); } } internal class VerticalGridWithSplitter { int m_Columns = 1; int m_Rows; float m_Height; float m_HorizontalSpacing; public int columns { get {return m_Columns; } } public int rows { get {return m_Rows; } } public float height { get {return m_Height; } } public float horizontalSpacing { get {return m_HorizontalSpacing; } } // Adjust grid values public float fixedWidth { get; set; } public Vector2 itemSize { get; set; } public float verticalSpacing { get; set; } // spacing between each row of items public float minHorizontalSpacing { get; set; } // minimum spacing between each column in grid public float topMargin { get; set; } public float bottomMargin { get; set; } public float rightMargin { get; set; } public float leftMargin { get; set; } // Call after setting parameters above and before using CalcRect public void InitNumRowsAndColumns(int itemCount, int maxNumRows) { // Set columns (with an excess of 1 minHorizontalSpacing) m_Columns = (int)Mathf.Floor((fixedWidth - leftMargin - rightMargin) / (itemSize.x + minHorizontalSpacing)); m_Columns = Mathf.Max(m_Columns, 1); // Set horizontal spacing m_HorizontalSpacing = 0f; if (m_Columns > 1) m_HorizontalSpacing = (fixedWidth - (m_Columns * itemSize.x + leftMargin + rightMargin)) / (m_Columns - 1); // Set rows m_Rows = Mathf.Min(maxNumRows, (int)Mathf.Ceil(itemCount / (float)m_Columns)); // Set height m_Height = m_Rows * (itemSize.y + verticalSpacing) - verticalSpacing + topMargin + bottomMargin; } public Rect CalcRect(int itemIdx, float yOffset) { float row = Mathf.Floor(itemIdx / columns); float column = itemIdx - row * columns; return new Rect(column * (itemSize.x + horizontalSpacing) + leftMargin, row * (itemSize.y + verticalSpacing) + topMargin + yOffset, itemSize.x, itemSize.y); } public int GetMaxVisibleItems(float height) { int visibleRows = (int)Mathf.Ceil((height - topMargin - bottomMargin) / (itemSize.y + verticalSpacing)); return visibleRows * columns; } int m_SplitAfterRow; float m_CurrentSplitHeight; float m_LastSplitUpdate; float m_TargetSplitHeight; public void ResetSplit() { m_SplitAfterRow = -1; m_CurrentSplitHeight = 0f; m_LastSplitUpdate = -1f; m_TargetSplitHeight = 0f; } public void OpenSplit(int splitAfterRowIndex, int numItems) { int numRows = (int)Mathf.Ceil(numItems / (float)m_Columns); float splitHeight = numRows * (itemSize.y + verticalSpacing) - verticalSpacing + topMargin + bottomMargin; m_SplitAfterRow = splitAfterRowIndex; m_TargetSplitHeight = splitHeight; m_LastSplitUpdate = Time.realtimeSinceStartup; } // Returns Rect of split content starting from index 0 public Rect CalcSplitRect(int splitIndex, float yOffset) { Rect rect = new Rect(0, 0, 0, 0); return rect; } public void CloseSplit() { m_TargetSplitHeight = 0f; } // Returns true if animating (client should ensure to repaint in this case) public bool UpdateSplitAnimationOnGUI() { if (m_SplitAfterRow != -1) { float delta = Time.realtimeSinceStartup - m_LastSplitUpdate; m_CurrentSplitHeight = delta * m_TargetSplitHeight; m_LastSplitUpdate = Time.realtimeSinceStartup; // Animate if (m_CurrentSplitHeight != m_TargetSplitHeight && Event.current.type == EventType.Repaint) { m_CurrentSplitHeight = Mathf.MoveTowards(m_CurrentSplitHeight, m_TargetSplitHeight, 0.03f); if (m_CurrentSplitHeight == 0 && m_TargetSplitHeight == 0) { ResetSplit(); } return true; } } return false; } } }
UnityCsReference/Editor/Mono/GUI/VerticalGrid.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUI/VerticalGrid.cs", "repo_id": "UnityCsReference", "token_count": 4734 }
307
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine.Bindings; using UnityEngine.Scripting; using System; using System.Runtime.InteropServices; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using Unity.Burst; namespace UnityEditor { [NativeHeader("Editor/Src/Utility/GameObjectChangeTracker.h")] internal static class GameObjectChangeTracker { static GameObjectChangeTracker() => Init(); [StaticAccessor("GameObjectChangeTracker", StaticAccessorType.DoubleColon)] extern static void Init(); public static event GameObjectChangeTrackerEventHandler GameObjectsChanged { add => m_GameObjectsChanged.Add(value); remove => m_GameObjectsChanged.Remove(value); } public static unsafe void PublishEvents(NativeArray<GameObjectChangeTrackerEvent> events) => OnGameObjectsChanged((IntPtr)events.GetUnsafeReadOnlyPtr(), events.Length); private static EventWithPerformanceTracker<GameObjectChangeTrackerEventHandler> m_GameObjectsChanged = new EventWithPerformanceTracker<GameObjectChangeTrackerEventHandler>($"{nameof(GameObjectChangeTracker)}.{nameof(GameObjectsChanged)}"); [RequiredByNativeCode(GenerateProxy = true)] static unsafe void OnGameObjectsChanged(IntPtr events, int eventsCount) { if (!m_GameObjectsChanged.hasSubscribers || eventsCount == 0) return; var nativeArray = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<GameObjectChangeTrackerEvent>(events.ToPointer(), eventsCount, Allocator.Invalid); var ash = AtomicSafetyHandle.Create(); InitStaticSafetyId(ref ash); NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref nativeArray, ash); try { foreach (var evt in m_GameObjectsChanged) evt(nativeArray); } finally { var result = AtomicSafetyHandle.EnforceAllBufferJobsHaveCompletedAndRelease(ash); if (result == EnforceJobResult.DidSyncRunningJobs) { UnityEngine.Debug.LogError( $"You cannot use the {nameof(GameObjectChangeTracker)} instance provided by {nameof(GameObjectsChanged)} in a job unless you complete the job before your callback finishes."); } } } // TODO: Once Burst supports internal/external functions in static initializers, this can become // static readonly int s_staticSafetyId = AtomicSafetyHandle.NewStaticSafetyId<GameObjectChangeTrackerEvents>(); // and InitStaticSafetyId() can be replaced with a call to AtomicSafetyHandle.SetStaticSafetyId(); static int s_staticSafetyId; [BurstDiscard] static void InitStaticSafetyId(ref AtomicSafetyHandle handle1) { if (s_staticSafetyId == 0) s_staticSafetyId = AtomicSafetyHandle.NewStaticSafetyId<GameObjectChangeTrackerEvent>(); AtomicSafetyHandle.SetStaticSafetyId(ref handle1, s_staticSafetyId); } } internal delegate void GameObjectChangeTrackerEventHandler(in NativeArray<GameObjectChangeTrackerEvent> events); [StructLayout(layoutKind: LayoutKind.Sequential)] internal readonly struct GameObjectChangeTrackerEvent { public GameObjectChangeTrackerEvent(int instanceId, GameObjectChangeTrackerEventType eventType) { InstanceId = instanceId; EventType = eventType; } public GameObjectChangeTrackerEvent(GameObjectChangeTrackerEventType eventType) { InstanceId = 0; EventType = eventType; } public readonly int InstanceId; public readonly GameObjectChangeTrackerEventType EventType; } [Flags] internal enum GameObjectChangeTrackerEventType : ushort { CreatedOrChanged = 1 << 0, Destroyed = 1 << 1, OrderChanged = 1 << 2, ChangedParent = 1 << 3, ChangedScene = 1 << 4, SceneOrderChanged = 1 << 5 } }
UnityCsReference/Editor/Mono/GameObjectChangeTracker.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GameObjectChangeTracker.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1639 }
308
// 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 UnityEditor; namespace UnityEditorInternal { [NativeHeader("Editor/Mono/GradientPreviewCache.bindings.h")] internal partial class GradientPreviewCache { public static extern Texture2D GenerateGradientPreview(Gradient gradient, Texture2D existingTexture, bool linearGradientKeys); [StaticAccessor("GradientPreviewCache::Get()", StaticAccessorType.Dot)] public static extern void ClearCache(); [FreeFunction("GradientPreviewCache_GetPreview_Internal<SerializedProperty>")] public static extern Texture2D GetPropertyPreview(SerializedProperty property, bool linearGradientKeys); [FreeFunction("GradientPreviewCache_GetPreview_Internal<Gradient>")] public static extern Texture2D GetGradientPreview(Gradient curve, bool linearGradientKeys); } }
UnityCsReference/Editor/Mono/GradientPreviewCache.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GradientPreviewCache.bindings.cs", "repo_id": "UnityCsReference", "token_count": 316 }
309
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; namespace UnityEditor.IMGUI.Controls { public class SphereBoundsHandle : PrimitiveBoundsHandle { [Obsolete("Use parameterless constructor instead.")] public SphereBoundsHandle(int controlIDHint) : base(controlIDHint) {} public SphereBoundsHandle() : base() {} public float radius { get { Vector3 size = GetSize(); float diameter = 0f; for (int axis = 0; axis < 3; ++axis) { // only consider size values on enabled axes if (IsAxisEnabled(axis)) diameter = Mathf.Max(diameter, Mathf.Abs(size[axis])); } return diameter * 0.5f; } set { SetSize(2f * value * Vector3.one); } } protected override void DrawWireframe() { bool x = IsAxisEnabled(Axes.X); bool y = IsAxisEnabled(Axes.Y); bool z = IsAxisEnabled(Axes.Z); if (x && y) Handles.DrawWireArc(center, Vector3.forward, Vector3.up, 360f, radius); if (x && z) Handles.DrawWireArc(center, Vector3.up, Vector3.right, 360f, radius); if (y && z) Handles.DrawWireArc(center, Vector3.right, Vector3.forward, 360f, radius); if (x && !y && !z) Handles.DrawLine(Vector3.right * radius, Vector3.left * radius); if (!x && y && !z) Handles.DrawLine(Vector3.up * radius, Vector3.down * radius); if (!x && !y && z) Handles.DrawLine(Vector3.forward * radius, Vector3.back * radius); } protected override Bounds OnHandleChanged(HandleDirection handle, Bounds boundsOnClick, Bounds newBounds) { Vector3 upperBound = newBounds.max; Vector3 lowerBound = newBounds.min; // ensure radius changes uniformly int changedAxis = 0; switch (handle) { case HandleDirection.NegativeY: case HandleDirection.PositiveY: changedAxis = 1; break; case HandleDirection.NegativeZ: case HandleDirection.PositiveZ: changedAxis = 2; break; } float rad = 0.5f * (upperBound[changedAxis] - lowerBound[changedAxis]); for (int axis = 0; axis < 3; ++axis) { if (axis == changedAxis) continue; lowerBound[axis] = center[axis] - rad; upperBound[axis] = center[axis] + rad; } return new Bounds((upperBound + lowerBound) * 0.5f, upperBound - lowerBound); } } }
UnityCsReference/Editor/Mono/Handles/BoundsHandle/SphereBoundsHandle.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Handles/BoundsHandle/SphereBoundsHandle.cs", "repo_id": "UnityCsReference", "token_count": 1544 }
310
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditorInternal; using UnityEngine; namespace UnityEditor { public sealed partial class Handles { internal static float DoSimpleEdgeHandle(Quaternion rotation, Vector3 position, float radius, bool editable = true) { if (Event.current.alt) editable = false; Vector3 right = rotation * Vector3.right; if (editable) { // Radius handles at ends EditorGUI.BeginChangeCheck(); radius = SizeSlider(position, right, radius); radius = SizeSlider(position, -right, radius); if (EditorGUI.EndChangeCheck()) radius = Mathf.Max(0.0f, radius); } // Draw gizmo if (radius > 0) DrawLine(position - right * radius, position + right * radius); return radius; } internal static float DoSimpleRadiusHandle(Quaternion rotation, Vector3 position, float radius, bool hemisphere, float arc = 360.0f, bool editable = true) { if (Event.current.alt) editable = false; Vector3 forward = rotation * Vector3.forward; Vector3 up = rotation * Vector3.up; Vector3 right = rotation * Vector3.right; if (editable) { // Radius handle in zenith bool temp = GUI.changed; GUI.changed = false; radius = SizeSlider(position, forward, radius); if (!hemisphere) radius = SizeSlider(position, -forward, radius); if (GUI.changed) radius = Mathf.Max(0.0f, radius); GUI.changed |= temp; // Radius handles at disc temp = GUI.changed; GUI.changed = false; radius = SizeSlider(position, right, radius); if (arc >= 90.0f) radius = SizeSlider(position, up, radius); if (arc >= 180.0f) radius = SizeSlider(position, -right, radius); if (arc >= 270.0f) radius = SizeSlider(position, -up, radius); if (GUI.changed) radius = Mathf.Max(0.0f, radius); GUI.changed |= temp; } // Draw gizmo if (radius > 0) { DrawWireArc(position, forward, right, arc, radius); DrawWireArc(position, up, forward, hemisphere ? 90 : 180, radius); for (int quarter = 0; quarter < 4; quarter++) { if (arc >= (90.0f * quarter)) { Vector3 normal = Matrix4x4.Rotate(Quaternion.Euler(0.0f, 0.0f, 90.0f * quarter)) * up; DrawWireArc(position, normal, forward, hemisphere ? 90 : 180, radius); } } Vector3 capNormal = Matrix4x4.Rotate(Quaternion.Euler(0.0f, 0.0f, arc)) * up; DrawWireArc(position, capNormal, forward, hemisphere ? 90 : 180, radius); } return radius; } // static void DrawHemispherePeriphery (Vector3 position, float radius) // { // Vector3 planeNormal = position - Camera.current.transform.position; // vector from camera to center // float sqrDist = planeNormal.sqrMagnitude; // squared distance from camera to center // float sqrRadius = radius * radius; // squared radius // float sqrOffset = sqrRadius * sqrRadius / sqrDist; // squared distance from actual center to drawn disc center // float insideAmount = sqrOffset / sqrRadius; // // // If we are not inside the sphere, calculate where to draw the periphery // if (insideAmount < 1) // { // float drawnRadius = Mathf.Sqrt(sqrRadius - sqrOffset); // the radius of the drawn disc // // // Draw periphery circle // Vector3 tangent = Vector3.Cross(planeNormal, Vector3.up); // if (tangent.sqrMagnitude < .001f) // tangent = Vector3.Cross(planeNormal, Vector3.right); // DrawWireArc(position - sqrRadius * planeNormal / sqrDist, planeNormal, tangent, -180, drawnRadius); // } // } } }
UnityCsReference/Editor/Mono/Handles/SimpleRadiusHandle.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Handles/SimpleRadiusHandle.cs", "repo_id": "UnityCsReference", "token_count": 2282 }
311
// 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 ICleanuppable { void Cleanup(); } }
UnityCsReference/Editor/Mono/ICleanuppable.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/ICleanuppable.cs", "repo_id": "UnityCsReference", "token_count": 86 }
312
// 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; using System; using System.Collections.Generic; internal class ImportSettingInternalID { static public void RegisterInternalID(SerializedObject serializedObject, UnityType type, long id, string name) { SerializedProperty internalIDMap = serializedObject.FindProperty("m_InternalIDToNameTable"); internalIDMap.arraySize++; SerializedProperty newEntry = internalIDMap.GetArrayElementAtIndex(internalIDMap.arraySize - 1); SerializedProperty first = newEntry.FindPropertyRelative("first"); SerializedProperty cid = first.FindPropertyRelative("first"); SerializedProperty lid = first.FindPropertyRelative("second"); cid.intValue = type.persistentTypeID; lid.longValue = id; SerializedProperty sname = newEntry.FindPropertyRelative("second"); sname.stringValue = name; } static public void RegisterInternalID(SerializedObject serializedObject, UnityType type, ICollection<long> ids, ICollection<string> names) { if (ids.Count != names.Count) return; SerializedProperty internalIDMap = serializedObject.FindProperty("m_InternalIDToNameTable"); var startIdx = internalIDMap.arraySize; internalIDMap.arraySize += ids.Count; var id = ids.GetEnumerator(); id.Reset(); id.MoveNext(); var name = names.GetEnumerator(); name.Reset(); name.MoveNext(); if (internalIDMap.arraySize > 0) { SerializedProperty newEntry = internalIDMap.GetArrayElementAtIndex(startIdx); for (int i = 0; i < ids.Count; ++i, id.MoveNext(), name.MoveNext()) { SerializedProperty first = newEntry.FindPropertyRelative("first"); SerializedProperty cid = first.FindPropertyRelative("first"); SerializedProperty lid = first.FindPropertyRelative("second"); cid.intValue = type.persistentTypeID; lid.longValue = id.Current; SerializedProperty sname = newEntry.FindPropertyRelative("second"); sname.stringValue = name.Current; newEntry.Next(false); } } } static public bool RemoveEntryFromInternalIDTable(SerializedObject serializedObject, UnityType type, long id, string name) { int classID = type.persistentTypeID; SerializedProperty internalIDMap = serializedObject.FindProperty("m_InternalIDToNameTable"); bool found = false; int index = 0; foreach (SerializedProperty element in internalIDMap) { SerializedProperty first = element.FindPropertyRelative("first"); SerializedProperty cid = first.FindPropertyRelative("first"); if (cid.intValue == classID) { SerializedProperty second = element.FindPropertyRelative("second"); SerializedProperty lid = first.FindPropertyRelative("second"); string foundName = second.stringValue; long localid = lid.longValue; if (foundName == name && localid == id) { found = true; internalIDMap.DeleteArrayElementAtIndex(index); return found; } } index++; } return found; } static public long FindInternalID(SerializedObject serializedObject, UnityType type, string name) { long id = 0; SerializedProperty internalIDMap = serializedObject.FindProperty("m_InternalIDToNameTable"); foreach (SerializedProperty element in internalIDMap) { SerializedProperty first = element.FindPropertyRelative("first"); SerializedProperty cid = first.FindPropertyRelative("first"); if (cid.intValue == type.persistentTypeID) { SerializedProperty second = element.FindPropertyRelative("second"); if (second.stringValue == name) { SerializedProperty lid = first.FindPropertyRelative("second"); id = lid.longValue; return id; } } } return id; } static public long MakeInternalID(SerializedObject serializedObject, UnityType type, string name) { long id = ImportSettingInternalID.FindInternalID(serializedObject, type, name); if (id == 0L) { id = AssetImporter.MakeLocalFileIDWithHash(type.persistentTypeID, name, 0); RegisterInternalID(serializedObject, type, id, name); } return id; } static public void Rename(SerializedObject serializedObject, UnityType type, string oldName, string newName) { RenameMultiple(serializedObject, type, new string[] { oldName }, new string[] { newName }); } // Rename multiple entries at once to avoid situations where swapping names of two entries would break references static public void RenameMultiple(SerializedObject serializedObject, UnityType type, string[] oldNames, string[] newNames) { int classID = type.persistentTypeID; int left = oldNames.Length; SerializedProperty recycleMap = serializedObject.FindProperty("m_InternalIDToNameTable"); foreach (SerializedProperty element in recycleMap) { SerializedProperty first = element.FindPropertyRelative("first"); SerializedProperty cid = first.FindPropertyRelative("first"); if (cid.intValue == classID) { SerializedProperty second = element.FindPropertyRelative("second"); int idx = Array.IndexOf(oldNames, second.stringValue); if (idx >= 0) { second.stringValue = newNames[idx]; if (--left == 0) break; } } } } }
UnityCsReference/Editor/Mono/ImportSettings/ImportSettingsInternalID.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/ImportSettings/ImportSettingsInternalID.cs", "repo_id": "UnityCsReference", "token_count": 2581 }
313
// 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(AudioChorusFilter))] class AudioChorusFilterEditor : Editor { private SerializedProperty m_DryMix; private SerializedProperty m_WetMix1; private SerializedProperty m_WetMix2; private SerializedProperty m_WetMix3; private SerializedProperty m_Delay; private SerializedProperty m_Rate; private SerializedProperty m_Depth; private static class Styles { public static readonly GUIContent DryMixTooltip = EditorGUIUtility.TrTextContent("Dry Mix", "Volume of original signal to pass to output"); public static readonly GUIContent WetMix1Tooltip = EditorGUIUtility.TrTextContent("Wet Mix 1", "Volume of 1st chorus tap"); public static readonly GUIContent WetMix2Tooltip = EditorGUIUtility.TrTextContent("Wet Mix 2", "Volume of 2nd chorus tap"); public static readonly GUIContent WetMix3Tooltip = EditorGUIUtility.TrTextContent("Wet Mix 3", "Volume of 3rd chorus tap"); public static readonly GUIContent DelayTooltip = EditorGUIUtility.TrTextContent("Delay", "Chorus delay in ms"); public static readonly GUIContent RateTooltip = EditorGUIUtility.TrTextContent("Rate", "Chorus modulation rate in hz"); public static readonly GUIContent DepthTooltip = EditorGUIUtility.TrTextContent("Depth", "Chorus modulation depth"); } private void OnEnable() { m_DryMix = serializedObject.FindProperty("m_DryMix"); m_WetMix1 = serializedObject.FindProperty("m_WetMix1"); m_WetMix2 = serializedObject.FindProperty("m_WetMix2"); m_WetMix3 = serializedObject.FindProperty("m_WetMix3"); m_Delay = serializedObject.FindProperty("m_Delay"); m_Rate = serializedObject.FindProperty("m_Rate"); m_Depth = serializedObject.FindProperty("m_Depth"); } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUILayout.PropertyField(m_DryMix, Styles.DryMixTooltip); EditorGUILayout.PropertyField(m_WetMix1, Styles.WetMix1Tooltip); EditorGUILayout.PropertyField(m_WetMix2, Styles.WetMix2Tooltip); EditorGUILayout.PropertyField(m_WetMix3, Styles.WetMix3Tooltip); EditorGUILayout.PropertyField(m_Delay, Styles.DelayTooltip); EditorGUILayout.PropertyField(m_Rate, Styles.RateTooltip); EditorGUILayout.PropertyField(m_Depth, Styles.DepthTooltip); serializedObject.ApplyModifiedProperties(); } } }
UnityCsReference/Editor/Mono/Inspector/AudioChorusFilterEditor.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/AudioChorusFilterEditor.cs", "repo_id": "UnityCsReference", "token_count": 1126 }
314
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEditor; using System; using System.Collections; using System.Collections.Generic; using UnityEditorInternal; using System.Linq; using Object = UnityEngine.Object; namespace UnityEditor { internal class AvatarBipedMapper { private struct BipedBone { public string name; public int index; public BipedBone(string name, int index) { this.name = name; this.index = index; } } private static BipedBone[] s_BipedBones = new BipedBone[] { // body new BipedBone("Pelvis", (int)HumanBodyBones.Hips), new BipedBone("L Thigh", (int)HumanBodyBones.LeftUpperLeg), new BipedBone("R Thigh", (int)HumanBodyBones.RightUpperLeg), new BipedBone("L Calf", (int)HumanBodyBones.LeftLowerLeg), new BipedBone("R Calf", (int)HumanBodyBones.RightLowerLeg), new BipedBone("L Foot", (int)HumanBodyBones.LeftFoot), new BipedBone("R Foot", (int)HumanBodyBones.RightFoot), new BipedBone("Spine", (int)HumanBodyBones.Spine), new BipedBone("Spine1", (int)HumanBodyBones.Chest), new BipedBone("Spine2", (int)HumanBodyBones.UpperChest), new BipedBone("Neck", (int)HumanBodyBones.Neck), new BipedBone("Head", (int)HumanBodyBones.Head), new BipedBone("L Clavicle", (int)HumanBodyBones.LeftShoulder), new BipedBone("R Clavicle", (int)HumanBodyBones.RightShoulder), new BipedBone("L UpperArm", (int)HumanBodyBones.LeftUpperArm), new BipedBone("R UpperArm", (int)HumanBodyBones.RightUpperArm), new BipedBone("L Forearm", (int)HumanBodyBones.LeftLowerArm), new BipedBone("R Forearm", (int)HumanBodyBones.RightLowerArm), new BipedBone("L Hand", (int)HumanBodyBones.LeftHand), new BipedBone("R Hand", (int)HumanBodyBones.RightHand), new BipedBone("L Toe0", (int)HumanBodyBones.LeftToes), new BipedBone("R Toe0", (int)HumanBodyBones.RightToes), // Left Hand new BipedBone("L Finger0", (int)HumanBodyBones.LeftThumbProximal), new BipedBone("L Finger01", (int)HumanBodyBones.LeftThumbIntermediate), new BipedBone("L Finger02", (int)HumanBodyBones.LeftThumbDistal), new BipedBone("L Finger1", (int)HumanBodyBones.LeftIndexProximal), new BipedBone("L Finger11", (int)HumanBodyBones.LeftIndexIntermediate), new BipedBone("L Finger12", (int)HumanBodyBones.LeftIndexDistal), new BipedBone("L Finger2", (int)HumanBodyBones.LeftMiddleProximal), new BipedBone("L Finger21", (int)HumanBodyBones.LeftMiddleIntermediate), new BipedBone("L Finger22", (int)HumanBodyBones.LeftMiddleDistal), new BipedBone("L Finger3", (int)HumanBodyBones.LeftRingProximal), new BipedBone("L Finger31", (int)HumanBodyBones.LeftRingIntermediate), new BipedBone("L Finger32", (int)HumanBodyBones.LeftRingDistal), new BipedBone("L Finger4", (int)HumanBodyBones.LeftLittleProximal), new BipedBone("L Finger41", (int)HumanBodyBones.LeftLittleIntermediate), new BipedBone("L Finger42", (int)HumanBodyBones.LeftLittleDistal), // Right Hand new BipedBone("R Finger0", (int)HumanBodyBones.RightThumbProximal), new BipedBone("R Finger01", (int)HumanBodyBones.RightThumbIntermediate), new BipedBone("R Finger02", (int)HumanBodyBones.RightThumbDistal), new BipedBone("R Finger1", (int)HumanBodyBones.RightIndexProximal), new BipedBone("R Finger11", (int)HumanBodyBones.RightIndexIntermediate), new BipedBone("R Finger12", (int)HumanBodyBones.RightIndexDistal), new BipedBone("R Finger2", (int)HumanBodyBones.RightMiddleProximal), new BipedBone("R Finger21", (int)HumanBodyBones.RightMiddleIntermediate), new BipedBone("R Finger22", (int)HumanBodyBones.RightMiddleDistal), new BipedBone("R Finger3", (int)HumanBodyBones.RightRingProximal), new BipedBone("R Finger31", (int)HumanBodyBones.RightRingIntermediate), new BipedBone("R Finger32", (int)HumanBodyBones.RightRingDistal), new BipedBone("R Finger4", (int)HumanBodyBones.RightLittleProximal), new BipedBone("R Finger41", (int)HumanBodyBones.RightLittleIntermediate), new BipedBone("R Finger42", (int)HumanBodyBones.RightLittleDistal) }; public static bool IsBiped(Transform root, List<string> report) { if (report != null) { report.Clear(); } Transform[] humanToTransform = new Transform[HumanTrait.BoneCount]; return MapBipedBones(root, ref humanToTransform, report); } public static Dictionary<int, Transform> MapBones(Transform root) { Dictionary<int, Transform> ret = new Dictionary<int, Transform>(); Transform[] humanToTransform = new Transform[HumanTrait.BoneCount]; if (MapBipedBones(root, ref humanToTransform, null)) { for (int boneIter = 0; boneIter < HumanTrait.BoneCount; boneIter++) { if (humanToTransform[boneIter] != null) { ret.Add(boneIter, humanToTransform[boneIter]); } } } // Move upper chest to chest if no chest was found if (!ret.ContainsKey((int)HumanBodyBones.Chest) && ret.ContainsKey((int)HumanBodyBones.UpperChest)) { ret.Add((int)HumanBodyBones.Chest, ret[(int)HumanBodyBones.UpperChest]); ret.Remove((int)HumanBodyBones.UpperChest); } return ret; } private static bool MapBipedBones(Transform root, ref Transform[] humanToTransform, List<string> report) { for (int bipedBoneIter = 0; bipedBoneIter < s_BipedBones.Length; bipedBoneIter++) { int boneIndex = s_BipedBones[bipedBoneIter].index; int parentIndex = HumanTrait.GetParentBone(boneIndex); bool required = HumanTrait.RequiredBone(boneIndex); bool parentRequired = parentIndex != -1 ? HumanTrait.RequiredBone(parentIndex) : true; Transform parentTransform = parentIndex != -1 ? humanToTransform[parentIndex] : root; if (parentTransform == null && !parentRequired) { parentIndex = HumanTrait.GetParentBone(parentIndex); parentRequired = parentIndex != -1 ? HumanTrait.RequiredBone(parentIndex) : true; parentTransform = parentIndex != -1 ? humanToTransform[parentIndex] : null; if (parentTransform == null && !parentRequired) { parentIndex = HumanTrait.GetParentBone(parentIndex); parentTransform = parentIndex != -1 ? humanToTransform[parentIndex] : null; } } humanToTransform[boneIndex] = MapBipedBone(bipedBoneIter, parentTransform, parentTransform, report); if (humanToTransform[boneIndex] == null && required) { return false; } } return true; } private static Transform MapBipedBone(int bipedBoneIndex, Transform transform, Transform parentTransform, List<string> report) { Transform ret = null; if (transform != null) { int childCount = transform.childCount; for (int childIter = 0; ret == null && childIter < childCount; childIter++) { string boneName = s_BipedBones[bipedBoneIndex].name; int boneIndex = s_BipedBones[bipedBoneIndex].index; if (transform.GetChild(childIter).name.EndsWith(boneName)) { ret = transform.GetChild(childIter); if (ret != null && report != null && boneIndex != (int)HumanBodyBones.Hips && transform != parentTransform) { string current = "- Invalid parent for " + ret.name + ". Expected " + parentTransform.name + ", but found " + transform.name + "."; if (boneIndex == (int)HumanBodyBones.LeftUpperLeg || boneIndex == (int)HumanBodyBones.RightUpperLeg) { current += " Disable Triangle Pelvis"; } else if (boneIndex == (int)HumanBodyBones.LeftShoulder || boneIndex == (int)HumanBodyBones.RightShoulder) { current += " Enable Triangle Neck"; } else if (boneIndex == (int)HumanBodyBones.Neck) { current += " Preferred is three Spine Links"; } else if (boneIndex == (int)HumanBodyBones.Head) { current += " Preferred is one Neck Links"; } current += "\n"; report.Add(current); } } } for (int childIter = 0; ret == null && childIter < childCount; childIter++) { ret = MapBipedBone(bipedBoneIndex, transform.GetChild(childIter), parentTransform, report); } } return ret; } internal static void BipedPose(GameObject go, AvatarSetupTool.BoneWrapper[] bones) { BipedPose(go.transform, true); // Orient Biped Quaternion rot = AvatarSetupTool.AvatarComputeOrientation(bones); go.transform.rotation = Quaternion.Inverse(rot) * go.transform.rotation; // Move Biped feet to ground plane AvatarSetupTool.MakeCharacterPositionValid(bones); } private static void BipedPose(Transform t, bool ignore) { if (t.name.EndsWith("Pelvis")) { t.localRotation = Quaternion.Euler(270, 90, 0); ignore = false; } else if (t.name.EndsWith("Thigh")) { t.localRotation = Quaternion.Euler(0, 180, 0); } else if (t.name.EndsWith("Toe0")) { t.localRotation = Quaternion.Euler(0, 0, 270); } else if (t.name.EndsWith("L Clavicle")) { t.localRotation = Quaternion.Euler(0, 270, 180); } else if (t.name.EndsWith("R Clavicle")) { t.localRotation = Quaternion.Euler(0, 90, 180); } else if (t.name.EndsWith("L Hand")) { t.localRotation = Quaternion.Euler(270, 0, 0); } else if (t.name.EndsWith("R Hand")) { t.localRotation = Quaternion.Euler(90, 0, 0); } else if (t.name.EndsWith("L Finger0")) { t.localRotation = Quaternion.Euler(0, 315, 0); } else if (t.name.EndsWith("R Finger0")) { t.localRotation = Quaternion.Euler(0, 45, 0); } else if (!ignore) { t.localRotation = Quaternion.identity; } foreach (Transform child in t) { BipedPose(child, ignore); } } } }
UnityCsReference/Editor/Mono/Inspector/Avatar/AvatarBipedMapper.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/Avatar/AvatarBipedMapper.cs", "repo_id": "UnityCsReference", "token_count": 6379 }
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 UnityEditor.Overlays; using UnityEngine; using UnityEngine.UIElements; using static UnityEditor.CameraPreviewUtils; namespace UnityEditor { // marked obsolete @thomastu 2023/04/05 [Obsolete("This Overlay is obsolete. Use the global Cameras Overlay instead.", false)] [Overlay(id = k_OverlayID, displayName = k_DisplayName, defaultDisplay = true)] [Icon("Icons/Overlays/CameraPreview.png")] class SceneViewCameraOverlay : IMGUIOverlay { internal static bool forceDisable = false; // should match color in GizmosDrawers.cpp const float kPreviewNormalizedSize = 0.2f; const string k_OverlayID = "Scene View/Camera"; const string k_DisplayName = "Camera Preview"; Camera m_SelectedCamera; Camera selectedCamera => m_SelectedCamera; static Dictionary<Camera, (SceneViewCameraOverlay overlay, int count)> s_CameraOverlays = new Dictionary<Camera, (SceneViewCameraOverlay, int)>(); SceneViewCameraOverlay(Camera camera) { minSize = new Vector2(40, 40); maxSize = new Vector2(4000, 4000); defaultSize = new Vector2(240, 135); m_SelectedCamera = camera; displayName = selectedCamera == null || string.IsNullOrEmpty(selectedCamera.name) ? "Camera Preview" : selectedCamera.name; s_CameraOverlays.Add(camera, (this ,1)); } public static SceneViewCameraOverlay GetOrCreateCameraOverlay(Camera camera) { if (s_CameraOverlays.ContainsKey(camera)) { var value = s_CameraOverlays[camera]; value.count += 1; s_CameraOverlays[camera] = value; return value.overlay; } var overlay = new SceneViewCameraOverlay(camera); SceneView.AddOverlayToActiveView(overlay); return overlay; } public static void DisableCameraOverlay(Camera cam) { if (s_CameraOverlays.ContainsKey(cam)) { var value = s_CameraOverlays[cam]; value.count -= 1; if (value.count == 0) { s_CameraOverlays.Remove(cam); SceneView.RemoveOverlayFromActiveView(value.overlay); } else s_CameraOverlays[cam] = value; } } void UpdateSize() { if (!sizeOverridden) size = new Vector2(240, 135); } public override void OnGUI() { if (selectedCamera == null) { GUILayout.Label("No camera selected", EditorStyles.centeredGreyMiniLabel); return; } if (!CameraEditorUtils.IsViewportRectValidToRender(selectedCamera.rect)) return; imguiContainer.style.flexGrow = 1; var sceneView = SceneView.lastActiveSceneView; // Do not render the Camera Preview overlay if the target camera GameObject is not part of the objects the // SceneView is rendering if (!sceneView.IsGameObjectInThisSceneView(selectedCamera.gameObject)) return; var cameraRect = imguiContainer.rect; cameraRect.width = Mathf.Floor(cameraRect.width); if (cameraRect.width < 1 || cameraRect.height < 1 || float.IsNaN(cameraRect.width) || float.IsNaN(cameraRect.height)) return; if (Event.current.type == EventType.Repaint) { Graphics.DrawTexture(cameraRect, Texture2D.whiteTexture, new Rect(0, 0, 1, 1), 0, 0, 0, 0, Color.black); Vector2 previewSize = selectedCamera.targetTexture ? new Vector2(selectedCamera.targetTexture.width, selectedCamera.targetTexture.height) : PlayModeView.GetMainPlayModeViewTargetSize(); if (previewSize.x < 0f) { // Fallback to Scene View of not a valid game view size previewSize.x = sceneView.position.width; previewSize.y = sceneView.position.height; } float rectAspect = cameraRect.width / cameraRect.height; float previewAspect = previewSize.x / previewSize.y; Rect previewRect = cameraRect; if (rectAspect > previewAspect) { float stretch = previewAspect / rectAspect; previewRect = new Rect(cameraRect.xMin + cameraRect.width * (1.0f - stretch) * .5f, cameraRect.yMin, stretch * cameraRect.width, cameraRect.height); } else { float stretch = rectAspect / previewAspect; previewRect = new Rect(cameraRect.xMin, cameraRect.yMin + cameraRect.height * (1.0f - stretch) * .5f, cameraRect.width, stretch * cameraRect.height); } var settings = new PreviewSettings(new Vector2((int)previewRect.width, (int)previewRect.height)); settings.overrideSceneCullingMask = sceneView.overrideSceneCullingMask; settings.scene = sceneView.customScene; var previewTexture = CameraPreviewUtils.GetPreview(selectedCamera, settings); Graphics.DrawTexture(previewRect, previewTexture, new Rect(0, 0, 1, 1), 0, 0, 0, 0, GUI.color, EditorGUIUtility.GUITextureBlit2SRGBMaterial); } } } }
UnityCsReference/Editor/Mono/Inspector/CameraOverlay.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/CameraOverlay.cs", "repo_id": "UnityCsReference", "token_count": 2684 }
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.Linq; using UnityEditor.StyleSheets; using UnityEngine; using Event = UnityEngine.Event; namespace UnityEditor.IMGUI.Controls { internal class AdvancedDropdownGUI { private static class Styles { public static GUIStyle itemStyle = "DD ItemStyle"; public static GUIStyle header = "DD HeaderStyle"; public static GUIStyle checkMark = "DD ItemCheckmark"; public static GUIStyle lineSeparator = "DefaultLineSeparator"; public static GUIStyle rightArrow = "ArrowNavigationRight"; public static GUIStyle leftArrow = "ArrowNavigationLeft"; public static GUIStyle searchFieldStyle = new GUIStyle(EditorStyles.toolbarSearchField) { margin = new RectOffset(5, 4, 4, 5) }; public static SVC<Color> searchBackgroundColor = new SVC<Color>("--theme-toolbar-background-color", Color.black); public static GUIContent checkMarkContent = new GUIContent("✔"); } internal static void LoadStyles() { Debug.Assert(Event.current.type == EventType.Repaint && Styles.itemStyle != null); } public static string k_SearchFieldName = "ComponentSearch"; //This should ideally match line height private Vector2 s_IconSize = new Vector2(13, 13); private AdvancedDropdownDataSource m_DataSource; internal Rect m_SearchRect; internal Rect m_HeaderRect; internal Rect areaRect { get; set; } internal virtual float searchHeight => m_SearchRect.height; internal virtual float headerHeight => m_HeaderRect.height; internal virtual GUIStyle lineStyle => Styles.itemStyle; internal virtual Vector2 iconSize => s_IconSize; internal AdvancedDropdownState state { get; set; } public AdvancedDropdownGUI(AdvancedDropdownDataSource dataSource) { m_DataSource = dataSource; } internal virtual void DrawItem(AdvancedDropdownItem item, string name, Texture2D icon, bool enabled, bool drawArrow, bool selected, bool hasSearch) { var content = item.content; // We need to pretend we have an icon to calculate proper width in case var lastContentImage = content.image; if (content.image == null) content.image = Texture2D.whiteTexture; // Clamp the rect width var rect = GetItemRect(content); var maxWidth = areaRect.width - GUI.skin.verticalScrollbar.fixedWidth; // todo: find a way to detect if we have a scrollbar if (drawArrow) maxWidth -= Styles.rightArrow.fixedWidth + Styles.rightArrow.margin.right; if (maxWidth > 0) rect.width = Math.Min(rect.width, maxWidth); content.image = lastContentImage; if (!string.IsNullOrEmpty(content.tooltip) && rect.Contains(Event.current.mousePosition) && !string.Equals(content.tooltip, content.text, StringComparison.Ordinal)) GUIStyle.SetMouseTooltip(content.tooltip, rect); if (Event.current.type != EventType.Repaint) return; lastContentImage = content.image; if (m_DataSource.selectedIDs.Any() && m_DataSource.selectedIDs.Contains(item.id)) { var checkMarkRect = new Rect(rect); checkMarkRect.width = iconSize.x + 1; Styles.checkMark.Draw(checkMarkRect, Styles.checkMarkContent, false, false, selected, selected); rect.x += iconSize.x + 1; rect.width -= iconSize.x + 1; // Don't draw the icon if the check mark is present content.image = null; } else if (content.image == null) { lineStyle.Draw(rect, GUIContent.none, false, false, selected, selected); rect.x += iconSize.x + 1; rect.width -= iconSize.x + 1; } EditorGUI.BeginDisabled(!enabled); var lastStyleClipping = lineStyle.clipping; lineStyle.clipping = TextClipping.Ellipsis; DrawItemContent(item, rect, content, false, false, selected, selected); lineStyle.clipping = lastStyleClipping; content.image = lastContentImage; if (drawArrow) { var yOffset = (lineStyle.fixedHeight - Styles.rightArrow.fixedHeight) / 2; Rect arrowRect = new Rect( rect.xMax, rect.y + yOffset, Styles.rightArrow.fixedWidth, Styles.rightArrow.fixedHeight); Styles.rightArrow.Draw(arrowRect, false, false, false, false); } EditorGUI.EndDisabled(); } internal virtual void DrawLineSeparator() { var rect = GUILayoutUtility.GetRect(GUIContent.none, Styles.lineSeparator, GUILayout.ExpandWidth(true)); if (Event.current.type != EventType.Repaint) return; Color orgColor = GUI.color; Color tintColor = (EditorGUIUtility.isProSkin) ? new Color(0.12f, 0.12f, 0.12f, 1.333f) : new Color(0.6f, 0.6f, 0.6f, 1.333f); GUI.color = GUI.color * tintColor; GUI.DrawTexture(rect, EditorGUIUtility.whiteTexture); GUI.color = orgColor; } internal void DrawHeader(AdvancedDropdownItem group, Action backButtonPressed, bool hasParent) { var content = group.content; m_HeaderRect = GUILayoutUtility.GetRect(content, Styles.header, GUILayout.ExpandWidth(true), GUILayout.MaxHeight(22)); bool hovered = m_HeaderRect.Contains(Event.current.mousePosition); if (Event.current.type == EventType.Repaint) Styles.header.Draw(m_HeaderRect, content, hovered, false, false, false); // Back button if (hasParent) { var yOffset = (m_HeaderRect.height - Styles.leftArrow.fixedWidth) / 2; var arrowRect = new Rect( m_HeaderRect.x + Styles.leftArrow.margin.left, m_HeaderRect.y + yOffset, Styles.leftArrow.fixedWidth, Styles.leftArrow.fixedHeight); if (Event.current.type == EventType.Repaint) Styles.leftArrow.Draw(arrowRect, false, false, false, false); if (Event.current.type == EventType.MouseDown && hovered) { backButtonPressed(); Event.current.Use(); } } } internal void DrawSearchField(bool isSearchFieldDisabled, string searchString, Action<string> searchChanged) { if (!isSearchFieldDisabled && string.IsNullOrEmpty(GUI.GetNameOfFocusedControl())) { EditorGUI.FocusTextInControl("ComponentSearch"); } using (new EditorGUI.DisabledScope(isSearchFieldDisabled)) { GUI.SetNextControlName(k_SearchFieldName); var newSearch = DrawSearchFieldControl(searchString); if (newSearch != searchString) { searchChanged(newSearch); } } } internal virtual string DrawSearchFieldControl(string searchString) { var controlRect = GUILayoutUtility.GetRect(0, 0, Styles.searchFieldStyle); m_SearchRect = CalculateSearchRect(ref controlRect); EditorGUI.DrawRect(m_SearchRect, Styles.searchBackgroundColor); var newSearch = EditorGUI.ToolbarSearchField(controlRect, searchString, false); return newSearch; } Rect CalculateSearchRect(ref Rect controlRect) { const float kBorderWidth = 1f; controlRect.height = Styles.searchFieldStyle.fixedHeight; controlRect.xMin += kBorderWidth; controlRect.xMax -= kBorderWidth; controlRect.yMin += kBorderWidth; return Styles.searchFieldStyle.margin.Add(controlRect); } internal Rect GetAnimRect(Rect position, float anim) { // Calculate rect for animated area var rect = new Rect(position); rect.x = position.x + position.width * anim; rect.y += searchHeight; rect.height -= searchHeight; return rect; } internal Vector2 CalculateContentSize(AdvancedDropdownDataSource dataSource) { float maxWidth = 0; float maxHeight = 0; bool includeArrow = false; float arrowWidth = Styles.rightArrow.fixedWidth; foreach (var child in dataSource.mainTree.children) { var content = child.content; var a = CalcItemSize(content); a.x += iconSize.x + 1; if (maxWidth < a.x) { maxWidth = a.x + 1; includeArrow |= child.children.Any(); } if (child.IsSeparator()) { maxHeight += Styles.lineSeparator.CalcHeight(content, maxWidth) + Styles.lineSeparator.margin.vertical; } else { maxHeight += CalcItemHeight(content, maxWidth); } } if (includeArrow) { maxWidth += arrowWidth; } // other size calculations may rely on m_HeaderRect and m_SearchRect, which wont be populated until the first time they are drawn // so they need to be calculated here if needed. if (m_HeaderRect == default(Rect)) { var headerContent = GUIContent.Temp(dataSource.mainTree.name, dataSource.mainTree.icon); var headerSize = Styles.header.CalcSize(headerContent); if (maxWidth > headerSize.x) headerSize.x = maxWidth; headerSize.y = Styles.header.CalcHeight(headerContent, maxWidth); m_HeaderRect = new Rect(0, 0, headerSize.x, headerSize.y); } if (m_SearchRect == default(Rect)) { var controlRectSize = Styles.searchFieldStyle.CalcSize(GUIContent.none); controlRectSize.x = maxWidth; var controlRect = new Rect(0, 0, controlRectSize.x, controlRectSize.y); m_SearchRect = CalculateSearchRect(ref controlRect); } return new Vector2(maxWidth, maxHeight); } internal float GetSelectionHeight(AdvancedDropdownDataSource dataSource, Rect buttonRect) { if (state.GetSelectedIndex(dataSource.mainTree) == -1) return 0; float heigth = 0; for (int i = 0; i < dataSource.mainTree.children.Count(); i++) { var child = dataSource.mainTree.children.ElementAt(i); var content = child.content; if (state.GetSelectedIndex(dataSource.mainTree) == i) { var diff = (CalcItemHeight(content, 0) - buttonRect.height) / 2f; return heigth + diff; } if (child.IsSeparator()) { heigth += Styles.lineSeparator.CalcHeight(content, 0) + Styles.lineSeparator.margin.vertical; } else { heigth += CalcItemHeight(content, 0); } } return heigth; } internal virtual Rect GetItemRect(in GUIContent content) { return GUILayoutUtility.GetRect(content, lineStyle, GUILayout.ExpandWidth(true)); } internal virtual float CalcItemHeight(GUIContent content, float width) { return lineStyle.CalcHeight(content, width); } internal virtual Vector2 CalcItemSize(GUIContent content) { return lineStyle.CalcSize(content); } internal virtual void DrawItemContent(AdvancedDropdownItem item, Rect rect, GUIContent content, bool isHover, bool isActive, bool on, bool hasKeyboardFocus) { lineStyle.Draw(rect, content, isHover, isActive, on, hasKeyboardFocus); } } }
UnityCsReference/Editor/Mono/Inspector/Core/AdvancedDropdown/AdvancedDropdownGUI.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/Core/AdvancedDropdown/AdvancedDropdownGUI.cs", "repo_id": "UnityCsReference", "token_count": 6031 }
317
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor { internal class PreviewWindow : InspectorWindow { [SerializeField] private InspectorWindow m_ParentInspectorWindow; VisualElement m_previewElement; VisualElement previewElement => m_previewElement ?? (m_previewElement = rootVisualElement.Q(className: "unity-inspector-preview")); internal bool IsFloatingWindow => parent is { window.rootView: not null, window.showMode: not ShowMode.MainWindow }; private readonly string k_PreviewName = "preview-container"; internal override BindingLogLevel defaultBindingLogLevel => BindingLogLevel.None; public void SetParentInspector(InspectorWindow inspector) { m_ParentInspectorWindow = inspector; // Create tracker after parent inspector window has been set (case 829182, 846156) CreateTracker(); } // It's important to NOT call the base.OnDestroy() here! // The InspectorWindow.OnDestroy() deletes the tracker if we are not using the // shared tracker. This makes sense when we are an InspectorWindow about to die, // but it does not make sense when we are a PreviewWindow sharing this tracker with // a perfectly not dead InspectorWindow. Killing the tracker used by a still-alive // InspectorWindow cause many problems. // case 1119612 protected override void OnDestroy() {} protected override void OnEnable() { titleContent = EditorGUIUtility.TrTextContent("Preview"); minSize = new Vector2(260, 220); AddInspectorWindow(this); var tpl = EditorGUIUtility.Load("UXML/InspectorWindow/PreviewWindow.uxml") as VisualTreeAsset; var container = tpl.Instantiate(); container.AddToClassList(s_MainContainerClassName); rootVisualElement.hierarchy.Add(container); rootVisualElement.AddStyleSheetPath("StyleSheets/InspectorWindow/PreviewWindow.uss"); RebuildContentsContainers(); } protected override void OnDisable() { base.OnDisable(); if (m_ParentInspectorWindow != null && GetInspectors().Contains(m_ParentInspectorWindow)) { m_ParentInspectorWindow.hasFloatingPreviewWindow = false; m_ParentInspectorWindow.RebuildContentsContainers(); } } protected override void CreateTracker() { if (m_ParentInspectorWindow != null) m_Tracker = m_ParentInspectorWindow.tracker; else if (m_Tracker == null) base.CreateTracker(); } internal override Editor GetLastInteractedEditor() { if (m_ParentInspectorWindow == null) return null; return m_ParentInspectorWindow.GetLastInteractedEditor(); } internal override void RebuildContentsContainers() { Editor.m_AllowMultiObjectAccess = true; var preview = previewElement; preview.Clear(); CreatePreviewables(); previewWindow = new InspectorPreviewWindow(); IPreviewable[] editorsWithPreviews = GetEditorsWithPreviews(tracker.activeEditors); IPreviewable editor = GetEditorThatControlsPreview(editorsWithPreviews); previewWindow = editor?.CreatePreview(previewWindow) as InspectorPreviewWindow; if (m_ParentInspectorWindow != null && previewWindow != null) { if (previewWindow.childCount == 0) { PrepareToolbar(previewWindow, true); UpdateLabel(previewWindow); VisualElement previewPane = previewWindow.GetPreviewPane(); // IMGUI fallback if (previewPane?.childCount == 0) { previewPane.Add(DrawPreview()); } } SetPreviewStyle(previewWindow); if (preview.Q(k_PreviewName) == null) preview.Add(previewWindow); } else { var container = DrawPreview(true); SetPreviewStyle(container); if (preview.Q(k_PreviewName) == null) preview.Add(container); } } void SetPreviewStyle(VisualElement element) { element.style.flexGrow = 1f; element.style.flexShrink = 0f; element.style.flexBasis = 0f; element.name = k_PreviewName; } IMGUIContainer DrawPreview(bool drawToolbar = false) { return new IMGUIContainer(() => { IPreviewable[] editorsWithPreviews = GetEditorsWithPreviews(tracker.activeEditors); IPreviewable editor = GetEditorThatControlsPreview(editorsWithPreviews); if (drawToolbar) { Rect toolbarRect = EditorGUILayout.BeginHorizontal(GUIContent.none, EditorStyles.toolbar, GUILayout.Height(kBottomToolbarHeight)); { // Label string label = string.Empty; if ((editor != null)) { label = editor.GetPreviewTitle().text; } GUILayout.Label(label, Styles.preToolbarLabel); GUILayout.FlexibleSpace(); if (editor != null && editor.HasPreviewGUI()) editor.OnPreviewSettings(); } EditorGUILayout.EndHorizontal(); } Rect previewPosition = GUILayoutUtility.GetRect(0, 10240, 64, 10240); // Draw background if (Event.current.type == EventType.Repaint) Styles.preBackground.Draw(previewPosition, false, false, false, false); // Draw preview if (editor != null && editor.HasPreviewGUI()) editor.DrawPreview(previewPosition); }); } public override void AddItemsToMenu(GenericMenu menu) { menu.AddItem(EditorGUIUtility.TrTextContent("Dock Preview to Inspector"), false, Close); } protected override void ShowButton(Rect r) {} internal override bool CanMaximize() { /*Since preview window is tightly coupled with Ispector window, maximizing this would destroy inspector * which internally closes all the windows tied with it which in this case would be this window so there * is no point in maximizing a winodw that will be closed as a part of maximizing*/ return false; } } }
UnityCsReference/Editor/Mono/Inspector/Core/PreviewWindow.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/Core/PreviewWindow.cs", "repo_id": "UnityCsReference", "token_count": 3273 }
318
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; namespace UnityEditor { internal class PropertyHandlerCache : IDisposable { internal readonly protected Dictionary<int, PropertyHandler> m_PropertyHandlers = new Dictionary<int, PropertyHandler>(); internal PropertyHandler GetHandler(SerializedProperty property) { PropertyHandler handler; int key = GetPropertyHash(property); if (m_PropertyHandlers.TryGetValue(key, out handler)) return handler; return null; } internal void SetHandler(SerializedProperty property, PropertyHandler handler) { int key = GetPropertyHash(property); m_PropertyHandlers[key] = handler; } internal static bool CanUseSameHandler(SerializedProperty p1, SerializedProperty p2) { return GetPropertyHash(p1) == GetPropertyHash(p2); } private static int GetPropertyHash(SerializedProperty property) { if (property.serializedObject.targetObject == null) return 0; // For efficiency, ignore indices inside brackets [] in order to make array elements share handlers. int key = property.serializedObject.targetObject.GetInstanceID() ^ property.hashCodeForPropertyPathWithoutArrayIndex; if (property.propertyType == SerializedPropertyType.ObjectReference) { key ^= property.objectReferenceInstanceIDValue; } return key; } public void Clear() { if (m_PropertyHandlers.Count > 0) { foreach (var handler in m_PropertyHandlers.Values) { handler.Dispose(); } m_PropertyHandlers.Clear(); } } public void Dispose() => Clear(); } }
UnityCsReference/Editor/Mono/Inspector/Core/Utils/PropertyDrawerCache.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/Core/Utils/PropertyDrawerCache.cs", "repo_id": "UnityCsReference", "token_count": 877 }
319
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; using UnityEditorInternal; using UnityEngine; using UnityEngine.SceneManagement; using UnityEditor.SceneManagement; using UnityObject = UnityEngine.Object; using UnityEditor.Experimental; using System.IO; namespace UnityEditor { [CustomEditor(typeof(GameObject))] [CanEditMultipleObjects] internal class GameObjectInspector : Editor { SerializedProperty m_Name; SerializedProperty m_IsActive; SerializedProperty m_Layer; SerializedProperty m_Tag; SerializedProperty m_StaticEditorFlags; SerializedProperty m_Icon; string m_GOPreviousName; bool m_SerializedObjectInitialized; internal override void PostSerializedObjectCreation() { if (m_SerializedObjectInitialized) { m_Name = serializedObject.FindProperty("m_Name"); m_IsActive = serializedObject.FindProperty("m_IsActive"); m_Layer = serializedObject.FindProperty("m_Layer"); m_Tag = serializedObject.FindProperty("m_TagString"); m_StaticEditorFlags = serializedObject.FindProperty("m_StaticEditorFlags"); m_Icon = serializedObject.FindProperty("m_Icon"); } } static class Styles { public static GUIContent typelessIcon = EditorGUIUtility.IconContent("Prefab Icon"); public static GUIContent overridesContent = EditorGUIUtility.TrTextContent("Overrides"); public static GUIContent staticContent = EditorGUIUtility.TrTextContent("Static", "Enable the checkbox to mark this GameObject as static for all systems.\n\nDisable the checkbox to mark this GameObject as not static for all systems.\n\nUse the drop-down menu to mark as this GameObject as static or not static for individual systems."); public static GUIContent layerContent = EditorGUIUtility.TrTextContent("Layer", "The layer that this GameObject is in.\n\nChoose Add Layer... to edit the list of available layers."); public static GUIContent tagContent = EditorGUIUtility.TrTextContent("Tag", "The tag that this GameObject has.\n\nChoose Untagged to remove the current tag.\n\nChoose Add Tag... to edit the list of available tags."); public static GUIContent staticPreviewContent = EditorGUIUtility.TrTextContent("Static Preview", "This asset is greater than 8MB so, by default, the Asset Preview displays a static preview.\nTo view the asset interactively, click the Asset Preview."); public static float tagFieldWidth = EditorGUI.CalcPrefixLabelWidth(Styles.tagContent, EditorStyles.boldLabel); public static float layerFieldWidth = EditorGUI.CalcPrefixLabelWidth(Styles.layerContent, EditorStyles.boldLabel); public static GUIStyle staticDropdown = "StaticDropdown"; public static GUIStyle tagPopup = new GUIStyle(EditorStyles.popup); public static GUIStyle layerPopup = new GUIStyle(EditorStyles.popup); public static GUIStyle overridesDropdown = new GUIStyle("MiniPullDown"); public static GUIStyle prefabButtonsHorizontalLayout = new GUIStyle { fixedHeight = 17, margin = new RectOffset { top = 1, bottom = 1 } }; public static GUIContent goTypeLabelMultiple = EditorGUIUtility.TrTextContent("Multiple"); private static GUIContent regularPrefab = EditorGUIUtility.TrTextContent("Prefab"); private static GUIContent disconnectedPrefab = EditorGUIUtility.TrTextContent("Prefab", "You have broken the prefab connection. Changes to the prefab will not be applied to this object before you Apply or Revert."); private static GUIContent modelPrefab = EditorGUIUtility.TrTextContent("Prefab"); private static GUIContent disconnectedModelPrefab = EditorGUIUtility.TrTextContent("Prefab", "You have broken the prefab connection. Changes to the model will not be applied to this object before you Revert."); private static GUIContent variantPrefab = EditorGUIUtility.TrTextContent("Prefab"); private static GUIContent disconnectedVariantPrefab = EditorGUIUtility.TrTextContent("Prefab", "You have broken the prefab connection. Changes to the prefab will not be applied to this object before you Apply or Revert."); private static GUIContent missingPrefabAsset = EditorGUIUtility.TrTextContent("Prefab", "The source Prefab or Model has been deleted."); public static GUIContent openModel = EditorGUIUtility.TrTextContent("Open", "Open Model in external tool."); public static GUIContent openPrefab = EditorGUIUtility.TrTextContent("Open", "Open Prefab Asset '{0}'\nPress modifier key [Alt] to open in isolation."); public static GUIContent tooltipForObjectFieldForRootInPrefabContents = EditorGUIUtility.TrTextContent("", "Replacing the root Prefab instance in a Variant is not supported since it will break all overrides for existing instances of this Variant, including their positions and rotations."); public static GUIContent tooltipForObjectFieldForNestedPrefabs = EditorGUIUtility.TrTextContent("", "You can only replace outermost Prefab instances. Open Prefab Mode to replace a nested Prefab instance."); public static string selectString = L10n.Tr("Select"); public static readonly float kIconSize = 24; public static readonly float column1Width = kIconSize + Styles.tagFieldWidth + 10; // Matrix based on two enums: // Columns correspond to PrefabTypeUtility.PrefabAssetType (see comments above rows). // Rows correspond to PrefabTypeUtility.PrefabInstanceStatus (None, Connected, Disconnected, Missing). // If missing, both enums will be "Missing". static public GUIContent[,] goTypeLabel = { // None { null, null, null, null }, // Prefab { regularPrefab, regularPrefab, disconnectedPrefab, null }, // Model { modelPrefab , modelPrefab, disconnectedModelPrefab, null}, // Variant { variantPrefab, variantPrefab, disconnectedVariantPrefab, null }, // Missing { null, null, null, missingPrefabAsset } }; static Styles() { // Seems to be a bug in the way controls with margin internal to layout groups with padding calculate position. We'll work around it here. layerPopup.margin.right = 0; overridesDropdown.margin.right = 0; } } const long kMaxPreviewFileSizeInKB = 8000; // 8 MB class PreviewData : IDisposable { bool m_Disposed; public readonly PreviewRenderUtility renderUtility; public GameObject gameObject { get; private set; } public string prefabAssetPath { get; private set; } public Bounds renderableBounds { get; private set; } public bool useStaticAssetPreview { get; set; } public PreviewData(UnityObject targetObject, bool creatingStaticPreview = false) { renderUtility = new PreviewRenderUtility(); renderUtility.camera.fieldOfView = 30.0f; if (!creatingStaticPreview) useStaticAssetPreview = IsPrefabFileTooLargeForInteractivePreview(targetObject); if (!useStaticAssetPreview) UpdateGameObject(targetObject); } public void UpdateGameObject(UnityObject targetObject) { UnityObject.DestroyImmediate(gameObject); gameObject = EditorUtility.InstantiateForAnimatorPreview(targetObject); renderUtility.AddManagedGO(gameObject); renderableBounds = GetRenderableBounds(gameObject); } // Very large prefabs takes too long to instantiate for the interactive preview so we // fall back to the static preview for such prefabs bool IsPrefabFileTooLargeForInteractivePreview(UnityObject prefabObject) { string prefabAssetPath = AssetDatabase.GetAssetPath(prefabObject); if (string.IsNullOrEmpty(prefabAssetPath)) return false; string guidString = AssetDatabase.AssetPathToGUID(prefabAssetPath); if (string.IsNullOrEmpty(guidString)) return false; var artifactKey = new ArtifactKey(new GUID(guidString)); var artifactID = AssetDatabaseExperimental.LookupArtifact(artifactKey); // The artifactID can be invalid if we are in the middle of an AssetDatabase.Refresh. if (!artifactID.isValid) return false; AssetDatabaseExperimental.GetArtifactPaths(artifactID, out var paths); if (paths.Length != 1) { Array.Sort(paths); int validatedPathCount = 1; for (int i = 1; i < paths.Length; i++) { if (paths[i].EndsWith(".materialinfo") || paths[i].EndsWith(".importpathinfo") || paths[i].EndsWith(".alphapathinfo")) validatedPathCount++; } if (validatedPathCount != paths.Length) { Debug.LogError("Prefabs should just have one artifact"); return false; } } string importedPrefabPath = Path.GetFullPath(paths[0]); if (!System.IO.File.Exists(importedPrefabPath)) { Debug.LogError("Could not find prefab artifact on disk"); return false; } long length = new System.IO.FileInfo(importedPrefabPath).Length; long fileSizeInKB = length / 1024; // Keep for debugging //Debug.Log("Imported prefab: " + prefabAssetPath + ". File size: " + fileSizeInKB + " KB" + " (guid " + importedPrefabPath + ")"); return fileSizeInKB > kMaxPreviewFileSizeInKB; } public void Dispose() { if (m_Disposed) return; renderUtility.Cleanup(); UnityObject.DestroyImmediate(gameObject); gameObject = null; m_Disposed = true; } } Dictionary<int, PreviewData> m_PreviewInstances = new Dictionary<int, PreviewData>(); Dictionary<int, Texture> m_PreviewCache; Vector2 m_PreviewDir; Vector2 m_StaticPreviewLabelSize; Rect m_PreviewRect; [Flags] enum ButtonStates { None = 0, Openable = 1 << 0, Selectable = 1 << 1, CanShowOverrides = 1 << 2, } ButtonStates m_ButtonStates; bool m_PlayModeObjects; bool m_IsAsset; bool m_ImmutableSelf; bool m_IsMissingArtifact; bool m_IsVariantParentMissingOrCorrupted; bool m_IsPrefabInstanceAnyRoot; bool m_IsPrefabInstanceOutermostRoot; bool m_IsAssetRoot; bool m_AllOfSamePrefabType = true; GameObject m_AllPrefabInstanceRootsAreFromThisAsset; bool m_IsInstanceRootInPrefabContents; bool m_HasRenderableParts = true; GUIContent m_OpenPrefabContent; GUIContent m_SelectedObjectCountContent; GameObject m_MissingGameObject; public void OnEnable() { if (EditorSettings.defaultBehaviorMode == EditorBehaviorMode.Mode2D) m_PreviewDir = new Vector2(0, 0); else { m_PreviewDir = new Vector2(120, -20); //Fix for FogBugz case : 1364821 Inspector Model Preview orientation is reversed when Bake Axis Conversion is enabled UnityObject importedObject = PrefabUtility.IsPartOfVariantPrefab(target) ? PrefabUtility.GetCorrespondingObjectFromSource(target) as GameObject : target; var importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(importedObject)) as ModelImporter; if (importer && importer.bakeAxisConversion) { m_PreviewDir += new Vector2(180,0); } } m_StaticPreviewLabelSize = new Vector2(0, 0); m_Name = serializedObject.FindProperty("m_Name"); m_IsActive = serializedObject.FindProperty("m_IsActive"); m_Layer = serializedObject.FindProperty("m_Layer"); m_Tag = serializedObject.FindProperty("m_TagString"); m_StaticEditorFlags = serializedObject.FindProperty("m_StaticEditorFlags"); m_Icon = serializedObject.FindProperty("m_Icon"); m_SerializedObjectInitialized = true; SetSelectedObjectCountLabelContent(); CalculatePrefabStatus(); CaculateHasRenderableParts(); m_MissingGameObject = EditorUtility.CreateGameObjectWithHideFlags("Missing GameObject for Object Field", HideFlags.HideAndDontSave); DestroyImmediate(m_MissingGameObject); m_PreviewCache = new Dictionary<int, Texture>(); if (EditorUtility.IsPersistent(target)) AssetEvents.assetsChangedOnHDD += OnAssetsChangedOnHDD; } void CalculatePrefabStatus() { m_PlayModeObjects = false; m_IsAsset = false; m_ImmutableSelf = false; m_IsMissingArtifact = false; m_ButtonStates = ButtonStates.Openable | ButtonStates.Selectable | ButtonStates.CanShowOverrides; m_IsVariantParentMissingOrCorrupted = false; m_IsPrefabInstanceAnyRoot = true; m_IsPrefabInstanceOutermostRoot = true; m_AllOfSamePrefabType = true; m_IsAssetRoot = false; PrefabAssetType firstType = PrefabUtility.GetPrefabAssetType(targets[0]); PrefabInstanceStatus firstStatus = PrefabUtility.GetPrefabInstanceStatus(targets[0]); m_OpenPrefabContent = null; m_AllPrefabInstanceRootsAreFromThisAsset = PrefabUtility.GetOriginalSourceOrVariantRoot(targets[0]); m_IsInstanceRootInPrefabContents = false; foreach (var o in targets) { var go = (GameObject)o; if (m_AllOfSamePrefabType) { PrefabAssetType type = PrefabUtility.GetPrefabAssetType(go); PrefabInstanceStatus status = PrefabUtility.GetPrefabInstanceStatus(go); if (type != firstType || status != firstStatus) m_AllOfSamePrefabType = false; } if (Application.IsPlaying(go)) m_PlayModeObjects = true; if (m_IsPrefabInstanceAnyRoot) { if (!PrefabUtility.IsAnyPrefabInstanceRoot(go)) { m_IsPrefabInstanceAnyRoot = false; // Conservative is false if any is false } } if (m_IsPrefabInstanceOutermostRoot) { if (!m_IsPrefabInstanceAnyRoot || !PrefabUtility.IsOutermostPrefabInstanceRoot(go)) { m_IsPrefabInstanceOutermostRoot = false; // Conservative is false if any is false } } if (m_AllPrefabInstanceRootsAreFromThisAsset != null && PrefabUtility.GetOriginalSourceOrVariantRoot(go) != m_AllPrefabInstanceRootsAreFromThisAsset) m_AllPrefabInstanceRootsAreFromThisAsset = null; if (m_IsPrefabInstanceOutermostRoot && targets.Length == 1) { if (PrefabStageUtility.IsGameObjectThePrefabRootInAnyPrefabStage(go)) m_IsInstanceRootInPrefabContents = true; // Replacing base instance in a Variant will break all overrides of existing instances of the Variant } if (PrefabUtility.IsPartOfPrefabAsset(go)) { m_IsAsset = true; // Conservative is true if any is true if (go.transform.parent == null) m_IsAssetRoot = true; } if (m_IsAsset) { if (PrefabUtility.IsPartOfImmutablePrefab(go)) { m_ImmutableSelf = true; // Conservative is true if any is true } } if (PrefabUtility.IsPrefabAssetMissing(go)) { m_IsMissingArtifact = true; m_ButtonStates &= ~ButtonStates.CanShowOverrides; var brokenAsset = GetMainAssetFromBrokenPrefabInstanceRoot(go) as BrokenPrefabAsset; if(brokenAsset == null) m_ButtonStates = ButtonStates.None; else { if (brokenAsset.isVariant) m_IsVariantParentMissingOrCorrupted = true; else if (!brokenAsset.isPrefabFileValid) m_ButtonStates &= ~ButtonStates.Openable; } } } } internal void SetSelectedObjectCountLabelContent() { m_SelectedObjectCountContent = new GUIContent($"({targets.Length})", $"{targets.Length} Objects Selected"); } internal void OnDisable() { foreach (var previewData in m_PreviewInstances.Values) previewData.Dispose(); ClearPreviewCache(); m_PreviewCache = null; if (string.IsNullOrEmpty(m_Name.stringValue) && !(string.IsNullOrEmpty(m_GOPreviousName))) { Debug.LogWarning("A GameObject name cannot be set to an empty string."); m_Name.stringValue = m_GOPreviousName; serializedObject.ApplyModifiedProperties(); } AssetEvents.assetsChangedOnHDD -= OnAssetsChangedOnHDD; } void OnAssetsChangedOnHDD(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { foreach (var importedAssetPath in importedAssets) ReloadPreviewInstance(importedAssetPath); } internal override void OnForceReloadInspector() { base.OnForceReloadInspector(); CalculatePrefabStatus(); CaculateHasRenderableParts(); ReloadPreviewInstances(); SetSelectedObjectCountLabelContent(); } void ClearPreviewCache() { if (m_PreviewCache == null) { return; } foreach (var texture in m_PreviewCache.Values) { DestroyImmediate(texture); } m_PreviewCache.Clear(); } private static StaticEditorFlags[] s_StaticEditorFlagValues; private static bool ShowMixedStaticEditorFlags(StaticEditorFlags mask) { uint countedBits = 0; uint numFlags = 0; if (s_StaticEditorFlagValues == null) { var values = Enum.GetValues(typeof(StaticEditorFlags)); s_StaticEditorFlagValues = new StaticEditorFlags[values.Length]; for (var i = 0; i < values.Length; ++i) s_StaticEditorFlagValues[i] = (StaticEditorFlags)values.GetValue(i); } foreach (var i in s_StaticEditorFlagValues) { numFlags++; if ((mask & i) > 0) countedBits++; } //If we have more then one selected... but it is not all the flags //All indicates 'everything' which means it should be a tick! return countedBits > 0 && countedBits != numFlags; } public override bool UseDefaultMargins() { return false; } protected override void OnHeaderGUI() { bool enabledTemp = GUI.enabled; GUI.enabled = true; EditorGUILayout.BeginVertical(EditorStyles.inspectorBig); GUI.enabled = enabledTemp; DrawInspector(); EditorGUILayout.EndVertical(); } public override void OnInspectorGUI() {} internal bool DrawInspector() { serializedObject.Update(); GameObject go = target as GameObject; // Don't let icon be null as it will create null reference exceptions. Texture2D icon = (Texture2D)(Styles.typelessIcon.image); // Leave iconContent to be default if multiple objects not the same type. if (m_AllOfSamePrefabType) { icon = PrefabUtility.GetIconForGameObject(go); } // Can't do this in OnEnable since it will cause Styles static initializer to be called and // access properties on EditorStyles static class before that one has been initialized. if (m_OpenPrefabContent == null) { if (targets.Length == 1) { GameObject originalSourceOrVariant = PrefabUtility.GetOriginalSourceOrVariantRoot((GameObject)target); if (originalSourceOrVariant != null) m_OpenPrefabContent = new GUIContent( Styles.openPrefab.text, string.Format(Styles.openPrefab.tooltip, originalSourceOrVariant.name)); } if (m_OpenPrefabContent == null) m_OpenPrefabContent = new GUIContent(Styles.openPrefab.text); } EditorGUILayout.BeginHorizontal(); Vector2 dropDownSize = EditorGUI.GetObjectIconDropDownSize(Styles.kIconSize, Styles.kIconSize); var iconRect = GUILayoutUtility.GetRect(1, 1, GUILayout.ExpandWidth(false)); iconRect.width = dropDownSize.x; iconRect.height = dropDownSize.y; EditorGUI.ObjectIconDropDown(iconRect, targets, true, icon, m_Icon); DrawPostIconContent(iconRect); using (new EditorGUI.DisabledScope(m_ImmutableSelf)) { EditorGUILayout.BeginVertical(); { EditorGUILayout.BeginHorizontal(); { EditorGUILayout.BeginHorizontal(GUILayout.Width(Styles.column1Width)); { GUILayout.FlexibleSpace(); // IsActive EditorGUI.PropertyField( GUILayoutUtility.GetRect(EditorStyles.toggle.padding.left, EditorGUIUtility.singleLineHeight, EditorStyles.toggle, GUILayout.ExpandWidth(false)), m_IsActive, GUIContent.none); } EditorGUILayout.EndHorizontal(); // Disable the name field of root GO in prefab asset using (new EditorGUI.DisabledScope(m_IsAsset && m_IsAssetRoot)) { // Name // Resets the game object name when attempted to set it to an empty string if (string.IsNullOrEmpty(m_Name.stringValue) && !(string.IsNullOrEmpty(m_GOPreviousName))) { Debug.LogWarning("A GameObject name cannot be set to an empty string."); m_Name.stringValue = m_GOPreviousName; } else m_GOPreviousName = m_Name.stringValue; EditorGUILayout.DelayedTextField(m_Name, GUIContent.none, EditorStyles.boldTextField); } if (targets.Length > 1) { var maxW = GUI.skin.label.CalcSize(m_SelectedObjectCountContent).x; GUILayout.Label(m_SelectedObjectCountContent, GUILayout.MaxWidth(maxW)); } // Static flags toggle DoStaticToggleField(go); // Static flags dropdown DoStaticFlagsDropDown(go); } EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(EditorGUI.kControlVerticalSpacing); EditorGUILayout.BeginHorizontal(); { // Tag GUILayout.Space(Styles.column1Width - Styles.tagFieldWidth); DoTagsField(go); EditorGUILayout.Space(EditorGUI.kDefaultSpacing, false); // Layer DoLayerField(go); } EditorGUILayout.EndHorizontal(); } EditorGUILayout.EndVertical(); } EditorGUILayout.EndHorizontal(); // Prefab Toolbar if (EditorGUIUtility.comparisonViewMode == EditorGUIUtility.ComparisonViewMode.None) { EditorGUILayout.Space(EditorGUI.kControlVerticalSpacing); DoPrefabButtons(); } serializedObject.ApplyModifiedProperties(); return true; } void DoPrefixLabel(GUIContent label, GUIStyle style) { var rect = GUILayoutUtility.GetRect(label, style, GUILayout.ExpandWidth(false)); rect.height = Math.Max(EditorGUI.kSingleLineHeight, rect.height); GUI.Label(rect, label, style); } void IndentToColumn1() { EditorGUILayout.BeginHorizontal(GUILayout.Width(Styles.column1Width)); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); } bool HandleDragPrefabAssetOverObjectFieldPopupMenu(Rect rect) { var evt = Event.current; bool perform = evt.type == EventType.DragPerform; if (rect.Contains(evt.mousePosition) && (perform ||evt.type == EventType.DragUpdated)) { DragAndDropVisualMode visualMode; if (PrefabReplaceUtility.GetDragVisualModeAndShowMenuWithReplaceMenuItemsWhenNeeded((GameObject)target, true, perform, false, false, out visualMode)) { DragAndDrop.visualMode = visualMode; return perform; } } return false; } void PrefabObjectField() { // Change Prefab asset for instance if (m_IsPrefabInstanceAnyRoot) { EditorGUILayout.BeginHorizontal(); EditorGUI.showMixedValue = m_AllPrefabInstanceRootsAreFromThisAsset == null && !m_IsMissingArtifact; using (var scope = new EditorGUI.ChangeCheckScope()) { GameObject newAsset; bool disabled = !m_IsPrefabInstanceOutermostRoot || m_IsInstanceRootInPrefabContents; using (new EditorGUI.DisabledScope(disabled)) { Rect r = EditorGUILayout.GetControlRect(false, EditorGUI.kSingleLineHeight); if (HandleDragPrefabAssetOverObjectFieldPopupMenu(r)) { GUIUtility.ExitGUI(); // handled by popup menu } if (m_IsMissingArtifact) newAsset = EditorGUI.ObjectField(r, m_MissingGameObject, typeof(GameObject), false) as GameObject; else newAsset = EditorGUI.ObjectField(r, m_AllPrefabInstanceRootsAreFromThisAsset, typeof(GameObject), false) as GameObject; } if (disabled) { // Tooltips (should have tooltips that matches each of the conditions in the above DisabledScope) var rect = EditorGUILayout.s_LastRect; if (rect.Contains(Event.current.mousePosition)) { if (m_IsInstanceRootInPrefabContents) GUI.Label(rect, Styles.tooltipForObjectFieldForRootInPrefabContents); else if (!m_IsPrefabInstanceOutermostRoot) GUI.Label(rect, Styles.tooltipForObjectFieldForNestedPrefabs); } } if (scope.changed) { if (newAsset != null) { string errorMsg = string.Empty; try { PrefabUtility.ThrowIfInvalidAssetForReplacePrefabInstance(newAsset, InteractionMode.UserAction); foreach (var t in targets) PrefabUtility.ThrowIfInvalidArgumentsForReplacePrefabInstance((GameObject)t, newAsset, false, InteractionMode.UserAction); } catch (InvalidOperationException e) { errorMsg = e.Message; } if (string.IsNullOrEmpty(errorMsg)) { // targets are in reverse order from the Hierarchy selection so we reverse it here so we get the same result as repalcing from the Hierarchy var replaceTargets = new List<UnityObject>(targets); replaceTargets.Reverse(); if (targets.Length > 1) PrefabUtility.ReplacePrefabAssetOfPrefabInstances(replaceTargets.Select(e => (GameObject)e).ToArray(), newAsset, InteractionMode.UserAction); else PrefabUtility.ReplacePrefabAssetOfPrefabInstance((GameObject)target, newAsset, InteractionMode.UserAction); CalculatePrefabStatus(); // Updates the cached m_FirstPrefabInstanceOutermostRootAsset to the newly selected Prefab GUIUtility.ExitGUI(); } else { var gameObjectsToPing = new List<GameObject>(); var assetGameObjectsWithInvalidComponents = PrefabUtility.FindGameObjectsWithInvalidComponent(newAsset); var instanceGameObjectsWithInvalidComponents = PrefabUtility.FindGameObjectsWithInvalidComponent((GameObject)target); if (assetGameObjectsWithInvalidComponents.Count > 0) gameObjectsToPing.Add(assetGameObjectsWithInvalidComponents[0]); if (instanceGameObjectsWithInvalidComponents.Count > 0) gameObjectsToPing.Add(instanceGameObjectsWithInvalidComponents[0]); Debug.LogWarning(errorMsg, gameObjectsToPing.Count > 0 ? gameObjectsToPing[0] : null); foreach(var go in gameObjectsToPing) EditorGUIUtility.PingObject(go); } } else { // 'newAsset' is null: Replacing with null Asset should just be ignored (no need to show a dialog) } } } EditorGUI.showMixedValue = false; EditorGUILayout.EndHorizontal(); } } private void DoPrefabButtons() { if (!m_IsPrefabInstanceAnyRoot || m_IsAsset) return; // Vertical spacing to group Prefab related UI from the GameObject's UI EditorGUILayout.Space(12); using (new EditorGUI.DisabledScope(m_PlayModeObjects)) { // Prefab label and asset field EditorGUILayout.BeginHorizontal(); PrefabAssetType singlePrefabType = PrefabUtility.GetPrefabAssetType(target); PrefabInstanceStatus singleInstanceStatus = PrefabUtility.GetPrefabInstanceStatus(target); GUIContent prefixLabel; if (targets.Length > 1) { prefixLabel = Styles.goTypeLabelMultiple; } else { prefixLabel = Styles.goTypeLabel[(int)singlePrefabType, (int)singleInstanceStatus]; } if (prefixLabel != null) { EditorGUILayout.BeginHorizontal(GUILayout.Width(Styles.column1Width)); GUILayout.FlexibleSpace(); DoPrefixLabel(prefixLabel, EditorStyles.label); EditorGUILayout.EndHorizontal(); } PrefabObjectField(); EditorGUILayout.EndHorizontal(); if (m_ButtonStates != ButtonStates.None) { EditorGUILayout.Space(EditorGUI.kControlVerticalSpacing); EditorGUILayout.BeginHorizontal(Styles.prefabButtonsHorizontalLayout); IndentToColumn1(); // Overrides Popup. Reserve space regardless of whether the button is there or not to avoid jumps in button sizes. Rect rect = GUILayoutUtility.GetRect(Styles.overridesContent, Styles.overridesDropdown); if (m_ButtonStates.HasFlag(ButtonStates.CanShowOverrides) && m_IsPrefabInstanceOutermostRoot) { if (EditorGUI.DropdownButton(rect, Styles.overridesContent, FocusType.Passive)) { if (targets.Length > 1) PopupWindow.Show(rect, new PrefabOverridesWindow(targets.Select(e => (GameObject)e).ToArray())); else PopupWindow.Show(rect, new PrefabOverridesWindow((GameObject)target)); GUIUtility.ExitGUI(); } } // Spacing between buttons GUILayoutUtility.GetRect(20, 6, GUILayout.MaxWidth(30), GUILayout.MinWidth(5)); // Select prefab if (GUILayout.Button(Styles.selectString, EditorStyles.miniButton)) { HashSet<UnityObject> selectedAssets = new HashSet<UnityObject>(); for (int i = 0; i < targets.Length; i++) { GameObject targetGo = targets[i] as GameObject; GameObject prefabGo = PrefabUtility.GetOriginalSourceOrVariantRoot(targetGo); if (prefabGo != null) { // Because of legacy prefab references we have to have this extra step // to make sure we ping the prefab asset correctly. // Reason is that scene files created prior to making prefabs CopyAssets // will reference prefabs as if they are serialized assets. Those references // works fine but we are not able to ping objects loaded directly from the asset // file, so we have to make sure we ping the metadata version of the prefab. var assetPath = AssetDatabase.GetAssetPath(prefabGo); selectedAssets.Add((GameObject)AssetDatabase.LoadMainAssetAtPath(assetPath)); } else { UnityObject mainAsset = GetMainAssetFromBrokenPrefabInstanceRoot(targetGo); if (mainAsset != null) selectedAssets.Add(mainAsset); } } Selection.objects = selectedAssets.ToArray(); if (Selection.objects.Length != 0) EditorGUIUtility.PingObject(Selection.activeObject); } // Open Prefab using (new EditorGUI.DisabledScope(targets.Length > 1 || !m_ButtonStates.HasFlag(ButtonStates.Openable))) { if (singlePrefabType == PrefabAssetType.Model) { // Open Model Prefab if (GUILayout.Button(Styles.openModel, EditorStyles.miniButton)) { GameObject asset = PrefabUtility.GetOriginalSourceOrVariantRoot(target); AssetDatabase.OpenAsset(asset); GUIUtility.ExitGUI(); } } else { // Open non-Model Prefab if (GUILayout.Button(m_OpenPrefabContent, EditorStyles.miniButton)) { var prefabStageMode = PrefabStageUtility.GetPrefabStageModeFromModifierKeys(); UnityObject asset = null; if (!m_IsVariantParentMissingOrCorrupted) asset = PrefabUtility.GetOriginalSourceOrVariantRoot(target); else asset = GetMainAssetFromBrokenPrefabInstanceRoot(target as GameObject); PrefabStageUtility.OpenPrefab(AssetDatabase.GetAssetPath(asset), (GameObject)target, prefabStageMode, StageNavigationManager.Analytics.ChangeType.EnterViaInstanceInspectorOpenButton); GUIUtility.ExitGUI(); } } } EditorGUILayout.EndHorizontal(); } } } private void DoLayerField(GameObject go) { EditorGUIUtility.labelWidth = Styles.layerFieldWidth; Rect layerRect = GUILayoutUtility.GetRect(GUIContent.none, Styles.layerPopup); EditorGUI.BeginProperty(layerRect, GUIContent.none, m_Layer); EditorGUI.BeginChangeCheck(); int layer = EditorGUI.LayerField(layerRect, Styles.layerContent, go.layer, Styles.layerPopup); if (EditorGUI.EndChangeCheck()) { GameObjectUtility.ShouldIncludeChildren includeChildren = GameObjectUtility.DisplayUpdateChildrenDialogIfNeeded(targets.OfType<GameObject>(), L10n.Tr("Change Layer"), string.Format(L10n.Tr("Do you want to set layer to {0} for all child objects as well?"), InternalEditorUtility.GetLayerName(layer))); if (includeChildren != GameObjectUtility.ShouldIncludeChildren.Cancel) { m_Layer.intValue = layer; SetLayer(layer, includeChildren == GameObjectUtility.ShouldIncludeChildren.IncludeChildren); } // Displaying the dialog to ask the user whether to update children nukes the gui state EditorGUIUtility.ExitGUI(); } EditorGUI.EndProperty(); } private void DoTagsField(GameObject go) { string tagName = go.tag; EditorGUIUtility.labelWidth = Styles.tagFieldWidth; Rect tagRect = GUILayoutUtility.GetRect(GUIContent.none, Styles.tagPopup); EditorGUI.BeginProperty(tagRect, GUIContent.none, m_Tag); EditorGUI.BeginChangeCheck(); string tag = EditorGUI.TagField(tagRect, Styles.tagContent, tagName); if (EditorGUI.EndChangeCheck()) { m_Tag.stringValue = tag; Undo.RecordObjects(targets, "Change Tag of " + targetTitle); foreach (UnityObject obj in targets) (obj as GameObject).tag = tag; } EditorGUI.EndProperty(); } private void DoStaticFlagsDropDown(GameObject go) { var rect = GUILayoutUtility.GetRect(GUIContent.none, Styles.staticDropdown, GUILayout.ExpandWidth(false)); rect.height = Math.Max(EditorGUIUtility.singleLineHeight, rect.height); bool toggled = EditorGUILayout.DropdownButton(GUIContent.none, FocusType.Keyboard, Styles.staticDropdown); if (toggled) { rect = GUILayoutUtility.topLevel.GetLast(); // We do not pass the serializedProperty directly, as its parent serializedObject // can get destroyed when references to parent windows are lost, thus we use // the target object & the path to reconstruct the property inside the window itself PopupWindow.Show(rect, new StaticFieldDropdown(m_StaticEditorFlags.serializedObject.targetObjects, m_StaticEditorFlags.propertyPath)); GUIUtility.ExitGUI(); } } private void DoStaticToggleField(GameObject go) { var staticRect = GUILayoutUtility.GetRect(Styles.staticContent, EditorStyles.toggle, GUILayout.ExpandWidth(false)); staticRect.height = Math.Max(EditorGUIUtility.singleLineHeight, staticRect.height); staticRect.width += 3; //offset for the bold text when displaying prefab instances. EditorGUI.BeginProperty(staticRect, GUIContent.none, m_StaticEditorFlags); EditorGUI.BeginChangeCheck(); var toggleRect = staticRect; EditorGUI.showMixedValue |= ShowMixedStaticEditorFlags((StaticEditorFlags)m_StaticEditorFlags.intValue); // Ignore mouse clicks that are not with the primary (left) mouse button so those can be grabbed by other things later. Event evt = Event.current; EventType origType = evt.type; bool nonLeftClick = (evt.type == EventType.MouseDown && evt.button != 0); if (nonLeftClick) evt.type = EventType.Ignore; var toggled = EditorGUI.ToggleLeft(toggleRect, Styles.staticContent, go.isStatic); if (nonLeftClick) evt.type = origType; EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { SceneModeUtility.SetStaticFlags(targets, int.MaxValue, toggled); serializedObject.SetIsDifferentCacheDirty(); // Displaying the dialog to ask the user whether to update children nukes the gui state (case 962453) EditorGUIUtility.ExitGUI(); } EditorGUI.EndProperty(); } UnityObject[] GetObjects(bool includeChildren) { return SceneModeUtility.GetObjects(targets, includeChildren); } void SetLayer(int layer, bool includeChildren) { UnityObject[] objects = GetObjects(includeChildren); Undo.RecordObjects(objects, "Change Layer of " + targetTitle); foreach (var o in objects) { var go = (GameObject)o; go.layer = layer; } } void ReloadPreviewInstance(string prefabAssetPath) { foreach (var pair in m_PreviewInstances) { var index = pair.Key; if (index > targets.Length) continue; var previewData = pair.Value; if (previewData.prefabAssetPath == prefabAssetPath) { previewData.UpdateGameObject(targets[index]); ClearPreviewCache(); return; } } } public override void ReloadPreviewInstances() { foreach (var pair in m_PreviewInstances) { var index = pair.Key; if (index > targets.Length) continue; var previewData = pair.Value; if (!previewData.useStaticAssetPreview) previewData.UpdateGameObject(targets[index]); } ClearPreviewCache(); } PreviewData GetPreviewData(bool creatingStaticPreview = false) { PreviewData previewData; if (!m_PreviewInstances.TryGetValue(referenceTargetIndex, out previewData)) { previewData = new PreviewData(target, creatingStaticPreview); m_PreviewInstances.Add(referenceTargetIndex, previewData); } if (!previewData.gameObject && !previewData.useStaticAssetPreview) ReloadPreviewInstances(); return previewData; } static readonly List<Renderer> s_RendererComponentsList = new List<Renderer>(); static bool IsRendererUsableForPreview(Renderer r) { switch (r) { case MeshRenderer mr: mr.gameObject.TryGetComponent<MeshFilter>(out var mf); if (mf == null || mf.sharedMesh == null) return false; break; case SkinnedMeshRenderer skin: if (skin.sharedMesh == null) return false; break; case SpriteRenderer sprite: if (sprite.sprite == null) return false; break; case BillboardRenderer billboard: if (billboard.billboard == null || billboard.sharedMaterial == null) return false; break; } return true; } void CaculateHasRenderableParts() { m_HasRenderableParts = HasRenderableParts(target as GameObject); } public static bool HasRenderableParts(GameObject go) { if (!go) return false; go.GetComponentsInChildren(s_RendererComponentsList); return s_RendererComponentsList.Any(IsRendererUsableForPreview); } public static Bounds GetRenderableBounds(GameObject go) { var b = new Bounds(); if (!go) return b; go.GetComponentsInChildren(s_RendererComponentsList); foreach (var r in s_RendererComponentsList) { if (!IsRendererUsableForPreview(r)) continue; if (b.extents == Vector3.zero) b = r.bounds; else b.Encapsulate(r.bounds); } return b; } private static float GetRenderableCenterRecurse(ref Vector3 center, GameObject go, int depth, int minDepth, int maxDepth) { if (depth > maxDepth) return 0; float ret = 0; if (depth > minDepth) { // Do we have a mesh? var renderer = go.GetComponent<MeshRenderer>(); var filter = go.GetComponent<MeshFilter>(); var skin = go.GetComponent<SkinnedMeshRenderer>(); var sprite = go.GetComponent<SpriteRenderer>(); var billboard = go.GetComponent<BillboardRenderer>(); if (renderer == null && filter == null && skin == null && sprite == null && billboard == null) { ret = 1; center = center + go.transform.position; } else if (renderer != null && filter != null) { // case 542145, epsilon is too small. Accept up to 1 centimeter before discarding this model. if (Vector3.Distance(renderer.bounds.center, go.transform.position) < 0.01F) { ret = 1; center = center + go.transform.position; } } else if (skin != null) { // case 542145, epsilon is too small. Accept up to 1 centimeter before discarding this model. if (Vector3.Distance(skin.bounds.center, go.transform.position) < 0.01F) { ret = 1; center = center + go.transform.position; } } else if (sprite != null) { if (Vector3.Distance(sprite.bounds.center, go.transform.position) < 0.01F) { ret = 1; center = center + go.transform.position; } } else if (billboard != null) { if (Vector3.Distance(billboard.bounds.center, go.transform.position) < 0.01F) { ret = 1; center = center + go.transform.position; } } } depth++; // Recurse into children foreach (Transform t in go.transform) { ret += GetRenderableCenterRecurse(ref center, t.gameObject, depth, minDepth, maxDepth); } return ret; } public static Vector3 GetRenderableCenterRecurse(GameObject go, int minDepth, int maxDepth) { Vector3 center = Vector3.zero; float sum = GetRenderableCenterRecurse(ref center, go, 0, minDepth, maxDepth); if (sum > 0) { center = center / sum; } else { center = go.transform.position; } return center; } public override bool HasPreviewGUI() { if (!EditorUtility.IsPersistent(target)) return false; return HasStaticPreview(); } private bool HasStaticPreview() { if (targets.Length > 1) return true; if (target == null) return false; return m_HasRenderableParts; } public override void OnPreviewSettings() { if (!ShaderUtil.hardwareSupportsRectRenderTexture) return; GUI.enabled = true; } private void DoRenderPreview(PreviewData previewData) { var bounds = previewData.renderableBounds; float halfSize = Mathf.Max(bounds.extents.magnitude, 0.0001f); float distance = halfSize * 3.8f; Quaternion rot = Quaternion.Euler(-m_PreviewDir.y, -m_PreviewDir.x, 0); Vector3 pos = bounds.center - rot * (Vector3.forward * distance); previewData.renderUtility.camera.transform.position = pos; previewData.renderUtility.camera.transform.rotation = rot; previewData.renderUtility.camera.nearClipPlane = distance - halfSize * 1.1f; previewData.renderUtility.camera.farClipPlane = distance + halfSize * 1.1f; previewData.renderUtility.lights[0].intensity = .7f; previewData.renderUtility.lights[0].transform.rotation = rot * Quaternion.Euler(40f, 40f, 0); previewData.renderUtility.lights[1].intensity = .7f; previewData.renderUtility.lights[1].transform.rotation = rot * Quaternion.Euler(340, 218, 177); previewData.renderUtility.ambientColor = new Color(.1f, .1f, .1f, 0); previewData.renderUtility.Render(true); } public override Texture2D RenderStaticPreview(string assetPath, UnityObject[] subAssets, int width, int height) { if (!HasStaticPreview() || !ShaderUtil.hardwareSupportsRectRenderTexture) { return null; } var previewData = GetPreviewData(true); previewData.renderUtility.BeginStaticPreview(new Rect(0, 0, width, height)); DoRenderPreview(previewData); return previewData.renderUtility.EndStaticPreview(); } void DrawAssetPreviewTexture(Rect rect) { Texture2D icon = AssetPreview.GetAssetPreview(target); if (!icon) { // We have a static preview it just hasn't been loaded yet. Repaint until we have it loaded. if (AssetPreview.IsLoadingAssetPreview(target.GetInstanceID())) Repaint(); } else { var scaleMode = ScaleMode.ScaleToFit; GUI.DrawTexture(rect, icon, scaleMode); if (m_StaticPreviewLabelSize.x == 0.0f && m_StaticPreviewLabelSize.y == 0.0f) m_StaticPreviewLabelSize = GUI.skin.label.CalcSize(Styles.staticPreviewContent); // Only render overlay text if there is space enough if (rect.width >= m_StaticPreviewLabelSize.x && rect.height >= m_StaticPreviewLabelSize.y + GUI.skin.label.padding.vertical) { using (new EditorGUI.DisabledScope(true)) { GUI.Label(new Rect(rect.x, rect.yMax - (m_StaticPreviewLabelSize.y + GUI.skin.label.padding.vertical), rect.width, m_StaticPreviewLabelSize.y), Styles.staticPreviewContent, EditorStyles.centeredGreyMiniLabel); } } } } public override void OnPreviewGUI(Rect r, GUIStyle background) { var previewData = GetPreviewData(); if (previewData.useStaticAssetPreview && GUI.Button(r, GUIContent.none)) { previewData.useStaticAssetPreview = false; previewData.UpdateGameObject(target); } if (previewData.useStaticAssetPreview || !ShaderUtil.hardwareSupportsRectRenderTexture) { if (Event.current.type == EventType.Repaint) DrawAssetPreviewTexture(r); return; } var direction = PreviewGUI.Drag2D(m_PreviewDir, r); if (direction != m_PreviewDir) { // None of the preview are valid since the camera position has changed. ClearPreviewCache(); m_PreviewDir = direction; } if (Event.current.type != EventType.Repaint) return; if (m_PreviewRect != r) { ClearPreviewCache(); m_PreviewRect = r; } var previewUtility = GetPreviewData().renderUtility; Texture previewTexture; if (m_PreviewCache.TryGetValue(referenceTargetIndex, out previewTexture)) { PreviewRenderUtility.DrawPreview(r, previewTexture); } else { previewUtility.BeginPreview(r, background); DoRenderPreview(previewData); previewUtility.EndAndDrawPreview(r); var copy = new RenderTexture(previewUtility.renderTexture); var previous = RenderTexture.active; Graphics.Blit(previewUtility.renderTexture, copy); RenderTexture.active = previous; m_PreviewCache.Add(referenceTargetIndex, copy); } } // Handle dragging in scene view public GameObject m_DragObject; static bool s_ShouldClearSelection; internal static bool s_CyclicNestingDetected; static bool s_PlaceObject; static Vector3 s_PlaceObjectPoint; static Vector3 s_PlaceObjectNormal; public void OnSceneDrag(SceneView sceneView, int index) { Event evt = Event.current; OnSceneDragInternal(sceneView, index, evt.type, evt.mousePosition, evt.alt); } static Scene GetDestinationSceneForNewGameObjectsForSceneView(SceneView sceneView) { if (sceneView.customParentForNewGameObjects != null) return sceneView.customParentForNewGameObjects.gameObject.scene; if (sceneView.customScene.IsValid()) return sceneView.customScene; return SceneManager.GetActiveScene(); } internal void OnSceneDragInternal(SceneView sceneView, int index, EventType type, Vector2 mousePosition, bool alt) { GameObject go = target as GameObject; if (!PrefabUtility.IsPartOfPrefabAsset(go)) return; var prefabAssetRoot = go.transform.root.gameObject; switch (type) { case EventType.DragUpdated: if (m_DragObject == null) { // While dragging the instantiated prefab we do not want to record undo for this object // this will cause a remerge of the instance since changes are undone while dragging. // The DrivenRectTransformTracker by default records Undo when used when driving // UI components. This breaks our hideflag setup below due to a remerge of the dragged instance. // StartRecordingUndo() is called on DragExited. Fixes case 1223793. DrivenRectTransformTracker.StopRecordingUndo(); Scene destinationScene = GetDestinationSceneForNewGameObjectsForSceneView(sceneView); if (!EditorApplication.isPlaying || EditorSceneManager.IsPreviewScene(destinationScene)) { m_DragObject = (GameObject)PrefabUtility.InstantiatePrefab(prefabAssetRoot, destinationScene); m_DragObject.name = go.name; } else { // Instatiate as regular GameObject in Play Mode so runtime logic // won't run into restrictions on restructuring Prefab instances. m_DragObject = Instantiate(prefabAssetRoot); SceneManager.MoveGameObjectToScene(m_DragObject, destinationScene); } m_DragObject.hideFlags = HideFlags.HideInHierarchy; if (HandleUtility.ignoreRaySnapObjects == null) HandleUtility.ignoreRaySnapObjects = m_DragObject.GetComponentsInChildren<Transform>(); else HandleUtility.ignoreRaySnapObjects = HandleUtility.ignoreRaySnapObjects.Union(m_DragObject.GetComponentsInChildren<Transform>()).ToArray(); PrefabStage prefabStage = PrefabStageUtility.GetCurrentPrefabStage(); if (prefabStage != null) { GameObject prefab = AssetDatabase.LoadMainAssetAtPath(prefabStage.assetPath) as GameObject; if (prefab != null) { if (PrefabUtility.CheckIfAddingPrefabWouldResultInCyclicNesting(prefab, target)) { s_CyclicNestingDetected = true; } } } } DragAndDrop.visualMode = DragAndDropVisualMode.Copy; Vector3 point, normal; float offset = 0; if (index == 0) { s_PlaceObject = HandleUtility.PlaceObject(mousePosition, out s_PlaceObjectPoint, out s_PlaceObjectNormal); } point = s_PlaceObjectPoint; normal = s_PlaceObjectNormal; if (s_PlaceObject) { if (Tools.pivotMode == PivotMode.Center) { float geomOffset = HandleUtility.CalcRayPlaceOffset(m_DragObject.GetComponentsInChildren<Transform>(), normal); if (geomOffset != Mathf.Infinity) offset = Vector3.Dot(m_DragObject.transform.position, normal) - geomOffset; } m_DragObject.transform.position = Matrix4x4.identity.MultiplyPoint(point + (normal * offset)); } else m_DragObject.transform.position = HandleUtility.GUIPointToWorldRay(mousePosition).GetPoint(10); if (alt) { if (offset != 0) { m_DragObject.transform.position = point; } m_DragObject.transform.position += prefabAssetRoot.transform.localPosition; } // Use prefabs original z position when in 2D mode if (sceneView.in2DMode) { Vector3 dragPosition = m_DragObject.transform.position; dragPosition.z = prefabAssetRoot.transform.position.z; m_DragObject.transform.position = dragPosition; } // Schedule selection clearing for when we start performing the actual drag action s_ShouldClearSelection = true; break; case EventType.DragPerform: DragPerform(sceneView, m_DragObject, go); m_DragObject = null; break; case EventType.DragExited: // DragExited is always fired after DragPerform so we do no need to call StartRecordingUndo // in DragPerform DrivenRectTransformTracker.StartRecordingUndo(); if (m_DragObject) { DestroyImmediate(m_DragObject, false); HandleUtility.ignoreRaySnapObjects = null; m_DragObject = null; } s_ShouldClearSelection = false; s_CyclicNestingDetected = false; break; } } internal static void DragPerform(SceneView sceneView, GameObject draggedObject, GameObject go) { Transform defaultParentObject = SceneView.GetDefaultParentObjectIfSet(); var parent = defaultParentObject != null ? defaultParentObject : sceneView.customParentForDraggedObjects; string uniqueName = GameObjectUtility.GetUniqueNameForSibling(parent, draggedObject.name); if (parent != null) { draggedObject.transform.SetParent(parent, true); } if (defaultParentObject == null && sceneView.customParentForDraggedObjects == null) { draggedObject.transform.SetAsLastSibling(); } draggedObject.hideFlags = 0; Undo.RegisterCreatedObjectUndo(draggedObject, "Place " + draggedObject.name); DragAndDrop.AcceptDrag(); if (s_ShouldClearSelection) { Selection.objects = new[] { draggedObject }; s_ShouldClearSelection = false; } else { // Since this inspector code executes for each dragged GameObject we should retain // selection to all of them by joining them to the previous selection list Selection.objects = Selection.gameObjects.Union(new[] { draggedObject }).ToArray(); } HandleUtility.ignoreRaySnapObjects = null; if (SceneView.mouseOverWindow != null) SceneView.mouseOverWindow.Focus(); if (!Application.IsPlaying(draggedObject)) draggedObject.name = uniqueName; s_CyclicNestingDetected = false; } internal UnityObject GetMainAssetFromBrokenPrefabInstanceRoot(GameObject targetGo) { //Handle cases where you have a variant with a parent that is missing var path = PrefabUtility.GetAssetPathOfSourcePrefab(targetGo); var asset = AssetDatabase.LoadMainAssetAtPath(path); return asset; } } }
UnityCsReference/Editor/Mono/Inspector/GameObjectInspector.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/GameObjectInspector.cs", "repo_id": "UnityCsReference", "token_count": 33309 }
320
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using Object = UnityEngine.Object; using UnityEditor.AnimatedValues; using UnityEngine; using UnityEngine.Rendering; using System; using System.Linq; using System.Collections.Generic; namespace UnityEditor { [CustomEditor(typeof(Light))] [CanEditMultipleObjects] public class LightEditor : Editor { public sealed class Settings { private SerializedObject m_SerializedObject; public SerializedProperty lightType { get; private set; } [Obsolete("The lightShape property has been deprecated in favor of the lightType property.")] public SerializedProperty lightShape { get; private set; } public SerializedProperty range { get; private set; } public SerializedProperty spotAngle { get; private set; } public SerializedProperty innerSpotAngle { get; private set; } public SerializedProperty enableSpotReflector { get; private set; } public SerializedProperty cookieSize { get; private set; } public SerializedProperty color { get; private set; } public SerializedProperty intensity { get; private set; } public SerializedProperty bounceIntensity { get; private set; } public SerializedProperty lightUnit { get; private set; } public SerializedProperty luxAtDistance { get; private set; } public SerializedProperty colorTemperature { get; private set; } public SerializedProperty useColorTemperature { get; private set; } public SerializedProperty cookieProp { get; private set; } public SerializedProperty shadowsType { get; private set; } public SerializedProperty shadowsStrength { get; private set; } public SerializedProperty shadowsResolution { get; private set; } public SerializedProperty shadowsBias { get; private set; } public SerializedProperty shadowsNormalBias { get; private set; } public SerializedProperty shadowsNearPlane { get; private set; } public SerializedProperty halo { get; private set; } public SerializedProperty flare { get; private set; } public SerializedProperty renderMode { get; private set; } public SerializedProperty cullingMask { get; private set; } public SerializedProperty renderingLayerMask { get; private set; } public SerializedProperty lightmapping { get; private set; } public SerializedProperty areaSizeX { get; private set; } public SerializedProperty areaSizeY { get; private set; } public SerializedProperty bakedShadowRadiusProp { get; private set; } public SerializedProperty bakedShadowAngleProp { get; private set; } Texture2D m_KelvinGradientTexture; const float kMinKelvin = 1000f; const float kMaxKelvin = 20000f; const float kSliderPower = 2f; // should have the same int values as corresponding shape in LightType private enum AreaLightShape { None = 0, Rectangle = 3, Disc = 4 } public Settings(SerializedObject so) { m_SerializedObject = so; } private static class Styles { public static readonly GUIContent Type = EditorGUIUtility.TrTextContent("Type", "Specifies the current type of light. Possible types are Directional, Spot, Point, and Area lights."); public static readonly GUIContent Shape = EditorGUIUtility.TrTextContent("Shape", "Specifies the shape of the Area light. Possible types are Rectangle and Disc."); public static readonly GUIContent Range = EditorGUIUtility.TrTextContent("Range", "Controls how far the light is emitted from the center of the object."); public static readonly GUIContent SpotAngle = EditorGUIUtility.TrTextContent("Spot Angle", "Controls the angle in degrees at the base of a Spot light's cone."); public static readonly GUIContent InnerOuterSpotAngle = EditorGUIUtility.TrTextContent("Inner / Outer Spot Angle", "Controls the inner and outer angles in degrees, at the base of a Spot light's cone."); public static readonly GUIContent Color = EditorGUIUtility.TrTextContent("Color", "Controls the color being emitted by the light."); public static readonly GUIContent UseColorTemperature = EditorGUIUtility.TrTextContent("Use color temperature mode", "Choose between RGB and temperature mode for light's color."); public static readonly GUIContent ColorFilter = EditorGUIUtility.TrTextContent("Filter", "A colored gel can be put in front of the light source to tint the light."); public static readonly GUIContent ColorTemperature = EditorGUIUtility.TrTextContent("Temperature", "Also known as CCT (Correlated color temperature). The color temperature of the electromagnetic radiation emitted from an ideal black body is defined as its surface temperature in Kelvin. White is 6500K"); public static readonly GUIContent Intensity = EditorGUIUtility.TrTextContent("Intensity", "Controls the brightness of the light. Light color is multiplied by this value."); public static readonly GUIContent LightmappingMode = EditorGUIUtility.TrTextContent("Mode", "Specifies the light mode used to determine if and how a light will be baked. Possible modes are Baked, Mixed, and Realtime."); public static readonly GUIContent LightBounceIntensityRealtimeGISupport = EditorGUIUtility.TrTextContent("Indirect Multiplier", "Determines the intensity of indirect light being contributed to the scene. Has no effect when both Realtime and Baked Global Illumination are disabled. If this value is 0, Realtime lights to be removed from realtime global illumination and Baked and Mixed lights to no longer emit indirect lighting."); public static readonly GUIContent LightBounceIntensity = EditorGUIUtility.TrTextContent("Indirect Multiplier", "Determines the intensity of indirect light being contributed to to the scene. Has no effect when Baked Global Illumination is disabled. If this value is 0, Baked and Mixed lights no longer emit indirect lighting."); public static readonly GUIContent ShadowType = EditorGUIUtility.TrTextContent("Shadow Type", "Specifies whether Hard Shadows, Soft Shadows, or No Shadows will be cast by the light."); public static readonly GUIContent CastShadows = EditorGUIUtility.TrTextContent("Cast Shadows", "Specifies whether Soft Shadows or No Shadows will be cast by the light."); //realtime public static readonly GUIContent ShadowRealtimeSettings = EditorGUIUtility.TrTextContent("Realtime Shadows", "Settings for realtime direct shadows."); public static readonly GUIContent ShadowStrength = EditorGUIUtility.TrTextContent("Strength", "Controls how dark the shadows cast by the light will be."); public static readonly GUIContent ShadowResolution = EditorGUIUtility.TrTextContent("Resolution", "Controls the rendered resolution of the shadow maps. A higher resolution will increase the fidelity of shadows at the cost of GPU performance and memory usage."); public static readonly GUIContent ShadowBias = EditorGUIUtility.TrTextContent("Bias", "Controls the distance at which the shadows will be pushed away from the light. Useful for avoiding false self-shadowing artifacts."); public static readonly GUIContent ShadowNormalBias = EditorGUIUtility.TrTextContent("Normal Bias", "Controls distance at which the shadow casting surfaces will be shrunk along the surface normal. Useful for avoiding false self-shadowing artifacts."); public static readonly GUIContent ShadowNearPlane = EditorGUIUtility.TrTextContent("Near Plane", "Controls the value for the near clip plane when rendering shadows. Currently clamped to 0.1 units or 1% of the lights range property, whichever is lower."); //baked public static readonly GUIContent BakedShadowRadius = EditorGUIUtility.TrTextContent("Baked Shadow Radius", "Controls the amount of artificial softening applied to the edges of shadows cast by the Point or Spot light."); public static readonly GUIContent BakedShadowAngle = EditorGUIUtility.TrTextContent("Baked Shadow Angle", "Controls the amount of artificial softening applied to the edges of shadows cast by directional lights."); public static readonly GUIContent Cookie = EditorGUIUtility.TrTextContent("Cookie", "Specifies the Texture mask to cast shadows, create silhouettes, or patterned illumination for the light."); public static readonly GUIContent CookieSize = EditorGUIUtility.TrTextContent("Size", "Controls the size of the cookie mask currently assigned to the light."); public static readonly GUIContent CookieTexture = EditorGUIUtility.TrTextContent("Cookie", "Texture to use for the light cookie."); public static readonly GUIContent DrawHalo = EditorGUIUtility.TrTextContent("Draw Halo", "When enabled, draws a spherical halo of light with a radius equal to the lights range value."); public static readonly GUIContent Flare = EditorGUIUtility.TrTextContent("Flare", "Specifies the flare object to be used by the light to render lens flares in the scene."); public static readonly GUIContent RenderMode = EditorGUIUtility.TrTextContent("Render Mode", "Specifies the importance of the light which impacts lighting fidelity and performance. Options are Auto, Important, and Not Important. This only affects Forward Rendering."); public static readonly GUIContent CullingMask = EditorGUIUtility.TrTextContent("Culling Mask", "Specifies which layers will be affected or excluded from the light's effect on objects in the scene."); public static readonly GUIContent RenderingLayerMask = EditorGUIUtility.TrTextContent("Rendering Layer Mask", "Mask that can be used with SRP when drawing shadows to filter renderers outside of the normal layering system."); public static readonly GUIContent AreaWidth = EditorGUIUtility.TrTextContent("Width", "Controls the width in units of the area light."); public static readonly GUIContent AreaHeight = EditorGUIUtility.TrTextContent("Height", "Controls the height in units of the area light."); public static readonly GUIContent AreaRadius = EditorGUIUtility.TrTextContent("Radius", "Controls the radius in units of the disc area light."); public static readonly GUIContent BakingWarning = EditorGUIUtility.TrTextContent("Light mode is currently overridden to Realtime mode. Enable Baked Global Illumination to use Mixed or Baked light modes."); public static readonly GUIContent IndirectBounceShadowWarning = EditorGUIUtility.TrTextContent("Realtime indirect bounce shadowing is only supported for Directional lights."); public static readonly GUIContent CookieSpotRepeatWarning = EditorGUIUtility.TrTextContent("Cookie textures for spot lights should be set to clamp, not repeat, to avoid artifacts."); public static readonly GUIContent CookieNotEnabledWarning = EditorGUIUtility.TrTextContent("Cookie support for baked lights is not enabled. Please enable it in Project Settings > Editor > Enable baked cookies support"); public static readonly GUIContent CookieNotEnabledInfo = EditorGUIUtility.TrTextContent("Cookie support for mixed lights is not enabled for indirect lighting. You can enable it in Project Settings > Editor > Enable baked cookies support"); public static readonly GUIContent CookieSpotDirectionalTextureWarning = EditorGUIUtility.TrTextContent("Spot and directional light cookie textures must be 2D."); public static readonly GUIContent CookiePointCubemapTextureWarning = EditorGUIUtility.TrTextContent("Cookie support for baked lights is not enabled. Please enable it in Project Settings > Editor > Enable baked cookies support"); public static readonly GUIContent MixedUnsupportedWarning = EditorGUIUtility.TrTextContent("Light mode is currently overridden to Realtime mode. The current render pipeline doesn't support Mixed mode and/or any of the lighting modes."); public static readonly GUIContent BakedUnsupportedWarning = EditorGUIUtility.TrTextContent("Light mode is currently overridden to Realtime mode. The current render pipeline doesn't support Baked mode."); public static readonly GUIContent[] LightmapBakeTypeTitles = { EditorGUIUtility.TrTextContent("Realtime"), EditorGUIUtility.TrTextContent("Mixed"), EditorGUIUtility.TrTextContent("Baked") }; public static readonly int[] LightmapBakeTypeValues = { (int)LightmapBakeType.Realtime, (int)LightmapBakeType.Mixed, (int)LightmapBakeType.Baked }; public static readonly GUIContent[] LightTypeTitles = { EditorGUIUtility.TrTextContent("Spot"), EditorGUIUtility.TrTextContent("Directional"), EditorGUIUtility.TrTextContent("Point"), EditorGUIUtility.TrTextContent("Area (baked only)") }; public static readonly int[] LightTypeValues = { (int)LightType.Spot, (int)LightType.Directional, (int)LightType.Point, (int)LightType.Rectangle }; public static readonly GUIContent[] AreaLightShapeTitles = { EditorGUIUtility.TrTextContent("Rectangle"), EditorGUIUtility.TrTextContent("Disc") }; public static readonly int[] AreaLightShapeValues = { (int)AreaLightShape.Rectangle, (int)AreaLightShape.Disc }; } public bool isRealtime { get { return lightmapping.intValue == (int)LightmapBakeType.Realtime; } } public bool isMixed { get { return lightmapping.intValue == (int)LightmapBakeType.Mixed; } } public bool isCompletelyBaked { get { return lightmapping.intValue == (int)LightmapBakeType.Baked; } } public bool isBakedOrMixed { get { return !isRealtime; } } public bool isAreaLightType { get { return lightType.intValue == (int)LightType.Rectangle || lightType.intValue == (int)LightType.Disc; } } internal bool typeIsSame { get { return !lightType.hasMultipleDifferentValues; } } internal bool shadowTypeIsSame { get { return !shadowsType.hasMultipleDifferentValues; } } internal bool lightmappingTypeIsSame { get { return !lightmapping.hasMultipleDifferentValues; } } internal bool isPrefabAsset { get { if (m_SerializedObject == null || m_SerializedObject.targetObject == null) return false; return PrefabUtility.IsPartOfPrefabAsset(m_SerializedObject.targetObject); } } public Light light { get { return m_SerializedObject.targetObject as Light; } } public Texture cookie { get { return cookieProp.objectReferenceValue as Texture; } } internal bool showMixedModeUnsupportedWarning { get { return !isPrefabAsset && isMixed && lightmappingTypeIsSame && !SupportedRenderingFeatures.IsLightmapBakeTypeSupported(LightmapBakeType.Mixed); } } internal bool showBakedModeUnsupportedWarning { get { return !isPrefabAsset && isCompletelyBaked && lightmappingTypeIsSame && !SupportedRenderingFeatures.IsLightmapBakeTypeSupported(LightmapBakeType.Baked); } } internal bool showBounceWarning { get { return typeIsSame && (light.type == LightType.Point || light.type == LightType.Spot) && lightmappingTypeIsSame && isRealtime && !bounceIntensity.hasMultipleDifferentValues && bounceIntensity.floatValue > 0.0F; } } internal bool showBakingWarning { get { return !isPrefabAsset && !Lightmapping.GetLightingSettingsOrDefaultsFallback().bakedGI && lightmappingTypeIsSame && isBakedOrMixed; } } internal bool showCookieSpotRepeatWarning { get { RenderPipelineAsset srpAsset = GraphicsSettings.currentRenderPipeline; bool usingSRP = srpAsset != null; return typeIsSame && light.type == LightType.Spot && !cookieProp.hasMultipleDifferentValues && cookie && cookie.wrapMode != TextureWrapMode.Clamp && !usingSRP; } } internal bool showCookieNotEnabledWarning { get { return typeIsSame && isCompletelyBaked && !cookieProp.hasMultipleDifferentValues && cookie && !EditorSettings.enableCookiesInLightmapper; } } internal bool showCookieNotEnabledInfo { get { return typeIsSame && isMixed && !cookieProp.hasMultipleDifferentValues && cookie && !EditorSettings.enableCookiesInLightmapper; } } public void OnEnable() { lightType = m_SerializedObject.FindProperty("m_Type"); range = m_SerializedObject.FindProperty("m_Range"); spotAngle = m_SerializedObject.FindProperty("m_SpotAngle"); innerSpotAngle = m_SerializedObject.FindProperty("m_InnerSpotAngle"); enableSpotReflector = m_SerializedObject.FindProperty("m_EnableSpotReflector"); cookieSize = m_SerializedObject.FindProperty("m_CookieSize"); color = m_SerializedObject.FindProperty("m_Color"); intensity = m_SerializedObject.FindProperty("m_Intensity"); bounceIntensity = m_SerializedObject.FindProperty("m_BounceIntensity"); lightUnit = m_SerializedObject.FindProperty("m_LightUnit"); luxAtDistance = m_SerializedObject.FindProperty("m_LuxAtDistance"); colorTemperature = m_SerializedObject.FindProperty("m_ColorTemperature"); useColorTemperature = m_SerializedObject.FindProperty("m_UseColorTemperature"); cookieProp = m_SerializedObject.FindProperty("m_Cookie"); shadowsType = m_SerializedObject.FindProperty("m_Shadows.m_Type"); shadowsStrength = m_SerializedObject.FindProperty("m_Shadows.m_Strength"); shadowsResolution = m_SerializedObject.FindProperty("m_Shadows.m_Resolution"); shadowsBias = m_SerializedObject.FindProperty("m_Shadows.m_Bias"); shadowsNormalBias = m_SerializedObject.FindProperty("m_Shadows.m_NormalBias"); shadowsNearPlane = m_SerializedObject.FindProperty("m_Shadows.m_NearPlane"); halo = m_SerializedObject.FindProperty("m_DrawHalo"); flare = m_SerializedObject.FindProperty("m_Flare"); renderMode = m_SerializedObject.FindProperty("m_RenderMode"); cullingMask = m_SerializedObject.FindProperty("m_CullingMask"); renderingLayerMask = m_SerializedObject.FindProperty("m_RenderingLayerMask"); lightmapping = m_SerializedObject.FindProperty("m_Lightmapping"); areaSizeX = m_SerializedObject.FindProperty("m_AreaSize.x"); areaSizeY = m_SerializedObject.FindProperty("m_AreaSize.y"); bakedShadowRadiusProp = m_SerializedObject.FindProperty("m_ShadowRadius"); bakedShadowAngleProp = m_SerializedObject.FindProperty("m_ShadowAngle"); if (m_KelvinGradientTexture == null) m_KelvinGradientTexture = CreateKelvinGradientTexture("KelvinGradientTexture", 300, 16, kMinKelvin, kMaxKelvin); } public void OnDestroy() { if (m_KelvinGradientTexture != null) DestroyImmediate(m_KelvinGradientTexture); } static Texture2D CreateKelvinGradientTexture(string name, int width, int height, float minKelvin, float maxKelvin) { // The texture is draw with a simple internal-GUITexture shader that don't perform any gamma correction // so we need to provide value for color temperature texture in gamma space and use a linear format for the texture var texture = new Texture2D(width, height, TextureFormat.ARGB32, false, true) { name = name, hideFlags = HideFlags.HideAndDontSave }; var pixels = new Color32[width * height]; float mappedMax = Mathf.Pow(maxKelvin, 1f / kSliderPower); float mappedMin = Mathf.Pow(minKelvin, 1f / kSliderPower); for (int i = 0; i < width; i++) { float pixelfrac = i / (float)(width - 1); float mappedValue = (mappedMax - mappedMin) * pixelfrac + mappedMin; float kelvin = Mathf.Pow(mappedValue, kSliderPower); Color kelvinColor = Mathf.CorrelatedColorTemperatureToRGB(kelvin); for (int j = 0; j < height; j++) pixels[j * width + i] = kelvinColor.gamma; } texture.SetPixels32(pixels); texture.wrapMode = TextureWrapMode.Clamp; texture.Apply(); return texture; } public void Update() { m_SerializedObject.Update(); } public void DrawLightType() { // To the user, we will only display it as a area light, but under the hood, we have Rectangle and Disc. This is not to confuse people // who still use our legacy light inspector. int selectedLightType = lightType.intValue; int selectedShape = isAreaLightType ? lightType.intValue : (int)AreaLightShape.None; var lightTypeRect = EditorGUILayout.GetControlRect(); EditorGUI.BeginProperty(lightTypeRect, Styles.Type, lightType); EditorGUI.BeginChangeCheck(); int type; if (Styles.LightTypeValues.Contains(lightType.intValue)) { // ^ The currently selected light type is supported in the // current pipeline. type = EditorGUI.IntPopup(lightTypeRect, Styles.Type, selectedLightType, Styles.LightTypeTitles, Styles.LightTypeValues); } else { // ^ The currently selected light type is not supported in // the current pipeline. Add it to the dropdown, since it // would show up as a blank entry. string currentTitle = ((LightType)lightType.intValue).ToString(); GUIContent[] titles = Styles.LightTypeTitles.Append(EditorGUIUtility.TrTextContent(currentTitle)).ToArray(); int[] values = Styles.LightTypeValues.Append(lightType.intValue).ToArray(); type = EditorGUI.IntPopup(lightTypeRect, Styles.Type, selectedLightType, titles, values); } if (EditorGUI.EndChangeCheck()) { AnnotationUtility.SetGizmosDirty(); lightType.intValue = type; } EditorGUI.EndProperty(); if (!Styles.LightTypeValues.Contains(lightType.intValue)) { EditorGUILayout.HelpBox( "This light type is not supported in the current active render pipeline. Change the light type or the active Render Pipeline to use this light.", MessageType.Info ); } if (isAreaLightType && selectedShape != (int)AreaLightShape.None) { var lightShapeRect = EditorGUILayout.GetControlRect(); EditorGUI.BeginProperty(lightShapeRect, Styles.Shape, lightType); EditorGUI.BeginChangeCheck(); int shape = EditorGUI.IntPopup(lightShapeRect, Styles.Shape, selectedShape, Styles.AreaLightShapeTitles, Styles.AreaLightShapeValues); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(light, "Adjust Light Shape"); lightType.intValue = shape; } EditorGUI.EndProperty(); } } public void DrawRange() { EditorGUILayout.PropertyField(range, Styles.Range); } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("showAreaOptions argument for DrawRange(showAreaOptions) has been removed. Use DrawRange() instead (UnityUpgradable).")] public void DrawRange(bool showAreaOptions) { DrawRange(); } public void DrawSpotAngle() { EditorGUILayout.Slider(spotAngle, 1f, 179f, Styles.SpotAngle); } public void DrawInnerAndOuterSpotAngle() { float textFieldWidth = 45f; float min = innerSpotAngle.floatValue; float max = spotAngle.floatValue; var rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight); // This widget is a little bit of a special case. // The right hand side of the min max slider will control the reset of the max value // The left hand side of the min max slider will control the reset of the min value // The label itself will not have a right click and reset value. rect = EditorGUI.PrefixLabel(rect, Styles.InnerOuterSpotAngle); EditorGUI.BeginProperty(new Rect(rect) { width = rect.width * 0.5f }, Styles.InnerOuterSpotAngle, innerSpotAngle); EditorGUI.BeginProperty(new Rect(rect) { xMin = rect.x + rect.width * 0.5f }, GUIContent.none, spotAngle); var minRect = new Rect(rect) { width = textFieldWidth }; var maxRect = new Rect(rect) { xMin = rect.xMax - textFieldWidth }; var sliderRect = new Rect(rect) { xMin = minRect.xMax + EditorGUI.kSpacing, xMax = maxRect.xMin - EditorGUI.kSpacing }; EditorGUI.DelayedFloatField(minRect, innerSpotAngle, GUIContent.none); EditorGUI.BeginChangeCheck(); EditorGUI.MinMaxSlider(sliderRect, ref min, ref max, 0f, 179f); if (EditorGUI.EndChangeCheck()) { innerSpotAngle.floatValue = min; spotAngle.floatValue = max; } EditorGUI.DelayedFloatField(maxRect, spotAngle, GUIContent.none); EditorGUI.EndProperty(); EditorGUI.EndProperty(); } public void DrawArea() { if (lightType.intValue == (int)LightType.Rectangle) { EditorGUILayout.PropertyField(areaSizeX, Styles.AreaWidth); EditorGUILayout.PropertyField(areaSizeY, Styles.AreaHeight); } else if (lightType.intValue == (int)LightType.Disc) { EditorGUILayout.PropertyField(areaSizeX, Styles.AreaRadius); } } public void DrawColor() { if (GraphicsSettings.lightsUseLinearIntensity && GraphicsSettings.lightsUseColorTemperature) { EditorGUILayout.PropertyField(useColorTemperature, Styles.UseColorTemperature); if (useColorTemperature.boolValue) { EditorGUILayout.LabelField(Styles.Color); EditorGUI.indentLevel += 1; EditorGUILayout.PropertyField(color, Styles.ColorFilter); EditorGUILayout.SliderWithTexture(Styles.ColorTemperature, colorTemperature, kMinKelvin, kMaxKelvin, kSliderPower, m_KelvinGradientTexture); EditorGUI.indentLevel -= 1; } else EditorGUILayout.PropertyField(color, Styles.Color); } else EditorGUILayout.PropertyField(color, Styles.Color); } void OnLightmappingItemSelected(object userData) { lightmapping.intValue = (int)userData; m_SerializedObject.ApplyModifiedProperties(); } public void DrawLightmapping() { var rect = EditorGUILayout.GetControlRect(); EditorGUI.BeginProperty(rect, Styles.LightmappingMode, lightmapping); rect = EditorGUI.PrefixLabel(rect, Styles.LightmappingMode); int index = Math.Max(0, Array.IndexOf(Styles.LightmapBakeTypeValues, lightmapping.intValue)); if (EditorGUI.DropdownButton(rect, Styles.LightmapBakeTypeTitles[index], FocusType.Passive)) { var menu = new GenericMenu(); for (int i = 0; i < Styles.LightmapBakeTypeValues.Length; i++) { int value = Styles.LightmapBakeTypeValues[i]; bool selected = (lightmappingTypeIsSame && (value == lightmapping.intValue)); if (((value == (int)LightmapBakeType.Mixed) || (value == (int)LightmapBakeType.Baked)) && ((!SupportedRenderingFeatures.IsLightmapBakeTypeSupported((LightmapBakeType)value) || !Lightmapping.GetLightingSettingsOrDefaultsFallback().bakedGI) && !isPrefabAsset)) { menu.AddDisabledItem(Styles.LightmapBakeTypeTitles[i], selected); } else { menu.AddItem(Styles.LightmapBakeTypeTitles[i], selected, OnLightmappingItemSelected, value); } } menu.DropDown(rect); } EditorGUI.EndProperty(); // first make sure that the modes arent unsupported, then unenabled if (showMixedModeUnsupportedWarning) EditorGUILayout.HelpBox(Styles.MixedUnsupportedWarning.text, MessageType.Warning); else if (showBakedModeUnsupportedWarning) EditorGUILayout.HelpBox(Styles.BakedUnsupportedWarning.text, MessageType.Warning); else if (showBakingWarning) EditorGUILayout.HelpBox(Styles.BakingWarning.text, MessageType.Warning); } internal void CheckLightmappingConsistency() { //Built-in render-pipeline only support baked area light, enforce it as this inspector is the built-in one. if (isAreaLightType && lightmapping.intValue != (int)LightmapBakeType.Baked) { lightmapping.intValue = (int)LightmapBakeType.Baked; m_SerializedObject.ApplyModifiedProperties(); } } public void DrawIntensity() { EditorGUILayout.PropertyField(intensity, Styles.Intensity); } public void DrawBounceIntensity() { if (SupportedRenderingFeatures.IsLightmapBakeTypeSupported(LightmapBakeType.Realtime)) { EditorGUILayout.PropertyField(bounceIntensity, Styles.LightBounceIntensityRealtimeGISupport); // No shadowing of indirect warning. if (showBounceWarning) { EditorGUILayout.HelpBox(Styles.IndirectBounceShadowWarning.text, MessageType.Warning); } } else { // no realtime gi support, no need to show this property if (lightmapping.intValue != (int)LightmapBakeType.Realtime) EditorGUILayout.PropertyField(bounceIntensity, Styles.LightBounceIntensity); } } static Object TextureValidator(Object[] references, System.Type objType, SerializedProperty property, EditorGUI.ObjectFieldValidatorOptions options) { // Accept RenderTextures of correct dimension Texture validated = (RenderTexture)EditorGUI.ValidateObjectFieldAssignment(references, typeof(RenderTexture), property, options); if (validated != null) { if (objType == typeof(Texture2D) && validated.dimension != TextureDimension.Tex2D) validated = null; else if (objType == typeof(Texture3D) && validated.dimension != TextureDimension.Tex3D) validated = null; else if (objType == typeof(Cubemap) && validated.dimension != TextureDimension.Cube) validated = null; } // Accept regular textures if (validated == null) validated = (Texture)EditorGUI.ValidateObjectFieldAssignment(references, objType, property, options); return validated; } static void TexturePropertyBody(Rect position, SerializedProperty prop, LightType cookieLightType) { EditorGUI.BeginChangeCheck(); int controlID = GUIUtility.GetControlID(12354, FocusType.Keyboard, position); Type type = null; switch (cookieLightType) { case LightType.Spot: case LightType.Directional: case LightType.Rectangle: case LightType.Disc: type = typeof(Texture2D); break; case LightType.Point: type = typeof(Cubemap); break; default: type = typeof(Texture); break; } var newValue = EditorGUI.DoObjectField(position, position, controlID, prop.objectReferenceValue, prop.objectReferenceValue, type, TextureValidator, false, typeof(RenderTexture)) as Texture; if (EditorGUI.EndChangeCheck()) prop.objectReferenceValue = newValue; } public void DrawCookieProperty(SerializedProperty cookieProperty, GUIContent content, LightType cookieLightType) { Rect controlRect = EditorGUILayout.GetControlRect(); Rect thumbRect, labelRect; EditorGUI.GetRectsForMiniThumbnailField(controlRect, out thumbRect, out labelRect); EditorGUI.HandlePrefixLabel(controlRect, labelRect, content, 0, EditorStyles.label); TexturePropertyBody(thumbRect, cookieProperty, cookieLightType); } public void DrawCookie() { // Don't draw cookie texture UI for area lights as cookies are not supported by them (except by HDRP, but they handle their own UI drawing logic) if (isAreaLightType) return; DrawCookieProperty(cookieProp, Styles.CookieTexture, (LightType)lightType.intValue); if (showCookieSpotRepeatWarning) { // warn on spotlights if the cookie is set to repeat EditorGUILayout.HelpBox(Styles.CookieSpotRepeatWarning.text, MessageType.Warning); } if (showCookieNotEnabledWarning) { // warn if cookie support is not enabled for baked lights EditorGUILayout.HelpBox(Styles.CookieNotEnabledWarning.text, MessageType.Warning); } if (showCookieNotEnabledInfo) { // info if cookie support is not enabled for mixed lights EditorGUILayout.HelpBox(Styles.CookieNotEnabledInfo.text, MessageType.Info); } } public void DrawCookieSize() { EditorGUI.indentLevel++; EditorGUILayout.PropertyField(cookieSize, Styles.CookieSize); EditorGUI.indentLevel--; } public void DrawHalo() { EditorGUILayout.PropertyField(halo, Styles.DrawHalo); } public void DrawFlare() { EditorGUILayout.PropertyField(flare, Styles.Flare); } public void DrawRenderMode() { EditorGUILayout.PropertyField(renderMode, Styles.RenderMode); } public void DrawCullingMask() { EditorGUILayout.PropertyField(cullingMask, Styles.CullingMask); } public void DrawRenderingLayerMask() { if (!GraphicsSettings.isScriptableRenderPipelineEnabled) return; using var changeScope = new EditorGUI.ChangeCheckScope(); var mask = renderingLayerMask.uintValue; mask = EditorGUILayout.RenderingLayerMaskField(Styles.RenderingLayerMask, mask); if (changeScope.changed) renderingLayerMask.uintValue = mask; } public void ApplyModifiedProperties() { m_SerializedObject.ApplyModifiedProperties(); } public void DrawShadowsType() { if (isAreaLightType) { var rect = EditorGUILayout.GetControlRect(); EditorGUI.BeginProperty(rect, Styles.CastShadows, shadowsType); EditorGUI.BeginChangeCheck(); bool shadows = EditorGUI.Toggle(rect, Styles.CastShadows, shadowsType.intValue != (int)LightShadows.None); if (EditorGUI.EndChangeCheck()) { shadowsType.intValue = shadows ? (int)LightShadows.Soft : (int)LightShadows.None; } EditorGUI.EndProperty(); } else { EditorGUILayout.PropertyField(shadowsType, Styles.ShadowType); } } public void DrawBakedShadowRadius() { using (new EditorGUI.DisabledScope(shadowsType.intValue != (int)LightShadows.Soft)) { EditorGUILayout.PropertyField(bakedShadowRadiusProp, Styles.BakedShadowRadius); } } public void DrawBakedShadowAngle() { using (new EditorGUI.DisabledScope(shadowsType.intValue != (int)LightShadows.Soft)) { EditorGUILayout.Slider(bakedShadowAngleProp, 0.0F, 90.0F, Styles.BakedShadowAngle); } } public void DrawRuntimeShadow() { EditorGUILayout.LabelField(Styles.ShadowRealtimeSettings); EditorGUI.indentLevel += 1; EditorGUILayout.Slider(shadowsStrength, 0f, 1f, Styles.ShadowStrength); EditorGUILayout.PropertyField(shadowsResolution, Styles.ShadowResolution); EditorGUILayout.Slider(shadowsBias, 0.0f, 2.0f, Styles.ShadowBias); EditorGUILayout.Slider(shadowsNormalBias, 0.0f, 3.0f, Styles.ShadowNormalBias); // this min bound should match the calculation in SharedLightData::GetNearPlaneMinBound() float nearPlaneMinBound = Mathf.Min(0.01f * range.floatValue, 0.1f); EditorGUILayout.Slider(shadowsNearPlane, nearPlaneMinBound, 10.0f, Styles.ShadowNearPlane); EditorGUI.indentLevel -= 1; } } private static class StylesEx { public static readonly GUIContent iconRemove = EditorGUIUtility.TrIconContent("Toolbar Minus", "Remove command buffer"); public static readonly GUIContent DisabledLightWarning = EditorGUIUtility.TrTextContent("Lighting has been disabled in at least one Scene view. Any changes applied to lights in the Scene will not be updated in these views until Lighting has been enabled again."); public static readonly GUIStyle invisibleButton = "InvisibleButton"; } private Settings m_Settings; protected Settings settings => m_Settings ?? (m_Settings = new Settings(serializedObject)); private IMGUI.Controls.SphereBoundsHandle m_BoundsHandle = new IMGUI.Controls.SphereBoundsHandle(); AnimBool m_AnimShowSpotOptions = new AnimBool(); AnimBool m_AnimShowPointOptions = new AnimBool(); AnimBool m_AnimShowDirOptions = new AnimBool(); AnimBool m_AnimShowAreaOptions = new AnimBool(); AnimBool m_AnimShowRuntimeOptions = new AnimBool(); AnimBool m_AnimShowShadowOptions = new AnimBool(); AnimBool m_AnimBakedShadowAngleOptions = new AnimBool(); AnimBool m_AnimBakedShadowRadiusOptions = new AnimBool(); AnimBool m_AnimShowLightBounceIntensity = new AnimBool(); private bool m_CommandBuffersShown = true; protected static readonly Color kGizmoLight = new Color(254 / 255f, 253 / 255f, 136 / 255f, 128 / 255f); protected static readonly Color kGizmoDisabledLight = new Color(135 / 255f, 116 / 255f, 50 / 255f, 128 / 255f); static readonly Vector3[] directionalLightHandlesRayPositions = new Vector3[] { new Vector3(1, 0, 0), new Vector3(-1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, -1, 0), new Vector3(1, 1, 0).normalized, new Vector3(1, -1, 0).normalized, new Vector3(-1, 1, 0).normalized, new Vector3(-1, -1, 0).normalized }; private void SetOptions(AnimBool animBool, bool initialize, bool targetValue) { if (initialize) { animBool.value = targetValue; animBool.valueChanged.AddListener(Repaint); } else { animBool.target = targetValue; } } bool spotOptionsValue { get { return settings.typeIsSame && settings.light.type == LightType.Spot; } } bool pointOptionsValue { get { return settings.typeIsSame && settings.light.type == LightType.Point; } } bool dirOptionsValue { get { return settings.typeIsSame && settings.light.type == LightType.Directional; } } bool areaOptionsValue { get { return settings.typeIsSame && settings.isAreaLightType; } } bool runtimeOptionsValue { get { return settings.typeIsSame && ((settings.light.type != LightType.Rectangle && settings.light.type != LightType.Disc) && !settings.isCompletelyBaked); } } bool bakedShadowRadius { get { return settings.typeIsSame && (settings.light.type == LightType.Point || settings.light.type == LightType.Spot) && settings.isBakedOrMixed; } } bool bakedShadowAngle { get { return settings.typeIsSame && settings.light.type == LightType.Directional && settings.isBakedOrMixed; } } bool shadowOptionsValue { get { return settings.shadowTypeIsSame && settings.light.shadows != LightShadows.None; } } private void UpdateShowOptions(bool initialize) { SetOptions(m_AnimShowSpotOptions, initialize, spotOptionsValue); SetOptions(m_AnimShowPointOptions, initialize, pointOptionsValue); SetOptions(m_AnimShowDirOptions, initialize, dirOptionsValue); SetOptions(m_AnimShowShadowOptions, initialize, shadowOptionsValue); SetOptions(m_AnimShowAreaOptions, initialize, areaOptionsValue); SetOptions(m_AnimShowRuntimeOptions, initialize, runtimeOptionsValue); SetOptions(m_AnimBakedShadowAngleOptions, initialize, bakedShadowAngle); SetOptions(m_AnimBakedShadowRadiusOptions, initialize, bakedShadowRadius); SetOptions(m_AnimShowLightBounceIntensity, initialize, true); } protected virtual void OnEnable() { settings.OnEnable(); UpdateShowOptions(true); } protected virtual void OnDestroy() { if (m_Settings != null) { m_Settings.OnDestroy(); m_Settings = null; } } private void CommandBufferGUI() { // Command buffers are not serialized data, so can't get to them through // serialized property (hence no multi-edit). if (targets.Length != 1) return; var light = target as Light; if (light == null) return; int count = light.commandBufferCount; if (count == 0) return; m_CommandBuffersShown = GUILayout.Toggle(m_CommandBuffersShown, GUIContent.Temp(count + " command buffers"), EditorStyles.foldout); if (!m_CommandBuffersShown) return; EditorGUI.indentLevel++; foreach (LightEvent le in (LightEvent[])System.Enum.GetValues(typeof(LightEvent))) { CommandBuffer[] cbs = light.GetCommandBuffers(le); foreach (CommandBuffer cb in cbs) { using (new GUILayout.HorizontalScope()) { // row with event & command buffer information label Rect rowRect = GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.miniLabel); rowRect.xMin += EditorGUI.indent; Rect minusRect = GetRemoveButtonRect(rowRect); rowRect.xMax = minusRect.x; GUI.Label(rowRect, string.Format("{0}: {1} ({2})", le, cb.name, EditorUtility.FormatBytes(cb.sizeInBytes)), EditorStyles.miniLabel); // and a button to remove it if (GUI.Button(minusRect, StylesEx.iconRemove, StylesEx.invisibleButton)) { light.RemoveCommandBuffer(le, cb); SceneView.RepaintAll(); PlayModeView.RepaintAll(); GUIUtility.ExitGUI(); } } } } // "remove all" button using (new GUILayout.HorizontalScope()) { GUILayout.FlexibleSpace(); if (GUILayout.Button("Remove all", EditorStyles.miniButton)) { light.RemoveAllCommandBuffers(); SceneView.RepaintAll(); PlayModeView.RepaintAll(); } } EditorGUI.indentLevel--; } static Rect GetRemoveButtonRect(Rect r) { var buttonSize = StylesEx.invisibleButton.CalcSize(StylesEx.iconRemove); return new Rect(r.xMax - buttonSize.x, r.y + (int)(r.height / 2 - buttonSize.y / 2), buttonSize.x, buttonSize.y); } public override void OnInspectorGUI() { settings.Update(); UpdateShowOptions(false); // Light type (shape and usage) settings.DrawLightType(); // When we are switching between two light types that don't show the range (directional lights don't) // we want the fade group to stay hidden. if (EditorGUILayout.BeginFadeGroup(1.0f - m_AnimShowDirOptions.faded)) settings.DrawRange(); EditorGUILayout.EndFadeGroup(); if (EditorGUILayout.BeginFadeGroup(m_AnimShowSpotOptions.faded)) settings.DrawSpotAngle(); EditorGUILayout.EndFadeGroup(); // Area width & height if (EditorGUILayout.BeginFadeGroup(m_AnimShowAreaOptions.faded)) settings.DrawArea(); EditorGUILayout.EndFadeGroup(); settings.DrawColor(); // Baking type settings.CheckLightmappingConsistency(); if (EditorGUILayout.BeginFadeGroup(1.0F - m_AnimShowAreaOptions.faded)) settings.DrawLightmapping(); EditorGUILayout.EndFadeGroup(); settings.DrawIntensity(); if (EditorGUILayout.BeginFadeGroup(m_AnimShowLightBounceIntensity.faded)) settings.DrawBounceIntensity(); EditorGUILayout.EndFadeGroup(); ShadowsGUI(); settings.DrawCookie(); // Cookie size also requires directional light if (EditorGUILayout.BeginFadeGroup(m_AnimShowDirOptions.faded)) settings.DrawCookieSize(); EditorGUILayout.EndFadeGroup(); settings.DrawHalo(); settings.DrawFlare(); settings.DrawRenderMode(); settings.DrawCullingMask(); settings.DrawRenderingLayerMask(); if (SceneView.lastActiveSceneView != null && SceneView.lastActiveSceneView.sceneLighting == false) EditorGUILayout.HelpBox(StylesEx.DisabledLightWarning.text, MessageType.Warning); CommandBufferGUI(); settings.ApplyModifiedProperties(); serializedObject.ApplyModifiedProperties(); } void ShadowsGUI() { //NOTE: FadeGroup's dont support nesting. Thus we just multiply the fade values here. settings.DrawShadowsType(); EditorGUI.indentLevel += 1; float show = m_AnimShowShadowOptions.faded; // Baked Shadow radius if (EditorGUILayout.BeginFadeGroup(show * m_AnimBakedShadowRadiusOptions.faded)) settings.DrawBakedShadowRadius(); EditorGUILayout.EndFadeGroup(); // Baked Shadow angle if (EditorGUILayout.BeginFadeGroup(show * m_AnimBakedShadowAngleOptions.faded)) settings.DrawBakedShadowAngle(); EditorGUILayout.EndFadeGroup(); // Runtime shadows - shadow strength, resolution, bias if (EditorGUILayout.BeginFadeGroup(show * m_AnimShowRuntimeOptions.faded)) settings.DrawRuntimeShadow(); EditorGUILayout.EndFadeGroup(); EditorGUI.indentLevel -= 1; } protected virtual void OnSceneGUI() { if (!target) return; Light t = target as Light; Color temp = Handles.color; if (t.enabled) Handles.color = kGizmoLight; else Handles.color = kGizmoDisabledLight; float thisRange = t.range; switch (t.type) { case LightType.Directional: Vector3 lightPos = t.transform.position; float lightSize; using (new Handles.DrawingScope(Matrix4x4.identity)) //be sure no matrix affect the size computation { lightSize = HandleUtility.GetHandleSize(lightPos); } float radius = lightSize * 0.2f; using (new Handles.DrawingScope(Matrix4x4.TRS(lightPos, t.transform.rotation, Vector3.one))) { Handles.DrawWireDisc(Vector3.zero, Vector3.forward, radius); foreach (Vector3 normalizedPos in directionalLightHandlesRayPositions) { Vector3 pos = normalizedPos * radius; Handles.DrawLine(pos, pos + new Vector3(0, 0, lightSize)); } } break; case LightType.Point: thisRange = Handles.RadiusHandle(Quaternion.identity, t.transform.position, thisRange); if (GUI.changed) { Undo.RecordObject(t, "Adjust Point Light"); t.range = thisRange; } break; case LightType.Spot: Transform tr = t.transform; Vector3 circleCenter = tr.position; Vector3 arrivalCenter = circleCenter + tr.forward * t.range; float lightDisc = t.range * Mathf.Tan(Mathf.Deg2Rad * t.spotAngle / 2.0f); Handles.DrawLine(circleCenter, arrivalCenter + tr.up * lightDisc); Handles.DrawLine(circleCenter, arrivalCenter - tr.up * lightDisc); Handles.DrawLine(circleCenter, arrivalCenter + tr.right * lightDisc); Handles.DrawLine(circleCenter, arrivalCenter - tr.right * lightDisc); Handles.DrawWireDisc(arrivalCenter, tr.forward, lightDisc); Handles.color = GetLightHandleColor(Handles.color); Vector2 angleAndRange = new Vector2(t.spotAngle, t.range); angleAndRange = Handles.ConeHandle(t.transform.rotation, t.transform.position, angleAndRange, 1.0f, 1.0f, true); if (GUI.changed) { Undo.RecordObject(t, "Adjust Spot Light"); t.spotAngle = angleAndRange.x; t.range = Mathf.Max(angleAndRange.y, 0.01F); } break; case LightType.Rectangle: EditorGUI.BeginChangeCheck(); Vector2 size = Handles.DoRectHandles(t.transform.rotation, t.transform.position, t.areaSize, false); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(t, "Adjust Rect Light"); t.areaSize = size; } // Draw the area light's normal only if it will not overlap with the current tool if (!((Tools.current == Tool.Move || Tools.current == Tool.Scale) && Tools.pivotRotation == PivotRotation.Local)) Handles.DrawLine(t.transform.position, t.transform.position + t.transform.forward); break; case LightType.Disc: m_BoundsHandle.radius = t.areaSize.x; m_BoundsHandle.axes = IMGUI.Controls.PrimitiveBoundsHandle.Axes.X | IMGUI.Controls.PrimitiveBoundsHandle.Axes.Y; m_BoundsHandle.center = Vector3.zero; m_BoundsHandle.wireframeColor = Handles.color; m_BoundsHandle.handleColor = GetLightHandleColor(Handles.color); Matrix4x4 mat = new Matrix4x4(); mat.SetTRS(t.transform.position, t.transform.rotation, new Vector3(1, 1, 1)); EditorGUI.BeginChangeCheck(); using (new Handles.DrawingScope(Color.white, mat)) m_BoundsHandle.DrawHandle(); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(t, "Adjust Disc Light"); t.areaSize = new Vector2(m_BoundsHandle.radius, t.areaSize.y); } break; } Handles.color = temp; } private Color GetLightHandleColor(Color wireframeColor) { Color color = wireframeColor; color.a = Mathf.Clamp01(color.a * 2); return Handles.ToActiveColorSpace(color); } } }
UnityCsReference/Editor/Mono/Inspector/LightEditor.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/LightEditor.cs", "repo_id": "UnityCsReference", "token_count": 25410 }
321
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Rendering; using UObject = UnityEngine.Object; namespace UnityEditor { public class MeshPreview : IDisposable { internal static class Styles { public static readonly GUIContent wireframeToggle = EditorGUIUtility.TrTextContent("Wireframe", "Show wireframe"); public static GUIContent displayModeDropdown = EditorGUIUtility.TrTextContent("", "Change display mode"); public static GUIContent uvChannelDropdown = EditorGUIUtility.TrTextContent("", "Change active UV channel"); public static GUIStyle preSlider = "preSlider"; public static GUIStyle preSliderThumb = "preSliderThumb"; } internal class Settings : IDisposable { public DisplayMode displayMode { get => m_DisplayMode; set => SetValue(ref m_DisplayMode, value); } DisplayMode m_DisplayMode = DisplayMode.Shaded; public int activeUVChannel { get => m_ActiveUVChannel; set => SetValue(ref m_ActiveUVChannel, value); } int m_ActiveUVChannel = 0; public int activeBlendshape { get => m_ActiveBlendshape; set => SetValue(ref m_ActiveBlendshape, value); } int m_ActiveBlendshape = 0; public bool drawWire { get => m_DrawWire; set => SetValue(ref m_DrawWire, value); } bool m_DrawWire = true; public Vector3 orthoPosition { get => m_OrthoPosition; set => SetValue(ref m_OrthoPosition, value); } Vector3 m_OrthoPosition = new Vector3(0.0f, 0.0f, 0.0f); public Vector2 previewDir { get => m_PreviewDir; set => SetValue(ref m_PreviewDir, value); } Vector2 m_PreviewDir = new Vector2(0, 0); public Vector2 lightDir { get => m_LightDir; set => SetValue(ref m_LightDir, value); } Vector2 m_LightDir = new Vector2(0, 0); public Vector3 pivotPositionOffset { get => m_PivotPositionOffset; set => SetValue(ref m_PivotPositionOffset, value); } Vector3 m_PivotPositionOffset = Vector3.zero; public float zoomFactor { get => m_ZoomFactor; set => SetValue(ref m_ZoomFactor, value); } float m_ZoomFactor = 1.0f; public int checkerTextureMultiplier { get => m_CheckerTextureMultiplier; set => SetValue(ref m_CheckerTextureMultiplier, value); } int m_CheckerTextureMultiplier = 10; public Material shadedPreviewMaterial { get => m_ShadedPreviewMaterial; set => SetValue(ref m_ShadedPreviewMaterial, value); } Material m_ShadedPreviewMaterial; public Material activeMaterial { get => m_ActiveMaterial; set => SetValue(ref m_ActiveMaterial, value); } Material m_ActiveMaterial; public Material meshMultiPreviewMaterial { get => m_MeshMultiPreviewMaterial; set => SetValue(ref m_MeshMultiPreviewMaterial, value); } Material m_MeshMultiPreviewMaterial; public Material wireMaterial { get => m_WireMaterial; set => SetValue(ref m_WireMaterial, value); } Material m_WireMaterial; public Material lineMaterial { get => m_LineMaterial; set => SetValue(ref m_LineMaterial, value); } Material m_LineMaterial; public Texture2D checkeredTexture { get => m_CheckeredTexture; set => SetValue(ref m_CheckeredTexture, value); } Texture2D m_CheckeredTexture; public bool[] availableDisplayModes { get => m_AvailableDisplayModes; set => SetValue(ref m_AvailableDisplayModes, value); } bool[] m_AvailableDisplayModes = Enumerable.Repeat(true, 7).ToArray(); public bool[] availableUVChannels { get => m_AvailableUVChannels; set => SetValue(ref m_AvailableUVChannels, value); } bool[] m_AvailableUVChannels = Enumerable.Repeat(true, 8).ToArray(); public event Action changed; public Settings() { shadedPreviewMaterial = new Material(Shader.Find("Standard")); wireMaterial = CreateWireframeMaterial(); meshMultiPreviewMaterial = CreateMeshMultiPreviewMaterial(); lineMaterial = CreateLineMaterial(); checkeredTexture = EditorGUIUtility.LoadRequired("Previews/Textures/textureChecker.png") as Texture2D; activeMaterial = shadedPreviewMaterial; orthoPosition = new Vector3(0.5f, 0.5f, -1); previewDir = new Vector2(130, 0); lightDir = new Vector2(-40, -40); zoomFactor = 1.0f; } public void Dispose() { if (shadedPreviewMaterial != null) UObject.DestroyImmediate(shadedPreviewMaterial); if (wireMaterial != null) UObject.DestroyImmediate(wireMaterial); if (meshMultiPreviewMaterial != null) UObject.DestroyImmediate(meshMultiPreviewMaterial); if (lineMaterial != null) UObject.DestroyImmediate(lineMaterial); } void SetValue<T>(ref T setting, T newValue) { if (setting == null || !setting.Equals(newValue)) { setting = newValue; changed?.Invoke(); } } public void Copy(Settings other) { displayMode = other.displayMode; activeUVChannel = other.activeUVChannel; activeBlendshape = other.activeBlendshape; drawWire = other.drawWire; orthoPosition = other.orthoPosition; previewDir = other.previewDir; lightDir = other.lightDir; pivotPositionOffset = other.pivotPositionOffset; zoomFactor = other.zoomFactor; checkerTextureMultiplier = other.checkerTextureMultiplier; shadedPreviewMaterial = other.shadedPreviewMaterial; activeMaterial = other.activeMaterial; meshMultiPreviewMaterial = other.meshMultiPreviewMaterial; wireMaterial = other.wireMaterial; lineMaterial = other.lineMaterial; checkeredTexture = other.checkeredTexture; availableDisplayModes = new bool[other.availableDisplayModes.Length]; Array.Copy(other.availableDisplayModes, availableDisplayModes, other.availableDisplayModes.Length); availableUVChannels = new bool[other.availableUVChannels.Length]; Array.Copy(other.availableUVChannels, availableUVChannels, other.availableUVChannels.Length); } } static string[] m_DisplayModes = { "Shaded", "UV Checker", "UV Layout", "Vertex Color", "Normals", "Tangents", "Blendshapes" }; static string[] m_UVChannels = { "Channel 0", "Channel 1", "Channel 2", "Channel 3", "Channel 4", "Channel 5", "Channel 6", "Channel 7" }; internal enum DisplayMode { Shaded = 0, UVChecker = 1, UVLayout = 2, VertexColor = 3, Normals = 4, Tangent = 5, Blendshapes = 6 } Mesh m_Target; public Mesh mesh { get => m_Target; set => m_Target = value; } PreviewRenderUtility m_PreviewUtility; Settings m_Settings; internal event Action<MeshPreview> settingsChanged; Mesh m_BakedSkinnedMesh; List<string> m_BlendShapes; public MeshPreview(Mesh target) { m_Target = target; m_PreviewUtility = new PreviewRenderUtility(); m_PreviewUtility.camera.fieldOfView = 30.0f; m_PreviewUtility.camera.transform.position = new Vector3(5, 5, 0); m_Settings = new Settings(); //Fix for FogBugz case : 1364821 Inspector Model Preview orientation is reversed when Bake Axis Conversion is enabled var importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(target)) as ModelImporter; if (importer && importer.bakeAxisConversion) { m_Settings.previewDir += new Vector2(180,0); } m_Settings.changed += OnSettingsChanged; m_BlendShapes = new List<string>(); CheckAvailableAttributes(); } public void Dispose() { DestroyBakedSkinnedMesh(); m_PreviewUtility.Cleanup(); m_Settings.changed -= OnSettingsChanged; m_Settings.Dispose(); } void OnSettingsChanged() { settingsChanged?.Invoke(this); } static Material CreateWireframeMaterial() { var shader = Shader.FindBuiltin("Internal-Colored.shader"); if (!shader) { Debug.LogWarning("Could not find the built-in Colored shader"); return null; } var mat = new Material(shader); mat.hideFlags = HideFlags.HideAndDontSave; mat.SetColor("_Color", new Color(0, 0, 0, 0.3f)); mat.SetFloat("_ZWrite", 0.0f); mat.SetFloat("_ZBias", -1.0f); return mat; } static Material CreateMeshMultiPreviewMaterial() { var shader = EditorGUIUtility.LoadRequired("Previews/MeshPreviewShader.shader") as Shader; if (!shader) { Debug.LogWarning("Could not find the built in Mesh preview shader"); return null; } var mat = new Material(shader); mat.hideFlags = HideFlags.HideAndDontSave; return mat; } static Material CreateLineMaterial() { Shader shader = Shader.FindBuiltin("Internal-Colored.shader"); if (!shader) { Debug.LogWarning("Could not find the built-in Colored shader"); return null; } var mat = new Material(shader); mat.hideFlags = HideFlags.HideAndDontSave; mat.SetFloat("_SrcBlend", (float)BlendMode.SrcAlpha); mat.SetFloat("_DstBlend", (float)BlendMode.OneMinusSrcAlpha); mat.SetFloat("_Cull", (float)CullMode.Off); mat.SetFloat("_ZWrite", 0.0f); return mat; } void ResetView() { m_Settings.zoomFactor = 1.0f; m_Settings.orthoPosition = new Vector3(0.5f, 0.5f, -1); m_Settings.pivotPositionOffset = Vector3.zero; m_Settings.activeUVChannel = 0; m_Settings.meshMultiPreviewMaterial.SetFloat("_UVChannel", (float)m_Settings.activeUVChannel); m_Settings.meshMultiPreviewMaterial.SetTexture("_MainTex", null); m_Settings.activeBlendshape = 0; } void FrameObject() { m_Settings.zoomFactor = 1.0f; m_Settings.orthoPosition = new Vector3(0.5f, 0.5f, -1); m_Settings.pivotPositionOffset = Vector3.zero; } void CheckAvailableAttributes() { if (!mesh.HasVertexAttribute(VertexAttribute.Color)) m_Settings.availableDisplayModes[(int)DisplayMode.VertexColor] = false; if (!mesh.HasVertexAttribute(VertexAttribute.Normal)) m_Settings.availableDisplayModes[(int)DisplayMode.Normals] = false; if (!mesh.HasVertexAttribute(VertexAttribute.Tangent)) m_Settings.availableDisplayModes[(int)DisplayMode.Tangent] = false; int index = 0; for (int i = 4; i < 12; i++) { if (!mesh.HasVertexAttribute((VertexAttribute)i)) m_Settings.availableUVChannels[index] = false; index++; } var blendShapeCount = mesh.blendShapeCount; if (blendShapeCount > 0) { for (int i = 0; i < blendShapeCount; i++) { m_BlendShapes.Add(mesh.GetBlendShapeName(i)); } } else { m_Settings.availableDisplayModes[(int)DisplayMode.Blendshapes] = false; } } void DoPopup(Rect popupRect, string[] elements, int selectedIndex, GenericMenu.MenuFunction2 func, bool[] disabledItems) { GenericMenu menu = new GenericMenu(); for (int i = 0; i < elements.Length; i++) { var element = elements[i]; if (element == m_DisplayModes[(int)DisplayMode.Blendshapes] && Selection.count > 1) continue; if (disabledItems == null || disabledItems[i]) menu.AddItem(new GUIContent(element), i == selectedIndex, func, i); else menu.AddDisabledItem(new GUIContent(element)); } menu.DropDown(popupRect); } void SetUVChannel(object data) { int popupIndex = (int)data; if (popupIndex < 0 || popupIndex >= m_Settings.availableUVChannels.Length) return; m_Settings.activeUVChannel = popupIndex; if (m_Settings.displayMode == DisplayMode.UVLayout || m_Settings.displayMode == DisplayMode.UVChecker) m_Settings.activeMaterial.SetFloat("_UVChannel", (float)popupIndex); } void DestroyBakedSkinnedMesh() { if (m_BakedSkinnedMesh) UObject.DestroyImmediate(m_BakedSkinnedMesh); } void SetDisplayMode(object data) { int popupIndex = (int)data; if (popupIndex < 0 || popupIndex >= m_DisplayModes.Length) return; m_Settings.displayMode = (DisplayMode)popupIndex; DestroyBakedSkinnedMesh(); switch (m_Settings.displayMode) { case DisplayMode.Shaded: OnDropDownAction(m_Settings.shadedPreviewMaterial, 0, false); break; case DisplayMode.UVChecker: OnDropDownAction(m_Settings.meshMultiPreviewMaterial, 4, false); m_Settings.meshMultiPreviewMaterial.SetTexture("_MainTex", m_Settings.checkeredTexture); m_Settings.meshMultiPreviewMaterial.mainTextureScale = new Vector2(m_Settings.checkerTextureMultiplier, m_Settings.checkerTextureMultiplier); break; case DisplayMode.UVLayout: OnDropDownAction(m_Settings.meshMultiPreviewMaterial, 0, true); break; case DisplayMode.VertexColor: OnDropDownAction(m_Settings.meshMultiPreviewMaterial, 1, false); break; case DisplayMode.Normals: OnDropDownAction(m_Settings.meshMultiPreviewMaterial, 2, false); break; case DisplayMode.Tangent: OnDropDownAction(m_Settings.meshMultiPreviewMaterial, 3, false); break; case DisplayMode.Blendshapes: OnDropDownAction(m_Settings.shadedPreviewMaterial, 0, false); BakeSkinnedMesh(); break; } } void SetBlendshape(object data) { int popupIndex = (int)data; if (popupIndex < 0 || popupIndex >= m_BlendShapes.Count) return; m_Settings.activeBlendshape = popupIndex; DestroyBakedSkinnedMesh(); BakeSkinnedMesh(); } internal void CopySettings(MeshPreview other) { m_Settings.Copy(other.m_Settings); } internal static void RenderMeshPreview( Mesh mesh, PreviewRenderUtility previewUtility, Settings settings, int meshSubset) { if (mesh == null || previewUtility == null) return; Bounds bounds = mesh.bounds; Transform renderCamTransform = previewUtility.camera.GetComponent<Transform>(); previewUtility.camera.nearClipPlane = 0.0001f; previewUtility.camera.farClipPlane = 1000f; if (settings.displayMode == DisplayMode.UVLayout) { previewUtility.camera.orthographic = true; previewUtility.camera.orthographicSize = settings.zoomFactor; renderCamTransform.position = settings.orthoPosition; renderCamTransform.rotation = Quaternion.identity; DrawUVLayout(mesh, previewUtility, settings); return; } float halfSize = bounds.extents.magnitude; float distance = 4.0f * halfSize; previewUtility.camera.orthographic = false; Quaternion camRotation = Quaternion.identity; Vector3 camPosition = camRotation * Vector3.forward * (-distance * settings.zoomFactor) + settings.pivotPositionOffset; renderCamTransform.position = camPosition; renderCamTransform.rotation = camRotation; previewUtility.lights[0].intensity = 1.1f; previewUtility.lights[0].transform.rotation = Quaternion.Euler(-settings.lightDir.y, -settings.lightDir.x, 0); previewUtility.lights[1].intensity = 1.1f; previewUtility.lights[1].transform.rotation = Quaternion.Euler(settings.lightDir.y, settings.lightDir.x, 0); previewUtility.ambientColor = new Color(.1f, .1f, .1f, 0); RenderMeshPreviewSkipCameraAndLighting(mesh, bounds, previewUtility, settings, null, meshSubset); } static void DrawUVLayout(Mesh mesh, PreviewRenderUtility previewUtility, Settings settings) { GL.PushMatrix(); // draw UV grid settings.lineMaterial.SetPass(0); GL.LoadProjectionMatrix(previewUtility.camera.projectionMatrix); GL.MultMatrix(previewUtility.camera.worldToCameraMatrix); GL.Begin(GL.LINES); const float step = 0.125f; for (var g = -2.0f; g <= 3.0f; g += step) { var majorLine = Mathf.Abs(g - Mathf.Round(g)) < 0.01f; if (majorLine) { // major grid lines: larger area than [0..1] range, more opaque GL.Color(new Color(0.6f, 0.6f, 0.7f, 1.0f)); GL.Vertex3(-2, g, 0); GL.Vertex3(+3, g, 0); GL.Vertex3(g, -2, 0); GL.Vertex3(g, +3, 0); } else if (g >= 0 && g <= 1) { // minor grid lines: only within [0..1] area, more transparent GL.Color(new Color(0.6f, 0.6f, 0.7f, 0.5f)); GL.Vertex3(0, g, 0); GL.Vertex3(1, g, 0); GL.Vertex3(g, 0, 0); GL.Vertex3(g, 1, 0); } } GL.End(); // draw the mesh GL.LoadIdentity(); settings.meshMultiPreviewMaterial.SetPass(0); GL.wireframe = true; Graphics.DrawMeshNow(mesh, previewUtility.camera.worldToCameraMatrix); GL.wireframe = false; GL.PopMatrix(); } internal static Color GetSubMeshTint(int index) { // color palette generator based on "golden ratio" idea, like in // https://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/ var hue = Mathf.Repeat(index * 0.618f, 1); var sat = index == 0 ? 0f : 0.3f; var val = 1f; return Color.HSVToRGB(hue, sat, val); } internal static void RenderMeshPreviewSkipCameraAndLighting( Mesh mesh, Bounds bounds, PreviewRenderUtility previewUtility, Settings settings, MaterialPropertyBlock customProperties, int meshSubset) // -1 for whole mesh { if (mesh == null || previewUtility == null) return; Quaternion rot = Quaternion.Euler(settings.previewDir.y, 0, 0) * Quaternion.Euler(0, settings.previewDir.x, 0); Vector3 pos = rot * (-bounds.center); bool oldFog = RenderSettings.fog; Unsupported.SetRenderSettingsUseFogNoDirty(false); int submeshes = mesh.subMeshCount; var tintSubmeshes = false; var colorPropID = 0; if (submeshes > 1 && settings.displayMode == DisplayMode.Shaded && customProperties == null && meshSubset == -1) { tintSubmeshes = true; customProperties = new MaterialPropertyBlock(); colorPropID = Shader.PropertyToID("_Color"); } if (settings.activeMaterial != null) { previewUtility.camera.clearFlags = CameraClearFlags.Nothing; if (meshSubset < 0 || meshSubset >= submeshes) { for (int i = 0; i < submeshes; ++i) { if (tintSubmeshes) customProperties.SetColor(colorPropID, GetSubMeshTint(i)); previewUtility.DrawMesh(mesh, pos, rot, settings.activeMaterial, i, customProperties); } } else previewUtility.DrawMesh(mesh, pos, rot, settings.activeMaterial, meshSubset, customProperties); previewUtility.Render(); } if (settings.wireMaterial != null && settings.drawWire) { previewUtility.camera.clearFlags = CameraClearFlags.Nothing; GL.wireframe = true; if (tintSubmeshes) customProperties.SetColor(colorPropID, settings.wireMaterial.color); if (meshSubset < 0 || meshSubset >= submeshes) { for (int i = 0; i < submeshes; ++i) { // lines/points already are wire-like; it does not make sense to overdraw // them again with dark wireframe color var topology = mesh.GetTopology(i); if (topology == MeshTopology.Lines || topology == MeshTopology.LineStrip || topology == MeshTopology.Points) continue; previewUtility.DrawMesh(mesh, pos, rot, settings.wireMaterial, i, customProperties); } } else previewUtility.DrawMesh(mesh, pos, rot, settings.wireMaterial, meshSubset, customProperties); previewUtility.Render(); GL.wireframe = false; } Unsupported.SetRenderSettingsUseFogNoDirty(oldFog); } static void SetTransformMatrix(Transform tr, Matrix4x4 mat) { // extract position var pos = new Vector3(mat.m03, mat.m13, mat.m23); // extract scale var scale = mat.lossyScale; // now remove scale from the matrix axes, var invScale = new Vector3(1.0f / scale.x, 1.0f / scale.y, 1.0f / scale.z); mat.m00 *= invScale.x; mat.m10 *= invScale.x; mat.m20 *= invScale.x; mat.m01 *= invScale.y; mat.m11 *= invScale.y; mat.m21 *= invScale.y; mat.m02 *= invScale.z; mat.m12 *= invScale.z; mat.m22 *= invScale.z; // and extract rotation var rot = mat.rotation; tr.localPosition = pos; tr.localRotation = rot; tr.localScale = scale; } void BakeSkinnedMesh() { if (mesh == null) return; var baseGameObjectForSkinnedMeshRenderer = new GameObject { hideFlags = HideFlags.HideAndDontSave }; SkinnedMeshRenderer skinnedMeshRenderer = baseGameObjectForSkinnedMeshRenderer.AddComponent<SkinnedMeshRenderer>(); skinnedMeshRenderer.hideFlags = HideFlags.HideAndDontSave; m_BakedSkinnedMesh = new Mesh() { hideFlags = HideFlags.HideAndDontSave }; var isRigid = mesh.blendShapeCount > 0 && mesh.bindposes.Length == 0; Transform[] boneTransforms = new Transform[mesh.bindposes.Length]; if (!isRigid) { for (int i = 0; i < boneTransforms.Length; i++) { var bindPoseInverse = mesh.bindposes[i].inverse; boneTransforms[i] = new GameObject().transform; boneTransforms[i].gameObject.hideFlags = HideFlags.HideAndDontSave; SetTransformMatrix(boneTransforms[i], bindPoseInverse); } skinnedMeshRenderer.bones = boneTransforms; } skinnedMeshRenderer.sharedMesh = mesh; skinnedMeshRenderer.SetBlendShapeWeight(m_Settings.activeBlendshape, 100f); skinnedMeshRenderer.BakeMesh(m_BakedSkinnedMesh); if (isRigid) m_BakedSkinnedMesh.RecalculateBounds(); skinnedMeshRenderer.sharedMesh = null; UObject.DestroyImmediate(skinnedMeshRenderer); UObject.DestroyImmediate(baseGameObjectForSkinnedMeshRenderer); if (!isRigid) { for (int i = 0; i < boneTransforms.Length; i++) UObject.DestroyImmediate(boneTransforms[i].gameObject); } } public Texture2D RenderStaticPreview(int width, int height) { if (!ShaderUtil.hardwareSupportsRectRenderTexture) return null; m_PreviewUtility.BeginStaticPreview(new Rect(0, 0, width, height)); DoRenderPreview(); return m_PreviewUtility.EndStaticPreview(); } void DoRenderPreview() { if (m_Settings.displayMode == DisplayMode.Blendshapes) RenderMeshPreview(m_BakedSkinnedMesh, m_PreviewUtility, m_Settings, -1); else RenderMeshPreview(mesh, m_PreviewUtility, m_Settings, -1); } public void OnPreviewGUI(Rect rect, GUIStyle background) { var evt = Event.current; if (!ShaderUtil.hardwareSupportsRectRenderTexture) { if (evt.type == EventType.Repaint) EditorGUI.DropShadowLabel(new Rect(rect.x, rect.y, rect.width, 40), "Mesh preview requires\nrender texture support"); return; } if ((evt.type == EventType.ValidateCommand || evt.type == EventType.ExecuteCommand) && evt.commandName == EventCommandNames.FrameSelected) { FrameObject(); evt.Use(); } if (evt.button <= 0 && m_Settings.displayMode != DisplayMode.UVLayout) m_Settings.previewDir = PreviewGUI.Drag2D(m_Settings.previewDir, rect); if (evt.button == 1 && m_Settings.displayMode != DisplayMode.UVLayout) m_Settings.lightDir = PreviewGUI.Drag2D(m_Settings.lightDir, rect); if (evt.type == EventType.ScrollWheel) MeshPreviewZoom(rect, evt); if (evt.type == EventType.MouseDrag && (m_Settings.displayMode == DisplayMode.UVLayout || evt.button == 2)) MeshPreviewPan(rect, evt); if (evt.type != EventType.Repaint) return; m_PreviewUtility.BeginPreview(rect, background); DoRenderPreview(); m_PreviewUtility.EndAndDrawPreview(rect); } public void OnPreviewSettings() { if (!ShaderUtil.hardwareSupportsRectRenderTexture) return; GUI.enabled = true; if (m_Settings.displayMode == DisplayMode.UVChecker) { int oldVal = m_Settings.checkerTextureMultiplier; float sliderWidth = EditorStyles.label.CalcSize(new GUIContent("--------")).x; Rect sliderRect = EditorGUILayout.GetControlRect(GUILayout.Width(sliderWidth)); sliderRect.x += 3; m_Settings.checkerTextureMultiplier = (int)GUI.HorizontalSlider(sliderRect, m_Settings.checkerTextureMultiplier, 30, 1, Styles.preSlider, Styles.preSliderThumb); if (oldVal != m_Settings.checkerTextureMultiplier) m_Settings.activeMaterial.mainTextureScale = new Vector2(m_Settings.checkerTextureMultiplier, m_Settings.checkerTextureMultiplier); } if (m_Settings.displayMode == DisplayMode.UVLayout || m_Settings.displayMode == DisplayMode.UVChecker) { float channelDropDownWidth = EditorStyles.toolbarDropDown.CalcSize(new GUIContent("Channel 6")).x; Rect channelDropdownRect = EditorGUILayout.GetControlRect(GUILayout.Width(channelDropDownWidth)); channelDropdownRect.y -= 1; channelDropdownRect.x += 5; GUIContent channel = new GUIContent("Channel " + m_Settings.activeUVChannel, Styles.uvChannelDropdown.tooltip); if (EditorGUI.DropdownButton(channelDropdownRect, channel, FocusType.Passive, EditorStyles.toolbarDropDown)) DoPopup(channelDropdownRect, m_UVChannels, m_Settings.activeUVChannel, SetUVChannel, m_Settings.availableUVChannels); } if (m_Settings.displayMode == DisplayMode.Blendshapes) { float blendshapesDropDownWidth = EditorStyles.toolbarDropDown.CalcSize(new GUIContent("Blendshapes")).x; Rect blendshapesDropdownRect = EditorGUILayout.GetControlRect(GUILayout.Width(blendshapesDropDownWidth)); blendshapesDropdownRect.y -= 1; blendshapesDropdownRect.x += 5; GUIContent blendshape = new GUIContent(m_BlendShapes[m_Settings.activeBlendshape], Styles.uvChannelDropdown.tooltip); if (EditorGUI.DropdownButton(blendshapesDropdownRect, blendshape, FocusType.Passive, EditorStyles.toolbarDropDown)) DoPopup(blendshapesDropdownRect, m_BlendShapes.ToArray(), m_Settings.activeBlendshape, SetBlendshape, null); } // calculate width based on the longest value in display modes float displayModeDropDownWidth = EditorStyles.toolbarDropDown.CalcSize(new GUIContent(m_DisplayModes[(int)DisplayMode.VertexColor])).x; Rect displayModeDropdownRect = EditorGUILayout.GetControlRect(GUILayout.Width(displayModeDropDownWidth)); displayModeDropdownRect.y -= 1; displayModeDropdownRect.x += 2; GUIContent displayModeDropdownContent = new GUIContent(m_DisplayModes[(int)m_Settings.displayMode], Styles.displayModeDropdown.tooltip); if (EditorGUI.DropdownButton(displayModeDropdownRect, displayModeDropdownContent, FocusType.Passive, EditorStyles.toolbarDropDown)) DoPopup(displayModeDropdownRect, m_DisplayModes, (int)m_Settings.displayMode, SetDisplayMode, m_Settings.availableDisplayModes); using (new EditorGUI.DisabledScope(m_Settings.displayMode == DisplayMode.UVLayout)) { m_Settings.drawWire = GUILayout.Toggle(m_Settings.drawWire, Styles.wireframeToggle, EditorStyles.toolbarButton); } } void OnDropDownAction(Material mat, int mode, bool flatUVs) { ResetView(); m_Settings.activeMaterial = mat; m_Settings.activeMaterial.SetFloat("_Mode", (float)mode); m_Settings.activeMaterial.SetFloat("_UVChannel", 0.0f); m_Settings.activeMaterial.SetFloat("_Cull", flatUVs ? (float)CullMode.Off : (float)CullMode.Back); } void MeshPreviewZoom(Rect rect, Event evt) { float zoomDelta = -(HandleUtility.niceMouseDeltaZoom * 0.5f) * 0.05f; var newZoom = m_Settings.zoomFactor + m_Settings.zoomFactor * zoomDelta; newZoom = Mathf.Clamp(newZoom, 0.1f, 10.0f); // we want to zoom around current mouse position var mouseViewPos = new Vector2( evt.mousePosition.x / rect.width, 1 - evt.mousePosition.y / rect.height); var mouseWorldPos = m_PreviewUtility.camera.ViewportToWorldPoint(mouseViewPos); var mouseToCamPos = m_Settings.orthoPosition - mouseWorldPos; var newCamPos = mouseWorldPos + mouseToCamPos * (newZoom / m_Settings.zoomFactor); if (m_Settings.displayMode != DisplayMode.UVLayout) { m_PreviewUtility.camera.transform.position = new Vector3(newCamPos.x, newCamPos.y, newCamPos.z); } else { m_Settings.orthoPosition = new Vector3(newCamPos.x, newCamPos.y, m_Settings.orthoPosition.z); } m_Settings.zoomFactor = newZoom; evt.Use(); } void MeshPreviewPan(Rect rect, Event evt) { var cam = m_PreviewUtility.camera; // event delta is in "screen" units of the preview rect, but the // preview camera is rendering into a render target that could // be different size; have to adjust drag position to match var delta = new Vector3( -evt.delta.x * cam.pixelWidth / rect.width, evt.delta.y * cam.pixelHeight / rect.height, 0); Vector3 screenPos; Vector3 worldPos; if (m_Settings.displayMode == DisplayMode.UVLayout) { screenPos = cam.WorldToScreenPoint(m_Settings.orthoPosition); screenPos += delta; worldPos = cam.ScreenToWorldPoint(screenPos); m_Settings.orthoPosition = new Vector3(worldPos.x, worldPos.y, m_Settings.orthoPosition.z); } else { screenPos = cam.WorldToScreenPoint(m_Settings.pivotPositionOffset); screenPos += delta; worldPos = cam.ScreenToWorldPoint(screenPos) - m_Settings.pivotPositionOffset; m_Settings.pivotPositionOffset += worldPos; } evt.Use(); } public static string GetInfoString(Mesh mesh) { if (mesh == null) return ""; string info = $"{mesh.vertexCount} Vertices, {InternalMeshUtil.GetPrimitiveCount(mesh)} Triangles"; int submeshes = mesh.subMeshCount; if (submeshes > 1) info += $", {submeshes} Sub Meshes"; int blendShapeCount = mesh.blendShapeCount; if (blendShapeCount > 0) info += $", {blendShapeCount} Blend Shapes"; info += " | " + InternalMeshUtil.GetVertexFormat(mesh); return info; } } }
UnityCsReference/Editor/Mono/Inspector/MeshPreview.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/MeshPreview.cs", "repo_id": "UnityCsReference", "token_count": 17150 }
322
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEngine.Bindings; namespace UnityEditor { [NativeHeader("Runtime/Misc/PlayerSettings.h")] [NativeHeader("Runtime/Scripting/ScriptingExportUtility.h")] [NativeHeader("Runtime/Graphics/DrawSplashScreenAndWatermarks.h")] internal partial class PlayerSettingsSplashScreenEditor { internal static extern bool licenseAllowsDisabling { [FreeFunction("GetPlayerSettings().GetSplashScreenSettings().CanDisableSplashScreen")] get; } [FreeFunction("GetSplashScreenBackgroundColor")] internal static extern Color GetSplashScreenActualBackgroundColor(); [FreeFunction("GetSplashScreenBackground")] internal static extern Texture2D GetSplashScreenActualBackgroundImage(Rect windowRect); [FreeFunction("GetSplashScreenBackgroundUvs")] internal static extern Rect GetSplashScreenActualUVs(Rect windowRect); } }
UnityCsReference/Editor/Mono/Inspector/PlayerSettingsEditor/PlayerSettingsSplashScreenEditor.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/PlayerSettingsEditor/PlayerSettingsSplashScreenEditor.bindings.cs", "repo_id": "UnityCsReference", "token_count": 373 }
323
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor.AnimatedValues; using UnityEngine; using UnityEngine.Rendering; namespace UnityEditor { [CustomEditor(typeof(RenderSettings))] internal class RenderSettingsInspector : Editor { Editor m_LightingEditor; Editor lightingEditor { get { return m_LightingEditor ?? (m_LightingEditor = Editor.CreateEditor(target, typeof(LightingEditor))); } } Editor m_FogEditor; Editor fogEditor { get { return m_FogEditor ?? (m_FogEditor = Editor.CreateEditor(target, typeof(FogEditor))); } } Editor m_OtherRenderingEditor; Editor otherRenderingEditor { get { return m_OtherRenderingEditor ?? (m_OtherRenderingEditor = Editor.CreateEditor(target, typeof(OtherRenderingEditor))); } } public virtual void OnEnable() { m_LightingEditor = null; m_FogEditor = null; m_OtherRenderingEditor = null; } public override void OnInspectorGUI() { lightingEditor.OnInspectorGUI(); fogEditor.OnInspectorGUI(); otherRenderingEditor.OnInspectorGUI(); } } }
UnityCsReference/Editor/Mono/Inspector/RenderSettingsInspector.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/RenderSettingsInspector.cs", "repo_id": "UnityCsReference", "token_count": 587 }
324
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Collections.Generic; using UnityEditor.IMGUI.Controls; using UnityEditorInternal; using UnityEngine; using UnityEngine.Rendering; namespace UnityEditor { [CustomEditor(typeof(SkinnedMeshRenderer))] [CanEditMultipleObjects] internal class SkinnedMeshRendererEditor : RendererEditorBase { class Styles { public static readonly GUIContent legacyClampBlendShapeWeightsInfo = EditorGUIUtility.TrTextContent("Note that BlendShape weight range is clamped. This can be disabled in Player Settings."); public static readonly GUIContent meshNotSupportingSkinningInfo = EditorGUIUtility.TrTextContent("The assigned mesh is missing either bone weights with bind pose, or blend shapes. This might cause the mesh not to render in the Player. If your mesh does not have either bone weights with bind pose, or blend shapes, use a Mesh Renderer instead of Skinned Mesh Renderer."); public static readonly GUIContent bounds = EditorGUIUtility.TrTextContent("Bounds", "The bounding box that encapsulates the mesh."); public static readonly GUIContent quality = EditorGUIUtility.TrTextContent("Quality", "Number of bones to use per vertex during skinning."); public static readonly GUIContent updateWhenOffscreen = EditorGUIUtility.TrTextContent("Update When Offscreen", "If an accurate bounding volume representation should be calculated every frame. "); public static readonly GUIContent mesh = EditorGUIUtility.TrTextContent("Mesh", "The mesh used by this renderer."); public static readonly GUIContent rootBone = EditorGUIUtility.TrTextContent("Root Bone", "Transform with which the bounds move, and the space in which skinning is computed."); } private SerializedProperty m_AABB; private SerializedProperty m_DirtyAABB; private SerializedProperty m_BlendShapeWeights; private SerializedProperty m_Quality; private SerializedProperty m_UpdateWhenOffscreen; private SerializedProperty m_Mesh; private SerializedProperty m_RootBone; private BoxBoundsHandle m_BoundsHandle = new BoxBoundsHandle(); public override void OnEnable() { base.OnEnable(); m_AABB = serializedObject.FindProperty("m_AABB"); m_DirtyAABB = serializedObject.FindProperty("m_DirtyAABB"); m_BlendShapeWeights = serializedObject.FindProperty("m_BlendShapeWeights"); m_Quality = serializedObject.FindProperty("m_Quality"); m_UpdateWhenOffscreen = serializedObject.FindProperty("m_UpdateWhenOffscreen"); m_Mesh = serializedObject.FindProperty("m_Mesh"); m_RootBone = serializedObject.FindProperty("m_RootBone"); m_BoundsHandle.SetColor(Handles.s_BoundingBoxHandleColor); } public override void OnInspectorGUI() { serializedObject.Update(); EditMode.DoEditModeInspectorModeButton( EditMode.SceneViewEditMode.Collider, "Edit Bounds", PrimitiveBoundsHandle.editModeButton, this ); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(m_AABB, Styles.bounds); // If we set m_AABB then we need to set m_DirtyAABB to false if (EditorGUI.EndChangeCheck()) m_DirtyAABB.boolValue = false; OnBlendShapeUI(); EditorGUILayout.PropertyField(m_Quality, Styles.quality); EditorGUILayout.PropertyField(m_UpdateWhenOffscreen, Styles.updateWhenOffscreen); OnMeshUI(); EditorGUILayout.PropertyField(m_RootBone, Styles.rootBone); DrawMaterials(); LightingSettingsGUI(false); RayTracingSettingsGUI(); OtherSettingsGUI(false, true); serializedObject.ApplyModifiedProperties(); } internal override Bounds GetWorldBoundsOfTarget(Object targetObject) { return ((SkinnedMeshRenderer)targetObject).bounds; } public void OnMeshUI() { SkinnedMeshRenderer renderer = (SkinnedMeshRenderer)target; EditorGUILayout.PropertyField(m_Mesh, Styles.mesh); if (renderer.sharedMesh != null) { bool haveClothComponent = renderer.gameObject.GetComponent<Cloth>() != null; if (!haveClothComponent && renderer.sharedMesh.blendShapeCount == 0 && (renderer.sharedMesh.boneWeights.Length == 0 || renderer.sharedMesh.bindposes.Length == 0)) { EditorGUILayout.HelpBox(Styles.meshNotSupportingSkinningInfo.text, MessageType.Error); } } } public void OnBlendShapeUI() { SkinnedMeshRenderer renderer = (SkinnedMeshRenderer)target; int blendShapeCount = renderer.sharedMesh == null ? 0 : renderer.sharedMesh.blendShapeCount; if (blendShapeCount == 0) return; GUIContent content = new GUIContent(); content.text = "BlendShapes"; EditorGUILayout.PropertyField(m_BlendShapeWeights, content, false); if (!m_BlendShapeWeights.isExpanded) return; EditorGUI.indentLevel++; if (PlayerSettings.legacyClampBlendShapeWeights) EditorGUILayout.HelpBox(Styles.legacyClampBlendShapeWeightsInfo.text, MessageType.Info); Mesh m = renderer.sharedMesh; int arraySize = m_BlendShapeWeights.arraySize; for (int i = 0; i < blendShapeCount; i++) { content.text = m.GetBlendShapeName(i); // Calculate the min and max values for the slider from the frame blendshape weights float sliderMin = 0f, sliderMax = 0f; int frameCount = m.GetBlendShapeFrameCount(i); for (int j = 0; j < frameCount; j++) { float frameWeight = m.GetBlendShapeFrameWeight(i, j); sliderMin = Mathf.Min(frameWeight, sliderMin); sliderMax = Mathf.Max(frameWeight, sliderMax); } // The SkinnedMeshRenderer blendshape weights array size can be out of sync with the size defined in the mesh // (default values in that case are 0) // The desired behaviour is to resize the blendshape array on edit. // Default path when the blend shape array size is big enough. if (i < arraySize) EditorGUILayout.Slider(m_BlendShapeWeights.GetArrayElementAtIndex(i), sliderMin, sliderMax, float.MinValue, float.MaxValue, content); // Fall back to 0 based editing & else { EditorGUI.BeginChangeCheck(); float value = EditorGUILayout.Slider(content, 0f, sliderMin, sliderMax, float.MinValue, float.MaxValue); if (EditorGUI.EndChangeCheck()) { m_BlendShapeWeights.arraySize = blendShapeCount; arraySize = blendShapeCount; m_BlendShapeWeights.GetArrayElementAtIndex(i).floatValue = value; } } } EditorGUI.indentLevel--; } public void OnSceneGUI() { if (!target) return; SkinnedMeshRenderer renderer = (SkinnedMeshRenderer)target; if (renderer.updateWhenOffscreen) { Bounds bounds = renderer.bounds; Vector3 center = bounds.center; Vector3 size = bounds.size; Handles.DrawWireCube(center, size); } else { using (new Handles.DrawingScope(renderer.actualRootBone.localToWorldMatrix)) { Bounds bounds = renderer.localBounds; m_BoundsHandle.center = bounds.center; m_BoundsHandle.size = bounds.size; // only display interactive handles if edit mode is active m_BoundsHandle.handleColor = EditMode.editMode == EditMode.SceneViewEditMode.Collider && EditMode.IsOwner(this) ? m_BoundsHandle.wireframeColor : Color.clear; EditorGUI.BeginChangeCheck(); m_BoundsHandle.DrawHandle(); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(renderer, "Resize Bounds"); renderer.localBounds = new Bounds(m_BoundsHandle.center, m_BoundsHandle.size); } } } } } }
UnityCsReference/Editor/Mono/Inspector/SkinnedMeshRendererEditor.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/SkinnedMeshRendererEditor.cs", "repo_id": "UnityCsReference", "token_count": 4056 }
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.Experimental.Rendering; namespace UnityEditor { // This derived class looks barren because TextureInspector already handles Texture2DArray (Texture or RenderTexture) for most functions. [CustomEditor(typeof(Texture2DArray))] [CanEditMultipleObjects] class Texture2DArrayInspector : TextureInspector { public override string GetInfoString() { var tex = (Texture2DArray)target; var info = $"{tex.width}x{tex.height} {tex.depth} slice{(tex.depth != 1 ? "s" : "")} {GraphicsFormatUtility.GetFormatString(tex.format)} {EditorUtility.FormatBytes(TextureUtil.GetStorageMemorySizeLong(tex))}"; return info; } public override Texture2D RenderStaticPreview(string assetPath, Object[] subAssets, int width, int height) { return m_Texture2DArrayPreview.RenderStaticPreview(target as Texture, assetPath, subAssets, width, height); } } }
UnityCsReference/Editor/Mono/Inspector/Texture2DArrayInspector.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/Texture2DArrayInspector.cs", "repo_id": "UnityCsReference", "token_count": 405 }
326
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Linq; using UnityEditorInternal; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.UIElements { internal class MinMaxGradientField : BaseField<ParticleSystem.MinMaxGradient> { [Obsolete("UxmlFactory is deprecated and will be removed. Use UxmlElementAttribute instead.", false)] protected new class UxmlFactory : UxmlFactory<MinMaxGradientField, UxmlTraits> { } public new static readonly string ussClassName = "unity-min-max-gradient-field"; public static readonly string visualInputUssClass = ussClassName + "__visual-input"; public static readonly string dropdownFieldUssClass = ussClassName + "__dropdown-field"; public static readonly string dropdownInputUssClass = ussClassName + "__dropdown-input"; public static readonly string gradientContainerUssClass = ussClassName + "__gradient-container"; public static readonly string colorFieldUssClass = ussClassName + "__color-field"; public static readonly string multipleValuesLabelUssClass = ussClassName + "__multiple-values-label"; /// <summary> /// Defines <see cref="UxmlTraits"/> for the <see cref="MinMaxGradientField"/>. /// </summary> /// <remarks> /// This class defines the properties of a MinMaxGradientField element that you can /// use in a UXML asset. /// </remarks> [Obsolete("UxmlTraits is deprecated and will be removed. Use UxmlElementAttribute instead.", false)] protected new class UxmlTraits : BaseField<ParticleSystem.MinMaxGradient>.UxmlTraits {} public readonly string[] stringModes = new[] { L10n.Tr("Color"), L10n.Tr("Gradient"), L10n.Tr("Random Between Two Colors"), L10n.Tr("Random Between Two Gradients"), L10n.Tr("Random Color") }; PropertyField m_ColorMin; PropertyField m_ColorMax; PropertyField m_GradientMin; PropertyField m_GradientMax; DropdownField m_ModeDropdown; VisualElement m_GradientsContainer; Label m_MixedValueTypeLabel; public MinMaxGradientField() : this(null, null) { } public MinMaxGradientField(MinMaxGradientPropertyDrawer.PropertyData propertyData, string label) : base(label, null) { if (propertyData != null) { m_ColorMin = new PropertyField(propertyData.colorMin, ""); m_ColorMin.AddToClassList(colorFieldUssClass); m_ColorMax = new PropertyField(propertyData.colorMax, ""); m_ColorMax.AddToClassList(colorFieldUssClass); m_GradientMin = new PropertyField(propertyData.gradientMin, ""); m_GradientMax = new PropertyField(propertyData.gradientMax, ""); m_ModeDropdown = new DropdownField { choices = stringModes.ToList() }; m_ModeDropdown.createMenuCallback = () => { var osMenu = new GenericOSMenu(); for (int i = 0; i < stringModes.Length; i++) { var option = stringModes[i]; var isValueSelected = propertyData.mode.intValue == i; osMenu.AddItem(option, isValueSelected, () => { m_ModeDropdown.value = option; }); } return osMenu; }; m_ModeDropdown.formatSelectedValueCallback = (value) => { // Don't show label for this dropdown return ""; }; m_ModeDropdown.index = propertyData.mode.intValue; m_ModeDropdown.AddToClassList(dropdownFieldUssClass); m_MixedValueTypeLabel = new Label("\u2014"); m_MixedValueTypeLabel.AddToClassList(multipleValuesLabelUssClass); var dropdownInput = m_ModeDropdown.Q<VisualElement>(null, "unity-popup-field__input"); dropdownInput.AddToClassList(dropdownInputUssClass); m_GradientsContainer = new VisualElement(); m_GradientsContainer.AddToClassList(gradientContainerUssClass); m_GradientsContainer.Add(m_GradientMin); m_GradientsContainer.Add(m_GradientMax); visualInput.AddToClassList(visualInputUssClass); visualInput.Add(m_ColorMin); visualInput.Add(m_ColorMax); visualInput.Add(m_GradientsContainer); visualInput.Add(m_MixedValueTypeLabel); visualInput.Add(m_ModeDropdown); m_ModeDropdown.RegisterCallback<ChangeEvent<string>>(e => { var index = Array.IndexOf(stringModes, e.newValue); var mode = (MinMaxGradientState)index; propertyData.mode.intValue = index; propertyData.mode.serializedObject.ApplyModifiedProperties(); UpdateFieldsDisplay(propertyData.mode); }); UpdateFieldsDisplay(propertyData.mode); } } private void UpdateFieldsDisplay(SerializedProperty mode) { var hasMixedValues = mode.hasMultipleDifferentValues; m_ColorMin.style.display = DisplayStyle.None; m_ColorMax.style.display = DisplayStyle.None; m_GradientMin.style.display = DisplayStyle.None; m_GradientMax.style.display = DisplayStyle.None; m_GradientsContainer.style.display = DisplayStyle.None; m_MixedValueTypeLabel.style.display = hasMixedValues ? DisplayStyle.Flex : DisplayStyle.None; if (hasMixedValues) { return; } var modeValue = (MinMaxGradientState)mode.intValue; switch (modeValue) { case MinMaxGradientState.k_Color: m_ColorMax.style.display = DisplayStyle.Flex; break; case MinMaxGradientState.k_Gradient: case MinMaxGradientState.k_RandomColor: m_GradientsContainer.style.display = DisplayStyle.Flex; m_GradientMax.style.display = DisplayStyle.Flex; break; case MinMaxGradientState.k_RandomBetweenTwoColors: m_ColorMin.style.display = DisplayStyle.Flex; m_ColorMax.style.display = DisplayStyle.Flex; break; case MinMaxGradientState.k_RandomBetweenTwoGradients: m_GradientsContainer.style.display = DisplayStyle.Flex; m_GradientMin.style.display = DisplayStyle.Flex; m_GradientMax.style.display = DisplayStyle.Flex; break; } } } }
UnityCsReference/Editor/Mono/Inspector/VisualElements/MinMaxGradientField.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/VisualElements/MinMaxGradientField.cs", "repo_id": "UnityCsReference", "token_count": 3427 }
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; using UnityEngine; using UnityEditor; using System.IO; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; using UnityEditor.Experimental; using UnityEngine.Scripting; using UnityEditor.Scripting.ScriptCompilation; using UnityEngine.UIElements; using UnityEngine.Video; using UnityEditor.Build; namespace UnityEditorInternal { partial class InternalEditorUtility { public static Texture2D FindIconForFile(string fileName) { int i = fileName.LastIndexOf('.'); string extension = i == -1 ? "" : fileName.Substring(i + 1).ToLower(); switch (extension) { // Most .asset files use their scriptable object defined icon instead of a default one. case "asset": return AssetDatabase.GetCachedIcon(fileName) as Texture2D ?? EditorGUIUtility.FindTexture("GameManager Icon"); case "cginc": return EditorGUIUtility.FindTexture("CGProgram Icon"); case "cs": return EditorGUIUtility.FindTexture("cs Script Icon"); case "guiskin": return EditorGUIUtility.FindTexture(typeof(GUISkin)); case "dll": return EditorGUIUtility.FindTexture("Assembly Icon"); case "asmdef": return EditorGUIUtility.FindTexture(typeof(AssemblyDefinitionAsset)); case "asmref": return EditorGUIUtility.FindTexture(typeof(AssemblyDefinitionAsset)); case "mat": return EditorGUIUtility.FindTexture(typeof(Material)); case "physicmaterial": return EditorGUIUtility.FindTexture(typeof(PhysicsMaterial)); case "prefab": return EditorGUIUtility.FindTexture("Prefab Icon"); case "shader": return EditorGUIUtility.FindTexture(typeof(Shader)); case "txt": return EditorGUIUtility.FindTexture(typeof(TextAsset)); case "unity": return EditorGUIUtility.FindTexture(typeof(SceneAsset)); case "prefs": return EditorGUIUtility.FindTexture(typeof(EditorSettings)); case "anim": return EditorGUIUtility.FindTexture(typeof(Animation)); case "meta": return EditorGUIUtility.FindTexture("MetaFile Icon"); case "mixer": return EditorGUIUtility.FindTexture(typeof(UnityEditor.Audio.AudioMixerController)); case "uxml": return EditorGUIUtility.FindTexture(typeof(UnityEngine.UIElements.VisualTreeAsset)); case "uss": return EditorGUIUtility.FindTexture(typeof(StyleSheet)); case "lighting": return EditorGUIUtility.FindTexture(typeof(UnityEngine.LightingSettings)); case "scenetemplate": return EditorGUIUtility.FindTexture("UnityEditor/SceneTemplate/SceneTemplateAsset Icon"); case "ttf": case "otf": case "fon": case "fnt": return EditorGUIUtility.FindTexture(typeof(Font)); case "aac": case "aif": case "aiff": case "au": case "mid": case "midi": case "mp3": case "mpa": case "ra": case "ram": case "wma": case "wav": case "wave": case "ogg": case "flac": return EditorGUIUtility.FindTexture(typeof(AudioClip)); case "ai": case "apng": case "png": case "bmp": case "cdr": case "dib": case "eps": case "exif": case "gif": case "ico": case "icon": case "j": case "j2c": case "j2k": case "jas": case "jiff": case "jng": case "jp2": case "jpc": case "jpe": case "jpeg": case "jpf": case "jpg": case "jpw": case "jpx": case "jtf": case "mac": case "omf": case "qif": case "qti": case "qtif": case "tex": case "tfw": case "tga": case "tif": case "tiff": case "wmf": case "psd": case "exr": case "hdr": return EditorGUIUtility.FindTexture(typeof(Texture)); case "3df": case "3dm": case "3dmf": case "3ds": case "3dv": case "3dx": case "blend": case "c4d": case "lwo": case "lws": case "ma": case "max": case "mb": case "mesh": case "obj": case "vrl": case "wrl": case "wrz": case "fbx": return EditorGUIUtility.FindTexture(typeof(Mesh)); case "dv": case "mp4": case "mpg": case "mpeg": case "m4v": case "ogv": case "vp8": case "webm": case "asf": case "asx": case "avi": case "dat": case "divx": case "dvx": case "mlv": case "m2l": case "m2t": case "m2ts": case "m2v": case "m4e": case "mjp": case "mov": case "movie": case "mp21": case "mpe": case "mpv2": case "ogm": case "qt": case "rm": case "rmvb": case "wmw": case "xvid": return AssetDatabase.GetCachedIcon(fileName) as Texture2D ?? EditorGUIUtility.FindTexture(typeof(VideoClip)); case "colors": case "gradients": case "curves": case "curvesnormalized": case "particlecurves": case "particlecurvessigned": case "particledoublecurves": case "particledoublecurvessigned": return EditorGUIUtility.FindTexture(typeof(ScriptableObject)); default: return null; } } [RequiredByNativeCode] public static Texture2D GetIconForFile(string fileName) { return FindIconForFile(fileName) ?? EditorGUIUtility.FindTexture(typeof(DefaultAsset)); } static GUIContent[] sStatusWheel; internal static GUIContent animatedProgressImage { get { if (sStatusWheel == null) { sStatusWheel = new GUIContent[12]; for (int i = 0; i < 12; i++) { GUIContent gc = new GUIContent(); gc.image = EditorGUIUtility.LoadIcon("WaitSpin" + i.ToString("00")); gc.image.hideFlags = HideFlags.HideAndDontSave; gc.image.name = "Spinner"; sStatusWheel[i] = gc; } } int frame = (int)Mathf.Repeat(Time.realtimeSinceStartup * 10, 11.99f); return sStatusWheel[frame]; } } public static string[] GetEditorSettingsList(string prefix, int count) { ArrayList aList = new ArrayList(); for (int i = 1; i <= count; i++) { string str = EditorPrefs.GetString(prefix + i, "defaultValue"); if (str == "defaultValue") break; aList.Add(str); } return aList.ToArray(typeof(string)) as string[]; } public static void SaveEditorSettingsList(string prefix, string[] aList, int count) { int i; for (i = 0; i < aList.Length; i++) EditorPrefs.SetString(prefix + (i + 1), (string)aList[i]); for (i = aList.Length + 1; i <= count; i++) EditorPrefs.DeleteKey(prefix + i); } public static string TextAreaForDocBrowser(Rect position, string text, GUIStyle style) { int id = EditorGUIUtility.GetControlID("TextAreaWithTabHandling".GetHashCode(), FocusType.Keyboard, position); var editor = EditorGUI.s_RecycledEditor; var evt = Event.current; if (editor.IsEditingControl(id) && evt.type == EventType.KeyDown) { if (evt.character == '\t') { editor.Insert('\t'); evt.Use(); GUI.changed = true; text = editor.text; } if (evt.character == '\n') { editor.Insert('\n'); evt.Use(); GUI.changed = true; text = editor.text; } } bool dummy; text = EditorGUI.DoTextField(editor, id, EditorGUI.IndentedRect(position), text, style, null, out dummy, false, true, false); return text; } public static Camera[] GetSceneViewCameras() { return SceneView.GetAllSceneCameras(); } public static void ShowGameView() { WindowLayout.ShowAppropriateViewOnEnterExitPlaymode(true); } internal struct AssetReference { // The guid is always valid. Assets not yet present will not have an instanceID yet. // Could be because it is on-demand imported. public string guid; public int instanceID; // instanceID of an object in an asset if the asset is available in imported form. Else 0. public sealed class GuidThenInstanceIDEqualityComparer : IEqualityComparer<AssetReference> { public bool Equals(AssetReference x, AssetReference y) { if (!string.IsNullOrEmpty(x.guid) || !string.IsNullOrEmpty(y.guid)) return string.Equals(x.guid, y.guid); // Both guids are nullOrEmpty now return x.instanceID == y.instanceID; } public int GetHashCode(AssetReference assetReference) { return (assetReference.instanceID * 397) ^ (assetReference.guid != null ? assetReference.guid.GetHashCode() : 0); } } public static bool IsAssetImported(int instanceID) { return instanceID != 0; } } public static List<int> GetNewSelection(int clickedInstanceID, List<int> allInstanceIDs, List<int> selectedInstanceIDs, int lastClickedInstanceID, bool keepMultiSelection, bool useShiftAsActionKey, bool allowMultiSelection) { return GetNewSelection(clickedInstanceID, allInstanceIDs, selectedInstanceIDs, lastClickedInstanceID, keepMultiSelection, useShiftAsActionKey, allowMultiSelection, Event.current?.shift ?? false, EditorGUI.actionKey); } internal static List<int> GetNewSelection(int clickedInstanceID, List<int> allInstanceIDs, List<int> selectedInstanceIDs, int lastClickedInstanceID, bool keepMultiSelection, bool useShiftAsActionKey, bool allowMultiSelection, bool shiftKeyIsDown, bool actionKeyIsDown) { List<string> allGuids = null; var clicked = new AssetReference() { guid = null, instanceID = clickedInstanceID }; return GetNewSelection(ref clicked, allInstanceIDs, allGuids, selectedInstanceIDs, lastClickedInstanceID, keepMultiSelection, useShiftAsActionKey, allowMultiSelection, shiftKeyIsDown, actionKeyIsDown); } internal static bool TrySetInstanceId(ref AssetReference entry) { if (entry.instanceID != 0 || string.IsNullOrEmpty(entry.guid)) return true; if (entry.instanceID == 0 && EditorUtility.isInSafeMode) return false; // Íf instance id is 0 in safe mode, then don't try to produce it. InstanceIDs are 0 for non script assets in safe mode. GUID lookupGUID = new GUID(entry.guid); var hash = UnityEditor.Experimental.AssetDatabaseExperimental.ProduceArtifactAsync(new ArtifactKey(lookupGUID)); if (!hash.isValid) return false; string path = AssetDatabase.GUIDToAssetPath(entry.guid); entry.instanceID = AssetDatabase.GetMainAssetInstanceID(path); return true; } internal static List<int> TryGetInstanceIds(List<int> entryInstanceIds, List<string> entryInstanceGuids, int from, int to) { List<GUID> guids = new List<GUID>(); for (int i = from; i <= to; ++i) { if (entryInstanceIds[i] == 0) { GUID parsedGuid = new GUID(entryInstanceGuids[i]); guids.Add(parsedGuid); } } // Force import if needed so that we can get an instance ID for the entry if (guids.Count == 0) { return entryInstanceIds.GetRange(from, to - from + 1); } else { var hashes = UnityEditor.Experimental.AssetDatabaseExperimental.ProduceArtifactsAsync(guids.ToArray()); if (System.Array.FindIndex(hashes, a => !a.isValid) != -1) return null; var newSelection = new List<int>(to - from + 1); for (int i = from; i <= to; ++i) { int instanceID = entryInstanceIds[i]; if (instanceID == 0) { if (EditorUtility.isInSafeMode) continue; // Íf instance id is 0 in safe mode, then don't try to produce it. InstanceIDs are 0 for non script assets in safe mode. string path = AssetDatabase.GUIDToAssetPath(entryInstanceGuids[i]); instanceID = AssetDatabase.GetMainAssetInstanceID(path); entryInstanceIds[i] = instanceID; } newSelection.Add(instanceID); } return newSelection; } } internal static List<int> GetNewSelection(ref AssetReference clickedEntry, List<int> allEntryInstanceIDs, List<string> allEntryGuids, List<int> selectedInstanceIDs, int lastClickedInstanceID, bool keepMultiSelection, bool useShiftAsActionKey, bool allowMultiSelection) { return GetNewSelection(ref clickedEntry, allEntryInstanceIDs, allEntryGuids, selectedInstanceIDs, lastClickedInstanceID, keepMultiSelection, useShiftAsActionKey, allowMultiSelection, Event.current.shift, EditorGUI.actionKey); } // Multi selection handling. Returns new list of selected instanceIDs internal static List<int> GetNewSelection(ref AssetReference clickedEntry, List<int> allEntryInstanceIDs, List<string> allEntryGuids, List<int> selectedInstanceIDs, int lastClickedInstanceID, bool keepMultiSelection, bool useShiftAsActionKey, bool allowMultiSelection, bool shiftKeyIsDown, bool actionKeyIsDown) { bool useShift = shiftKeyIsDown || (actionKeyIsDown && useShiftAsActionKey); bool useActionKey = actionKeyIsDown && !useShiftAsActionKey; if (!allowMultiSelection) useShift = useActionKey = false; int firstIndex; int lastIndex; // Toggle selected node from selection if (useActionKey && !useShift) { var newSelection = new List<int>(selectedInstanceIDs); if (newSelection.Contains(clickedEntry.instanceID)) { // In case the user is performing CTRL+click on an already selected item, delay the deselection so that Drag may be initiated. if (!(Event.current.control && Event.current.type == EventType.MouseDown)) newSelection.Remove(clickedEntry.instanceID); } else { if (TrySetInstanceId(ref clickedEntry)) newSelection.Add(clickedEntry.instanceID); } return newSelection; } // Select everything between the first selected object and the selected else if (useShift) { if (clickedEntry.instanceID == lastClickedInstanceID) { return new List<int>(selectedInstanceIDs); } if (!GetFirstAndLastSelected(allEntryInstanceIDs, selectedInstanceIDs, out firstIndex, out lastIndex)) { // We had no selection var newSelection = new List<int>(1); if (TrySetInstanceId(ref clickedEntry)) newSelection.Add(clickedEntry.instanceID); return newSelection; } int newIndex = -1; int prevIndex = -1; // Only valid in case the selection concerns assets if (!TrySetInstanceId(ref clickedEntry)) return new List<int>(selectedInstanceIDs); int clickedInstanceID = clickedEntry.instanceID; if (lastClickedInstanceID != 0) { for (int i = 0; i < allEntryInstanceIDs.Count; ++i) { if (allEntryInstanceIDs[i] == clickedInstanceID) newIndex = i; if (allEntryInstanceIDs[i] == lastClickedInstanceID) prevIndex = i; } } else { for (int i = 0; i < allEntryInstanceIDs.Count; ++i) { if (allEntryInstanceIDs[i] == clickedInstanceID) newIndex = i; } } System.Diagnostics.Debug.Assert(newIndex != -1); // new item should be part of visible folder set int dir = 0; if (prevIndex != -1) dir = (newIndex > prevIndex) ? 1 : -1; int from = 0, to = 0; var addExisting = false; bool usingArrowKeys = Event.current != null ? Event.current.keyCode == KeyCode.DownArrow || Event.current.keyCode == KeyCode.UpArrow : false; var clickedInTheMiddle = lastIndex > newIndex && firstIndex < newIndex; if (selectedInstanceIDs.Count > 1) { var clickedID = allEntryInstanceIDs[newIndex]; var noGapsInSelection = (allEntryInstanceIDs.Count - firstIndex + selectedInstanceIDs.Count) == allEntryInstanceIDs.Count - lastIndex; var isInSelection = selectedInstanceIDs.Contains(clickedID); // if the newly clicked item is already selected, // we treat this as a combination of selecting items from the highest selected item to the clicked item // or from the lowest selected item to the clicked item depending on the direction of the selection, // e.g. if we select item 1 and shift-select item 5, then shift-select item 3, we'll have items 1 to 3 selected if (isInSelection || noGapsInSelection || clickedInTheMiddle) { from = dir > 0 ? firstIndex : newIndex; to = dir > 0 ? newIndex : lastIndex; // if we clicked in-between the lowest and highest selected indices of a selection containing gaps // and the item was not already in the selection // make sure that the new selection is added to the currently existing one if (clickedInTheMiddle && !noGapsInSelection && !isInSelection) addExisting = true; } else if (dir > 0) { if (newIndex > lastIndex) { from = lastIndex + 1; to = newIndex; addExisting = true; } else { from = newIndex; to = lastIndex; } } else if (dir < 0) { if (newIndex < firstIndex) { from = newIndex; to = firstIndex - 1; addExisting = true; } else { from = firstIndex; to = newIndex; } } } if (!addExisting || usingArrowKeys) { if (newIndex > lastIndex) { from = firstIndex; to = newIndex; } else if (newIndex >= firstIndex && newIndex < lastIndex) { if (dir > 0) { from = newIndex; to = lastIndex; } else { from = firstIndex; to = newIndex; } } else { from = newIndex; to = lastIndex; } } if (allEntryGuids == null) { List<int> allSelectedInstanceIDs = new List<int>(); if (addExisting && !usingArrowKeys) { allSelectedInstanceIDs.AddRange(selectedInstanceIDs.GetRange(0, selectedInstanceIDs.Count)); allSelectedInstanceIDs.AddRange(allEntryInstanceIDs.GetRange(from, to - from + 1)); if (clickedInTheMiddle) allSelectedInstanceIDs = allSelectedInstanceIDs.Distinct().ToList(); } else { allSelectedInstanceIDs.AddRange(allEntryInstanceIDs.GetRange(from, to - from + 1)); } return allSelectedInstanceIDs; } var foundInstanceIDs = TryGetInstanceIds(allEntryInstanceIDs, allEntryGuids, from, to); if (foundInstanceIDs != null) { // adding the entire selectedInstanceIDs would result // in the last entry being duplicated later on // thus when selecting upwards we add the existing selection - 1; // when selecting downwards don't add the last index from the new selection if (addExisting && !usingArrowKeys) { List<int> allSelectedInstanceIDs = new List<int>(); allSelectedInstanceIDs.AddRange(selectedInstanceIDs.GetRange(0, selectedInstanceIDs.Count)); allSelectedInstanceIDs.AddRange(allEntryInstanceIDs.GetRange(from, to - from + 1)); if (clickedInTheMiddle) allSelectedInstanceIDs = allSelectedInstanceIDs.Distinct().ToList(); return allSelectedInstanceIDs; } return foundInstanceIDs; } return new List<int>(selectedInstanceIDs); } // Just set the selection to the clicked object else { if (keepMultiSelection) { // Don't change selection on mouse down when clicking on selected item. // This is for dragging in case with multiple items selected or right click (mouse down should not unselect the rest). if (selectedInstanceIDs.Contains(clickedEntry.instanceID)) { return new List<int>(selectedInstanceIDs); } } if (TrySetInstanceId(ref clickedEntry)) { var newSelection = new List<int>(1); newSelection.Add(clickedEntry.instanceID); return newSelection; } else { return new List<int>(selectedInstanceIDs); } } } static bool GetFirstAndLastSelected(List<int> allEntries, List<int> selectedInstanceIDs, out int firstIndex, out int lastIndex) { firstIndex = -1; lastIndex = -1; for (int i = 0; i < allEntries.Count; ++i) { if (selectedInstanceIDs.Contains(allEntries[i])) { if (firstIndex == -1) firstIndex = i; lastIndex = i; // just overwrite and we will have the last in the end... } } return firstIndex != -1 && lastIndex != -1; } internal static string GetApplicationExtensionForRuntimePlatform(RuntimePlatform platform) { switch (platform) { case RuntimePlatform.OSXEditor: return "app"; case RuntimePlatform.WindowsEditor: return "exe"; default: break; } return string.Empty; } public static bool IsValidFileName(string filename) { string validFileName = RemoveInvalidCharsFromFileName(filename, false); if (validFileName != filename || string.IsNullOrEmpty(validFileName)) return false; return true; } public static string RemoveInvalidCharsFromFileName(string filename, bool logIfInvalidChars) { if (string.IsNullOrEmpty(filename)) return filename; filename = filename.Trim(); // remove leading and trailing white spaces if (string.IsNullOrEmpty(filename)) return filename; string invalidChars = new string(System.IO.Path.GetInvalidFileNameChars()); string legal = ""; bool hasInvalidChar = false; foreach (char c in filename) { if (invalidChars.IndexOf(c) == -1) legal += c; else hasInvalidChar = true; } if (hasInvalidChar && logIfInvalidChars) { string invalid = GetDisplayStringOfInvalidCharsOfFileName(filename); if (invalid.Length > 0) Debug.LogWarningFormat("A filename cannot contain the following character{0}: {1}", invalid.Length > 1 ? "s" : "", invalid); } return legal; } public static string GetDisplayStringOfInvalidCharsOfFileName(string filename) { if (string.IsNullOrEmpty(filename)) return ""; string invalid = new string(System.IO.Path.GetInvalidFileNameChars()); string illegal = ""; foreach (char c in filename) { if (invalid.IndexOf(c) >= 0) { if (illegal.IndexOf(c) == -1) { if (illegal.Length > 0) illegal += " "; illegal += c; } } } return illegal; } internal static bool IsScriptOrAssembly(string filename) { if (string.IsNullOrEmpty(filename)) return false; switch (System.IO.Path.GetExtension(filename).ToLower()) { case ".cs": return true; case ".dll": case ".exe": return AssemblyHelper.IsManagedAssembly(filename); default: return false; } } internal static IEnumerable<string> GetAllScriptGUIDs() { return AssetDatabase.GetAllAssetPaths() .Where(asset => (IsScriptOrAssembly(asset) && !UnityEditor.PackageManager.Folders.IsPackagedAssetPath(asset))) .Select(asset => AssetDatabase.AssetPathToGUID(asset)); } internal static string GetMonolithicEngineAssemblyPath() { // We still build a monolithic UnityEngine.dll as a compilation target for user projects. // It lives next to the editor dll. var dir = Path.GetDirectoryName(GetEditorAssemblyPath()); return Path.Combine(dir, "UnityEngine.dll"); } internal static string[] GetCompilationDefines(EditorScriptCompilationOptions options, BuildTarget target, int subtarget) { return GetCompilationDefines(options, target, subtarget, PlayerSettings.GetApiCompatibilityLevel(NamedBuildTarget.FromActiveSettings(target))); } public static void SetShowGizmos(bool value) { var view = PlayModeView.GetMainPlayModeView(); if (view == null) view = PlayModeView.GetRenderingView(); if (view == null) return; view.SetShowGizmos(value); } private static Material blitSceneViewCaptureMat; public static bool CaptureSceneView(SceneView sv, RenderTexture rt) { if (!sv.hasFocus) return false; if (blitSceneViewCaptureMat == null) blitSceneViewCaptureMat = (Material)EditorGUIUtility.LoadRequired("SceneView/BlitSceneViewCapture.mat"); // Grab SceneView framebuffer into a temporary RT. RenderTexture tmp = RenderTexture.GetTemporary(rt.descriptor); Rect rect = new Rect(0, 0, sv.position.width, sv.position.height); sv.m_Parent.GrabPixels(tmp, rect); // Blit it into the target RT, it will be flipped by the shader if necessary. Graphics.Blit(tmp, rt, blitSceneViewCaptureMat); RenderTexture.ReleaseTemporary(tmp); return true; } static readonly Regex k_UnityAssemblyRegex = new("^(Unity|UnityEditor|UnityEngine).", RegexOptions.Compiled); internal static bool IsUnityAssembly(Type type) { var assemblyName = type.Assembly.GetName().ToString(); return k_UnityAssemblyRegex.IsMatch(assemblyName); } } }
UnityCsReference/Editor/Mono/InternalEditorUtility.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/InternalEditorUtility.cs", "repo_id": "UnityCsReference", "token_count": 15292 }
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.Threading; using Bee.BeeDriver; using Bee.BinLog; using NiceIO; using PlayerBuildProgramLibrary.Data; using UnityEditor.Build; using UnityEditor.Build.Player; using UnityEditor.Build.Reporting; using UnityEditor.CrashReporting; using UnityEditor.Scripting; using UnityEditor.Scripting.ScriptCompilation; using UnityEditor.Utils; using UnityEditorInternal; using UnityEngine; using UnityEngine.Scripting; namespace UnityEditor.Modules { internal abstract class BeeBuildPostprocessor : IBuildPostprocessor { protected BeeDriverResult BeeDriverResult { get; set; } protected static bool isBuildingPlayer { get; set; } public static readonly string kBackupFolderPostfix = "_BackUpThisFolder_ButDontShipItWithYourGame"; static readonly string kXrBootSettingsKey = "xr-boot-settings"; public virtual void LaunchPlayer(BuildLaunchPlayerArgs args) => throw new NotSupportedException(); public virtual void PostProcess(BuildPostProcessArgs args, out BuildProperties outProperties) { PostProcess(args); // NOTE: For some reason, calling PostProcess seems like it can trigger this object to be GC'd // so create is just before returning outProperties = ScriptableObject.CreateInstance<DefaultBuildProperties>(); } public virtual bool SupportsInstallInBuildFolder() => false; public virtual bool SupportsLz4Compression() => false; public virtual Compression GetDefaultCompression() => Compression.None; public virtual void UpdateBootConfig(BuildTarget target, BootConfigData config, BuildOptions options) { config.Set("wait-for-native-debugger", "0"); if (config.Get("player-connection-debug") == "1") { config.Set("wait-for-managed-debugger", EditorUserBuildSettings.waitForManagedDebugger ? "1" : "0"); config.Set("managed-debugger-fixed-port", EditorUserBuildSettings.managedDebuggerFixedPort.ToString()); } config.Set("hdr-display-enabled", PlayerSettings.useHDRDisplay ? "1" : "0"); if (BuildPipeline.IsFeatureSupported("ENABLE_SCRIPTING_GC_WBARRIERS", target)) { if (PlayerSettings.gcWBarrierValidation) config.AddKey("validate-write-barriers"); if (PlayerSettings.gcIncremental) config.Set("gc-max-time-slice", "3"); } string xrBootSettings = UnityEditor.EditorUserBuildSettings.GetPlatformSettings(BuildPipeline.GetBuildTargetName(target), kXrBootSettingsKey); if (!String.IsNullOrEmpty(xrBootSettings)) { var bootSettings = xrBootSettings.Split(';'); foreach (var bootSetting in bootSettings) { var setting = bootSetting.Split(':'); if (setting.Length == 2 && !String.IsNullOrEmpty(setting[0]) && !String.IsNullOrEmpty(setting[1])) { config.Set(setting[0], setting[1]); } } } if ((options & BuildOptions.Development) != 0) { if ((options & BuildOptions.EnableDeepProfilingSupport) != 0) { config.Set("profiler-enable-deep-profiling-support", "1"); } } } protected virtual string GetIl2CppDataBackupFolderName(BuildPostProcessArgs args) => $"{args.installPath.ToNPath().FileNameWithoutExtension}{kBackupFolderPostfix}"; public virtual string GetExtension(BuildTarget target, int subtarget, BuildOptions options) => string.Empty; [RequiredByNativeCode] static bool IsBuildingPlayer() => isBuildingPlayer; [RequiredByNativeCode] static void BeginProfile() => UnityBeeDriverProfilerSession.Start($"{DagDirectory}/buildreport.json"); [RequiredByNativeCode] static void EndProfile() => UnityBeeDriverProfilerSession.Finish(); [RequiredByNativeCode] static void BeginBuildSection(string name) => UnityBeeDriverProfilerSession.BeginSection(name); [RequiredByNativeCode] static void EndBuildSection() => UnityBeeDriverProfilerSession.EndSection(); protected virtual IPluginImporterExtension GetPluginImpExtension() => new EditorPluginImporterExtension(); protected virtual PluginsData PluginsDataFor(BuildPostProcessArgs args) { return new PluginsData { Plugins = GetPluginBuildTargetsFor(args).SelectMany(GetPluginsFor).ToArray() }; } protected virtual IEnumerable<BuildTarget> GetPluginBuildTargetsFor(BuildPostProcessArgs args) { yield return args.target; } protected virtual Plugin GetPluginFor(PluginImporter imp, BuildTarget target, string destinationPath) { // Skip .cpp files. They get copied to il2cpp output folder just before code compilation if (DesktopPluginImporterExtension.IsCppPluginFile(imp.assetPath)) return null; return new Plugin { AssetPath = imp.assetPath, DestinationPath = destinationPath, }; } IEnumerable<Plugin> GetPluginsFor(BuildTarget target) { var buildTargetName = BuildPipeline.GetBuildTargetName(target); var pluginImpExtension = GetPluginImpExtension(); foreach (PluginImporter imp in PluginImporter.GetImporters(target)) { if (!IsPluginCompatibleWithCurrentBuild(target, imp)) continue; // Skip managed DLLs. if (!imp.isNativePlugin) continue; // HACK: This should never happen. if (string.IsNullOrEmpty(imp.assetPath)) { UnityEngine.Debug.LogWarning("Got empty plugin importer path for " + target); continue; } var destinationPath = pluginImpExtension.CalculateFinalPluginPath(buildTargetName, imp); if (string.IsNullOrEmpty(destinationPath)) continue; var plugin = GetPluginFor(imp, target, destinationPath); if (plugin != null) yield return plugin; } } static IEnumerable<NPath> GetFilesWithRoleFromBuildReport(BuildReport report, params string[] roles) => report.GetFiles() .Where(file => roles.Contains(file.role)) .Select(file => file.path.ToNPath()) .GroupBy(file => file.FileName) .Select(group => group.First()); LinkerConfig LinkerConfigFor(BuildPostProcessArgs args) { var namedBuildTarget = GetNamedBuildTarget(args); var strippingLevel = PlayerSettings.GetManagedStrippingLevel(namedBuildTarget); // IL2CPP does not support a managed stripping level of disabled. If the player settings // do try this (which should not be possible from the editor), use Low instead. if (GetScriptingBackend(args) == ScriptingBackend.IL2CPP && strippingLevel == ManagedStrippingLevel.Disabled) strippingLevel = ManagedStrippingLevel.Minimal; var additionalArgs = new List<string>(); var diagArgs = Debug.GetDiagnosticSwitch("VMUnityLinkerAdditionalArgs").value as string; if (!string.IsNullOrEmpty(diagArgs)) additionalArgs.Add(diagArgs.Trim('\'')); var linkerInputDirectory = DagDirectory.Combine($"artifacts/UnityLinkerInputs").CreateDirectory(); // In Disabled mode, we pass all generated and engine assemblies to the linker as roots, as the linker // will only perform a simple assembly reference traversal, ignoring link.xml files and attributes which // would otherwise find dependent assemblies to preserve. // In other modes (when stripping is desired), we pass only a smaller set of user assemblies (assemblies from // packages if used in any scenes, as well as any assembly from the Assets folder) as roots. var assembliesToProcess = strippingLevel == ManagedStrippingLevel.Disabled ? GetFilesWithRoleFromBuildReport(args.report, "ManagedLibrary", "ManagedEngineAPI").Select(f => f.FileName) : args.usedClassRegistry.GetUsedUserAssemblies(); return new LinkerConfig { LinkXmlFiles = AssemblyStripper.GetLinkXmlFiles(args, linkerInputDirectory), EditorToLinkerData = AssemblyStripper.WriteEditorData(args, linkerInputDirectory), AssembliesToProcess = assembliesToProcess.ToArray(), Runtime = GetScriptingBackend(args).ToString().ToLowerInvariant(), Profile = IL2CPPUtils.ApiCompatibilityLevelToDotNetProfileArgument( PlayerSettings.GetApiCompatibilityLevel(namedBuildTarget), args.target), Ruleset = strippingLevel switch { ManagedStrippingLevel.Disabled => "Copy", ManagedStrippingLevel.Minimal => "Minimal", ManagedStrippingLevel.Low => "Conservative", ManagedStrippingLevel.Medium => "Aggressive", ManagedStrippingLevel.High => "Experimental", _ => throw new ArgumentException($"Unhandled {nameof(ManagedStrippingLevel)} value") }, AdditionalArgs = additionalArgs.ToArray(), ModulesAssetPath = $"{BuildPipeline.GetPlaybackEngineDirectory(args.target, 0)}/modules.asset", AllowDebugging = GetAllowDebugging(args), PerformEngineStripping = PlayerSettings.stripEngineCode, }; } static bool IsBuildOptionSet(BuildOptions options, BuildOptions flag) => (options & flag) != 0; static string GetConfigurationName(Il2CppCompilerConfiguration compilerConfiguration) { // In IL2CPP, Master config is called "ReleasePlus" return compilerConfiguration != Il2CppCompilerConfiguration.Master ? compilerConfiguration.ToString() : "ReleasePlus"; } protected virtual string Il2CppBuildConfigurationNameFor(BuildPostProcessArgs args) { return GetConfigurationName(PlayerSettings.GetIl2CppCompilerConfiguration(GetNamedBuildTarget(args))); } protected virtual IEnumerable<string> AdditionalIl2CppArgsFor(BuildPostProcessArgs args) { yield break; } IEnumerable<string> SplitArgs(string args) { int startIndex = 0; bool inQuotes = false; int i = 0; for (; i < args.Length; i++) { if (args[i] == '"') inQuotes = !inQuotes; if (args[i] == ' ' && !inQuotes) { if (i - startIndex > 0) yield return args.Substring(startIndex, i - startIndex); startIndex = i + 1; } } if (i - startIndex > 0) yield return args.Substring(startIndex, i - startIndex); } protected virtual string Il2CppSysrootPathFor(BuildPostProcessArgs args) => null; protected virtual string Il2CppToolchainPathFor(BuildPostProcessArgs args) => null; protected virtual string Il2CppCompilerFlagsFor(BuildPostProcessArgs args) => null; protected virtual string Il2CppLinkerFlagsFor(BuildPostProcessArgs args) => null; protected virtual string Il2CppLinkerFlagsFileFor(BuildPostProcessArgs args) => null; protected virtual string Il2CppDataRelativePath(BuildPostProcessArgs args) => "Data"; Il2CppConfig Il2CppConfigFor(BuildPostProcessArgs args) { if (GetScriptingBackend(args) != ScriptingBackend.IL2CPP) return null; var additionalArgs = new List<string>(AdditionalIl2CppArgsFor(args)); var diagArgs = Debug.GetDiagnosticSwitch("VMIl2CppAdditionalArgs").value as string; if (!string.IsNullOrEmpty(diagArgs)) additionalArgs.AddRange(SplitArgs(diagArgs.Trim('\''))); var playerSettingsArgs = PlayerSettings.GetAdditionalIl2CppArgs(); if (!string.IsNullOrEmpty(playerSettingsArgs)) additionalArgs.AddRange(SplitArgs(playerSettingsArgs)); var sysrootPath = Il2CppSysrootPathFor(args); var toolchainPath = Il2CppToolchainPathFor(args); var compilerFlags = Il2CppCompilerFlagsFor(args); var linkerFlags = Il2CppLinkerFlagsFor(args); var linkerFlagsFile = Il2CppLinkerFlagsFileFor(args); var relativeDataPath = Il2CppDataRelativePath(args); if (CrashReportingSettings.enabled) additionalArgs.Add("--emit-source-mapping"); var namedBuildTarget = GetNamedBuildTarget(args); var apiCompatibilityLevel = PlayerSettings.GetApiCompatibilityLevel(namedBuildTarget); var il2cppCodeGeneration = PlayerSettings.GetIl2CppCodeGeneration(namedBuildTarget); var platformHasIncrementalGC = BuildPipeline.IsFeatureSupported("ENABLE_SCRIPTING_GC_WBARRIERS", args.target); var allowDebugging = GetAllowDebugging(args); NPath extraTypesFile = null; if (PlayerBuildInterface.ExtraTypesProvider != null) { var extraTypes = new HashSet<string>(); foreach (var extraType in PlayerBuildInterface.ExtraTypesProvider()) { extraTypes.Add(extraType); } extraTypesFile = "Temp/extra-types.txt"; extraTypesFile.WriteAllLines(extraTypes.ToArray()); } return new Il2CppConfig { EnableDeepProfilingSupport = GetDevelopment(args) && IsBuildOptionSet(args.report.summary.options, BuildOptions.EnableDeepProfilingSupport), EnableFullGenericSharing = il2cppCodeGeneration == Il2CppCodeGeneration.OptimizeSize, Profile = IL2CPPUtils.ApiCompatibilityLevelToDotNetProfileArgument(PlayerSettings.GetApiCompatibilityLevel(namedBuildTarget), args.target), IDEProjectDefines = IL2CPPUtils.GetBuilderDefinedDefines(args.target, apiCompatibilityLevel, allowDebugging), ConfigurationName = Il2CppBuildConfigurationNameFor(args), GcWBarrierValidation = platformHasIncrementalGC && PlayerSettings.gcWBarrierValidation, GcIncremental = platformHasIncrementalGC && PlayerSettings.gcIncremental && (apiCompatibilityLevel == ApiCompatibilityLevel.NET_4_6 || apiCompatibilityLevel == ApiCompatibilityLevel.NET_Standard_2_0 || apiCompatibilityLevel == ApiCompatibilityLevel.NET_Unity_4_8 || apiCompatibilityLevel == ApiCompatibilityLevel.NET_Standard), CreateSymbolFiles = !GetDevelopment(args) || CrashReportingSettings.enabled, AdditionalCppFiles = PluginImporter.GetImporters(args.target) .Where(imp => DesktopPluginImporterExtension.IsCppPluginFile(imp.assetPath)) .Select(imp => imp.assetPath) .ToArray(), AdditionalArgs = additionalArgs.ToArray(), AllowDebugging = allowDebugging, CompilerFlags = compilerFlags, LinkerFlags = linkerFlags, LinkerFlagsFile = linkerFlagsFile, SysRootPath = sysrootPath, ToolChainPath = toolchainPath, RelativeDataPath = relativeDataPath, ExtraTypes = extraTypesFile?.ToString(), GenerateUsymFile = PlayerSettings.GetIl2CppStacktraceInformation(namedBuildTarget) == Il2CppStacktraceInformation.MethodFileLineNumber, UsymtoolPath = GetUsymtoolPath(), }; } static string GetUsymtoolPath() { if (Application.platform == RuntimePlatform.OSXEditor) return Paths.Combine(EditorApplication.applicationContentsPath, "Tools", "macosx", "usymtool"); if (Application.platform == RuntimePlatform.LinuxEditor) return Paths.Combine(EditorApplication.applicationContentsPath, "Tools", "usymtool"); return Paths.Combine(EditorApplication.applicationContentsPath, "Tools", "usymtool.exe"); } static bool IsNewInputSystemEnabled() { var propName = "activeInputHandler"; var ps = PlayerSettings.GetSerializedObject(); var newInputEnabledProp = ps.FindProperty(propName); if (newInputEnabledProp == null) throw new Exception($"Failed to find {propName}"); return newInputEnabledProp.intValue != 0; } static GenerateNativePluginsForAssembliesSettings GetGenerateNativePluginsForAssembliesSettings(BuildPostProcessArgs args) { var settings = new GenerateNativePluginsForAssembliesSettings(); settings.DisplayName = "Generating Native Plugins"; if (BuildPipelineInterfaces.processors.generateNativePluginsForAssembliesProcessors != null) { foreach (var processor in BuildPipelineInterfaces.processors.generateNativePluginsForAssembliesProcessors) { var setupResult = processor.PrepareOnMainThread(new () { report = args.report }); if (setupResult.additionalInputFiles != null) settings.AdditionalInputFiles = settings.AdditionalInputFiles.Concat(setupResult.additionalInputFiles).ToArray(); if (setupResult.displayName != null) settings.DisplayName = setupResult.displayName; settings.HasCallback = true; } } return settings; } PlayerBuildConfig PlayerBuildConfigFor(BuildPostProcessArgs args) => new PlayerBuildConfig { DestinationPath = GetInstallPathFor(args), StagingArea = args.stagingArea, CompanyName = args.companyName, ProductName = Paths.MakeValidFileName(args.productName), PlayerPackage = args.playerPackage, ApplicationIdentifier = PlayerSettings.GetApplicationIdentifier(GetNamedBuildTarget(args)), InstallIntoBuildsFolder = GetInstallingIntoBuildsFolder(args), GenerateIdeProject = GetCreateSolution(args), Development = (args.options & BuildOptions.Development) == BuildOptions.Development, NoGUID = (args.options & BuildOptions.NoUniqueIdentifier) == BuildOptions.NoUniqueIdentifier, ScriptingBackend = GetScriptingBackend(args), Architecture = GetArchitecture(args), DataFolder = GetDataFolderFor(args), GenerateNativePluginsForAssembliesSettings = GetGenerateNativePluginsForAssembliesSettings(args), Services = new () { EnableAnalytics = UnityEngine.Analytics.Analytics.enabled, EnableCrashReporting = UnityEditor.CrashReporting.CrashReportingSettings.enabled, EnablePerformanceReporting = UnityEngine.Analytics.PerformanceReporting.enabled, EnableUnityConnect = UnityEngine.Connect.UnityConnectSettings.enabled, }, StreamingAssetsFiles = BuildPlayerContext.ActiveInstance.StreamingAssets .Select(e => new StreamingAssetsFile { File = e.src.ToString(), RelativePath = e.dst.ToString() }) .ToArray(), UseNewInputSystem = IsNewInputSystemEnabled(), ManagedAssemblies = GetFilesWithRoleFromBuildReport(args.report, "ManagedLibrary", "DependentManagedLibrary", "ManagedEngineAPI") .Select(p => p.ToString()) .ToArray() }; protected virtual string GetInstallPathFor(BuildPostProcessArgs args) { // Try to minimize path lengths for windows NPath absoluteInstallationPath = args.installPath; return absoluteInstallationPath.IsChildOf(NPath.CurrentDirectory) ? absoluteInstallationPath.RelativeTo(NPath.CurrentDirectory).ToString() : absoluteInstallationPath.ToString(); } protected string GetDataFolderFor(BuildPostProcessArgs args) => $"Library/PlayerDataCache/{BuildPipeline.GetSessionIdForBuildTarget(args.target, args.subtarget)}/Data"; protected ScriptingBackend GetScriptingBackend(BuildPostProcessArgs args) { var scriptingBackend = PlayerSettings.GetScriptingBackend(GetNamedBuildTarget(args)); switch (scriptingBackend) { case ScriptingImplementation.Mono2x: return ScriptingBackend.Mono; case ScriptingImplementation.IL2CPP: return ScriptingBackend.IL2CPP; #pragma warning disable 618 case ScriptingImplementation.CoreCLR: return ScriptingBackend.CoreCLR; #pragma warning restore 618 default: throw new NotSupportedException("Unknown scripting backend:" + scriptingBackend); } } protected virtual string GetPlatformNameForBuildProgram(BuildPostProcessArgs args) => args.target.ToString(); protected virtual string GetArchitecture(BuildPostProcessArgs args) => EditorUserBuildSettings.GetPlatformSettings(BuildPipeline.GetBuildTargetName(args.target), "Architecture"); protected Dictionary<string, Action<NodeFinishedMessage>> ResultProcessors { get; } = new (); RunnableProgram MakePlayerBuildProgram(BuildPostProcessArgs args) { var buildProgramAssembly = new NPath($"{args.playerPackage}/{GetPlatformNameForBuildProgram(args)}PlayerBuildProgram.exe"); NPath buildPipelineFolder = $"{EditorApplication.applicationContentsPath}/Tools/BuildPipeline"; NPath beePlatformFolder = $"{args.playerPackage}/Bee"; var searchPaths = $"{beePlatformFolder}{Path.PathSeparator}"; if (IL2CPPUtils.UsingDevelopmentBuild()) { searchPaths = $"{IL2CPPUtils.ConstructBeeLibrarySearchPath()}{Path.PathSeparator}"; } return new SystemProcessRunnableProgram(NetCoreRunProgram.NetCoreRunPath, new[] { buildProgramAssembly.InQuotes(SlashMode.Native), $"\"{searchPaths}{buildPipelineFolder}\"" }, new () {{ "DOTNET_SYSTEM_GLOBALIZATION_INVARIANT", "1" }}); } static NPath DagDirectory => "Library/Bee"; string DagName(BuildPostProcessArgs args) => $"Player{GetInstallPathFor(args).GetHashCode():x8}"; protected virtual IEnumerable<object> GetDataForBuildProgramFor(BuildPostProcessArgs args) { yield return PlayerBuildConfigFor(args); yield return PluginsDataFor(args); yield return LinkerConfigFor(args); yield return Il2CppConfigFor(args); } protected virtual RunnableProgram BeeBackendProgram(BuildPostProcessArgs args) => null; protected virtual BuildRequest SetupBuildRequest(BuildPostProcessArgs args, ILPostProcessingProgram ilpp) { RunnableProgram buildProgram = MakePlayerBuildProgram(args); var cacheMode = ((args.options & BuildOptions.CleanBuildCache) == BuildOptions.CleanBuildCache) ? UnityBeeDriver.CacheMode.WriteOnly : UnityBeeDriver.CacheMode.ReadWrite; var buildRequest = UnityBeeDriver.BuildRequestFor(buildProgram, DagName(args), DagDirectory.ToString(), false, "",ilpp, cacheMode, UnityBeeDriver.StdOutModeForPlayerBuilds, BeeBackendProgram(args)); buildRequest.DataForBuildProgram.Add(() => GetDataForBuildProgramFor(args).Where(o=> o is not null)); return buildRequest; } // Some node types produce meaningful, human readable error messages, // but the output files names are Unity internals, not helpful to users. // For such nodes, directly print the output if the action fails. void PrintStdoutOnErrorProcessor(NodeFinishedMessage node) { if (node.ExitCode != 0) Debug.LogError(node.Output); else DefaultResultProcessor(node); } void UnityLinkerResultProcessor(NodeFinishedMessage node) { if (node.ExitCode != 0 && node.Output.Contains("UnityEditor")) Debug.LogError($"UnityEditor.dll assembly is referenced by user code, but this is not allowed."); else DefaultResultProcessor(node); } void UsymtoolResultProcessor(NodeFinishedMessage node) { // Usymtool might print a message like "error: <something>" to stdout, even when // it succeeds. So only process error messages when it fails. if (node.ExitCode != 0) DefaultResultProcessor(node); } public BeeBuildPostprocessor() { ResultProcessors["IL2CPP_CodeGen"] = PrintStdoutOnErrorProcessor; ResultProcessors["UnityLinker"] = UnityLinkerResultProcessor; ResultProcessors["ExtractUsedFeatures"] = PrintStdoutOnErrorProcessor; ResultProcessors["Usym"] = UsymtoolResultProcessor; } protected void DefaultResultProcessor(NodeFinishedMessage node, bool printErrors = true, bool printWarnings = true) { var output = node.Node.OutputDirectory; if (string.IsNullOrEmpty(output)) output = node.Node.OutputFile; var lines = (node.Output ?? string.Empty).Split(new[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries); if (printErrors) { var errorKey = "error:"; foreach (var error in lines.Where(l => l.StartsWith(errorKey, StringComparison.InvariantCultureIgnoreCase))) Debug.LogError($"{output}: {error.Substring(errorKey.Length).TrimStart()}"); } if (printWarnings) { var warningKey = "warning:"; foreach (var warning in lines.Where(l => l.StartsWith(warningKey, StringComparison.InvariantCultureIgnoreCase))) Debug.LogWarning($"{output}: {warning.Substring(warningKey.Length).TrimStart()}"); } if (node.ExitCode != 0) Debug.LogError($"Building {output} failed with output:\n{node.Output}"); } void ReportBuildResults() { foreach (var node in BeeDriverResult.NodeFinishedMessages) { var annotationAction = node.Node.Annotation.Split(' ')[0]; if (ResultProcessors.TryGetValue(annotationAction, out var processor)) processor(node); else DefaultResultProcessor(node); } foreach (var resultBeeDriverMessage in BeeDriverResult.BeeDriverMessages) { if (resultBeeDriverMessage.Kind == BeeDriverResult.MessageKind.Warning) Debug.LogWarning(resultBeeDriverMessage.Text); else Debug.LogError(resultBeeDriverMessage.Text); } } void ReportBuildOutputFiles(BuildPostProcessArgs args) { // Remove any previous file entries in the build report. // We can track any file written by the backend ourselves. // Once all platforms use the Bee backend, we can remove a lot // of code to add file entries in the native build pipeline. args.report.DeleteAllFileEntries(); var filesOutput = BeeDriverResult.DataFromBuildProgram.Get<BuiltFilesOutput>(); foreach (var outputfile in filesOutput.Files.ToNPaths().Where(f => f.FileExists() && !f.IsSymbolicLink)) args.report.RecordFileAdded(outputfile.ToString(), outputfile.Extension); var config = filesOutput.BootConfigArtifact.ToNPath().ReadAllLines(); var guidKey = "build-guid="; var guidLine = config.FirstOrDefault(l => l.StartsWith(guidKey)); if (guidLine != null) { var guid = guidLine.Substring(guidKey.Length); args.report.SetBuildGUID(new GUID(guid)); } else { args.report.SetBuildGUID(new GUID("00000000000000000000000000000000")); } } public virtual string PrepareForBuild(BuildPlayerOptions buildOptions) { // Clean the Bee folder in PrepareForBuild, so that it is also clean for script compilation. if ((buildOptions.options & BuildOptions.CleanBuildCache) == BuildOptions.CleanBuildCache) EditorCompilation.ClearBeeBuildArtifacts(); return null; } protected virtual void CleanBuildOutput(BuildPostProcessArgs args) { if (!GetInstallingIntoBuildsFolder(args)) { new NPath(GetInstallPathFor(args)).DeleteIfExists(DeleteMode.Soft); new NPath(GetInstallPathFor(args)).Parent.Combine(GetIl2CppDataBackupFolderName(args)).DeleteIfExists(DeleteMode.Soft); } } static void GenerateNativePluginsForAssemblies(GenerateNativePluginsForAssembliesArgs args) { using var section = UnityBeeDriverProfilerSession.ProfilerInstance.Section(nameof(GenerateNativePluginsForAssembliesArgs)); var generateArgs = new IGenerateNativePluginsForAssemblies.GenerateArgs { assemblyFiles = args.Assemblies }; bool wrotePlugins = false; bool wroteSymbols = false; foreach (var processor in BuildPipelineInterfaces.processors.generateNativePluginsForAssembliesProcessors) { var result = processor.GenerateNativePluginsForAssemblies(generateArgs); if (result.generatedPlugins?.Length > 0) { wrotePlugins = true; foreach (var file in result.generatedPlugins.ToNPaths()) file.Copy($"{args.PluginOutputFolder}/{file.FileName}"); } if (result.generatedSymbols?.Length > 0) { wroteSymbols = true; foreach (var file in result.generatedSymbols.ToNPaths()) file.Copy($"{args.SymbolOutputFolder}/{file.FileName}"); } } if (!wrotePlugins) { // We need to produce a file, so Bee will not be upset when we use the `FilesOrDummy` mechanism. new NPath(args.PluginOutputFolder) .Combine("no_plugins_were_generated.txt") .WriteAllText("GenerateNativePluginsForAssemblies did not produce any output"); } if (!wroteSymbols) { // We need to produce a file, so Bee will not be upset when we use the `FilesOrDummy` mechanism. new NPath(args.SymbolOutputFolder) .Combine("no_symbols_were_generated.txt") .WriteAllText("GenerateNativePluginsForAssemblies did not produce any output"); } } public virtual void PostProcess(BuildPostProcessArgs args) { try { if ((args.options & BuildOptions.CleanBuildCache) == BuildOptions.CleanBuildCache) CleanBuildOutput(args); var buildStep = args.report.BeginBuildStep("Setup incremental player build"); var buildRequest = SetupBuildRequest(args,new ILPostProcessingProgram()); args.report.EndBuildStep(buildStep); buildStep = args.report.BeginBuildStep("Incremental player build"); using var cancellationTokenSource = new CancellationTokenSource(); buildRequest.Target = "Player"; buildRequest.RegisterRPCCallback<GenerateNativePluginsForAssembliesArgs>(nameof(GenerateNativePluginsForAssemblies), GenerateNativePluginsForAssemblies); var activeBuild = BeeDriver.BuildAsync(buildRequest, cancellationToken: cancellationTokenSource.Token); { while (!activeBuild.TaskObject.IsCompleted) { activeBuild.TaskObject.Wait(100); //important to keep on pumping the execution context here, as there might be async tasks being kicked off by the bee driver build that have to run on the main thread. ((UnitySynchronizationContext) SynchronizationContext.Current).Exec(); var activeBuildStatus = activeBuild.Status; float progress = activeBuildStatus.Progress.HasValue ? activeBuildStatus.Progress.Value.nodesFinishedOrUpToDate / (float) activeBuildStatus.Progress.Value.totalNodesQeueued : 0f; if (EditorUtility.DisplayCancelableProgressBar("Incremental Player Build", activeBuildStatus.Description, progress)) { EditorUtility.DisplayCancelableProgressBar("Incremental Player Build", "Canceling build", 1.0f); cancellationTokenSource.Cancel(); } } args.report.EndBuildStep(buildStep); BeeDriverResult = activeBuild.TaskObject.Result; UnityBeeDriverProfilerSession.AddTaskToWaitForBeforeFinishing(BeeDriverResult.ProfileOutputWritingTask); if (BeeDriverResult.Success) { PostProcessCompletedBuild(args); } ReportBuildResults(); UnityBeeDriver.RunCleanBeeCache(); if (BeeDriverResult.Success) { buildStep = args.report.BeginBuildStep("Report output files"); ReportBuildOutputFiles(args); args.report.EndBuildStep(buildStep); } else throw new BuildFailedException($"Player build failed: {args.report.SummarizeErrors()}", silent: true); } } catch (OperationCanceledException) { throw; } catch (BuildFailedException) { throw; } catch (AggregateException e) { if (e.InnerException is OperationCanceledException or BuildFailedException) throw e.InnerException; throw new BuildFailedException(e); } catch (Exception e) { throw new BuildFailedException(e); } } public virtual void PostProcessCompletedBuild(BuildPostProcessArgs args) { if (PlayerSettings.GetManagedStrippingLevel(GetNamedBuildTarget(args)) == ManagedStrippingLevel.Disabled) return; var strippingInfo = GetStrippingInfoFromBuild(args); if (strippingInfo != null && EditorBuildOutputPathFor(args) != null) { args.report.AddAppendix(strippingInfo); var linkerToEditorData = AssemblyStripper.ReadLinkerToEditorData(EditorBuildOutputPathFor(args).ToString()); AssemblyStripper.UpdateBuildReport(linkerToEditorData, strippingInfo); } } public virtual bool AddIconsToBuild(AddIconsArgs args) => true; protected virtual bool GetCreateSolution(BuildPostProcessArgs args) => false; protected virtual NPath EditorBuildOutputPathFor(BuildPostProcessArgs buildPostProcessArgs) => null; protected virtual StrippingInfo GetStrippingInfoFromBuild(BuildPostProcessArgs args) => null; protected virtual bool IsPluginCompatibleWithCurrentBuild(BuildTarget buildTarget, PluginImporter imp) { var cpu = imp.GetPlatformData(buildTarget, "CPU"); return !string.Equals(cpu, "None", StringComparison.OrdinalIgnoreCase); } protected NamedBuildTarget GetNamedBuildTarget(BuildPostProcessArgs args) { var buildTargetGroup = BuildPipeline.GetBuildTargetGroup(args.target); if (buildTargetGroup == BuildTargetGroup.Standalone) { return (StandaloneBuildSubtarget)args.subtarget == StandaloneBuildSubtarget.Server ? NamedBuildTarget.Server : NamedBuildTarget.Standalone; } return NamedBuildTarget.FromBuildTargetGroup(buildTargetGroup); } protected bool GetDevelopment(BuildPostProcessArgs args) => IsBuildOptionSet(args.options, BuildOptions.Development); protected bool GetInstallingIntoBuildsFolder(BuildPostProcessArgs args) => IsBuildOptionSet(args.options, BuildOptions.InstallInBuildFolder); protected bool ShouldAppendBuild(BuildPostProcessArgs args) => IsBuildOptionSet(args.options, BuildOptions.AcceptExternalModificationsToPlayer); protected virtual bool GetAllowDebugging(BuildPostProcessArgs args) => (args.report.summary.options & BuildOptions.AllowDebugging) == BuildOptions.AllowDebugging; } internal class DefaultBuildProperties : BuildProperties { public override DeploymentTargetRequirements GetTargetRequirements() { return null; } } }
UnityCsReference/Editor/Mono/Modules/BeeBuildPostprocessor.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Modules/BeeBuildPostprocessor.cs", "repo_id": "UnityCsReference", "token_count": 16765 }
329
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using UnityEditor.Hardware; using UnityEditorInternal; using UnityEngine; using UnityEngine.Networking.PlayerConnection; namespace UnityEditor.Networking.PlayerConnection { internal interface IConnectionStateInternal : IConnectionState { EditorWindow parentWindow { get; } GUIContent notificationMessage { get; } bool deepProfilingSupported { get; } void AddItemsToTree(ConnectionTreeViewWindow connectionTreeViewWindow, Rect position); string connectionDisplayName { get; set; } } internal enum EditorConnectionTarget { None, MainEditorProcessPlaymode, MainEditorProcessEditmode, // add out-off-process player/profiler here } public static class PlayerConnectionGUIUtility { public static IConnectionState GetConnectionState(EditorWindow parentWindow, Action<string> connectedCallback = null) { return new GeneralConnectionState(parentWindow, (player, editorConnectionTarget) => connectedCallback?.Invoke(player)); } internal static IConnectionState GetConnectionState(EditorWindow parentWindow, Action<EditorConnectionTarget> editorModeTargetSwitchedCallback, Func<EditorConnectionTarget, bool> editorModeTargetConnectionStatus, Action<string, EditorConnectionTarget?> connectedCallback = null) { return new GeneralConnectionState(parentWindow, connectedCallback, editorModeTargetSwitchedCallback, editorModeTargetConnectionStatus); } } static class Styles { public static readonly GUIStyle defaultDropdown = "MiniPullDown"; public static readonly GUIContent dropdownButton = UnityEditor.EditorGUIUtility.TrTextContent("", "Target Selection: Choose the target to connect to."); } public static class PlayerConnectionGUI { public static void ConnectionTargetSelectionDropdown(Rect rect, IConnectionState state, GUIStyle style = null) { var internalState = state as IConnectionStateInternal; if (internalState?.parentWindow) { if (internalState.notificationMessage != null) internalState.parentWindow.ShowNotification(internalState.notificationMessage); else internalState.parentWindow.RemoveNotification(); } style ??= Styles.defaultDropdown; if (!UnityEditor.EditorGUI.DropdownButton(rect, Styles.dropdownButton, FocusType.Keyboard, style)) return; if (internalState != null) { ConnectionTreeViewWindow ctvw = new ConnectionTreeViewWindow(internalState, rect); PopupWindow.Show(rect, ctvw); } } } public static class PlayerConnectionGUILayout { public static void ConnectionTargetSelectionDropdown(IConnectionState state, GUIStyle style = null, int maxWidth = 100) { if (style == null) style = Styles.defaultDropdown; Styles.dropdownButton.text = ConnectionUIHelper.GetToolbarContent(state.connectionName, style, maxWidth ); var size = style.CalcSize(Styles.dropdownButton); Rect connectRect = GUILayoutUtility.GetRect(size.x, size.y); if(connectRect.width > size.x) Styles.dropdownButton.text = ConnectionUIHelper.GetToolbarContent(state.connectionName, style, (int)connectRect.width); PlayerConnectionGUI.ConnectionTargetSelectionDropdown(connectRect, state, style); } } internal class GeneralConnectionState : IConnectionStateInternal { static class Content { public static readonly GUIContent Playmode = UnityEditor.EditorGUIUtility.TrTextContent("Play Mode"); public static readonly GUIContent Editmode = UnityEditor.EditorGUIUtility.TrTextContent("Edit Mode"); public static readonly GUIContent EnterIPText = UnityEditor.EditorGUIUtility.TrTextContent("<Enter IP>"); public static readonly GUIContent AutoconnectedPlayer = UnityEditor.EditorGUIUtility.TrTextContent("(Autoconnected Player)"); public static readonly GUIContent ConnectingToPlayerMessage = UnityEditor.EditorGUIUtility.TrTextContent("Connecting to player... (this can take a while)"); public static readonly string LocalHostProhibited = L10n.Tr(" (Localhost prohibited)"); public static readonly string VersionMismatch = L10n.Tr(" (Version mismatch)"); public static readonly string Editor = "Editor"; public static readonly string DirectConnection = "Direct Connection"; } static GUIContent s_NotificationMessage; public GUIContent notificationMessage => s_NotificationMessage; // keep this constant in sync with PLAYER_DIRECT_IP_CONNECT_GUID in GeneralConnection.h const int PLAYER_DIRECT_IP_CONNECT_GUID = 0xFEED; // keep this constant in sync with PLAYER_DIRECT_URL_CONNECT_GUID in GeneralConnection.h const int PLAYER_DIRECT_URL_CONNECT_GUID = 0xFEEE; const string k_EditorConnectionName = "Editor"; public EditorWindow parentWindow { get; private set; } public ConnectionTarget connectedToTarget => ProfilerDriver.IsConnectionEditor() ? ConnectionTarget.Editor : ConnectionTarget.Player; public string connectionName { get { string name = ProfilerDriver.GetConnectionIdentifier(ProfilerDriver.connectedProfiler); if (m_EditorModeTargetState.HasValue && name.Contains(k_EditorConnectionName)) { if (m_EditorModeTargetConnectionStatus(EditorConnectionTarget.MainEditorProcessEditmode)) name = Content.Editmode.text; else name = Content.Playmode.text; } return name; } } public string connectionDisplayName { get; set; } public bool deepProfilingSupported => ProfilerDriver.IsDeepProfilingSupported(ProfilerDriver.connectedProfiler); event Action<string, EditorConnectionTarget?> connected; event Action<EditorConnectionTarget> switchedEditorModeTarget; Func<EditorConnectionTarget, bool> m_EditorModeTargetConnectionStatus; EditorConnectionTarget? m_EditorModeTargetState = null; static List<WeakReference> s_AllGeneralAttachToPlayerStates = new List<WeakReference>(); public GeneralConnectionState(EditorWindow parentWindow, Action<string, EditorConnectionTarget?> connectedCallback = null, Action<EditorConnectionTarget> editorModeTargetSwitchedCallback = null, Func<EditorConnectionTarget, bool> editorModeTargetConnectionStatus = null) { this.parentWindow = parentWindow; if (parentWindow != null) connected += (player, editorConnectionTarget) => this.parentWindow.Repaint(); if (connectedCallback != null) connected += connectedCallback; if (editorModeTargetSwitchedCallback != null) { Debug.Assert(editorModeTargetConnectionStatus != null, $"{nameof(editorModeTargetConnectionStatus)} can't be null when a {nameof(editorModeTargetSwitchedCallback)} is provided."); switchedEditorModeTarget += editorModeTargetSwitchedCallback; m_EditorModeTargetConnectionStatus = editorModeTargetConnectionStatus; m_EditorModeTargetState = EditorConnectionTarget.None; } s_AllGeneralAttachToPlayerStates.Add(new WeakReference(this)); } private static void SuccessfullyConnectedToPlayer(string player, EditorConnectionTarget? editorConnectionTarget = null) { for (int i = s_AllGeneralAttachToPlayerStates.Count - 1; i >= 0; i--) { if (s_AllGeneralAttachToPlayerStates[i] == null || !s_AllGeneralAttachToPlayerStates[i].IsAlive) { s_AllGeneralAttachToPlayerStates.RemoveAt(i); } var generalConnectionState = (s_AllGeneralAttachToPlayerStates[i].Target as GeneralConnectionState); generalConnectionState.connected?.Invoke(player, editorConnectionTarget); if (editorConnectionTarget.HasValue) { generalConnectionState.switchedEditorModeTarget?.Invoke(editorConnectionTarget.Value); } else { if (player.Contains(k_EditorConnectionName)) { // if e.g. the console or the memory profiler connects to the Editor, the profiler should switch to PlayMode profiling, not to Editmode profiling // especially since falling back onto the Editor is the default. generalConnectionState.switchedEditorModeTarget?.Invoke(EditorConnectionTarget.MainEditorProcessPlaymode); } else { generalConnectionState.switchedEditorModeTarget?.Invoke(EditorConnectionTarget.None); } } } } public virtual void AddItemsToTree(ConnectionTreeViewWindow menu, Rect position) { bool hasAnyConnectionOpen = false; AddAvailablePlayerConnections(menu, ref hasAnyConnectionOpen); AddAvailableDeviceConnections(menu, ref hasAnyConnectionOpen); AddLastConnectedIP(menu, ref hasAnyConnectionOpen); // Case 810030: Check if player is connected using AutoConnect Profiler feature via 'connect <ip> string in PlayerConnectionConfigFile // In that case ProfilerDriver.GetAvailableProfilers() won't return the connected player // But we still want to show that it's connected, because the data is incoming if (!ProfilerDriver.IsConnectionEditor() && !hasAnyConnectionOpen) { menu.AddDisabledItem(new ConnectionDropDownItem(Content.AutoconnectedPlayer.text, ProfilerDriver.connectedProfiler, Content.DirectConnection, ConnectionDropDownItem.ConnectionMajorGroup.Direct, () => true, null)); } AddConnectionViaEnterIPWindow(menu, GUIUtility.GUIToScreenRect(position)); } internal static void DirectIPConnect(string ip) { // Profiler.DirectIPConnect is a blocking call, so a notification message is used to show the progress if (ProfilerDriver.connectedProfiler == PLAYER_DIRECT_IP_CONNECT_GUID) return; s_NotificationMessage = Content.ConnectingToPlayerMessage; ProfilerDriver.DirectIPConnect(ip); s_NotificationMessage = null; SuccessfullyConnectedToPlayer(ip); } internal static void DirectURLConnect(string url) { // Profiler.DirectURLConnect is a blocking call, so a notification message is used to show the progress s_NotificationMessage = Content.ConnectingToPlayerMessage; ProfilerDriver.DirectURLConnect(url); s_NotificationMessage = null; SuccessfullyConnectedToPlayer(url); } void AddLastConnectedIP(ConnectionTreeViewWindow menuOptions, ref bool hasOpenConnection) { string lastIP = AttachToPlayerPlayerIPWindow.GetLastIPString(); if (string.IsNullOrEmpty(lastIP)) return; bool isConnected = ProfilerDriver.connectedProfiler == PLAYER_DIRECT_IP_CONNECT_GUID; hasOpenConnection |= isConnected; menuOptions.AddItem(new ConnectionDropDownItem(lastIP, PLAYER_DIRECT_IP_CONNECT_GUID, Content.DirectConnection, ConnectionDropDownItem.ConnectionMajorGroup.Direct, () => ProfilerDriver.connectedProfiler == PLAYER_DIRECT_IP_CONNECT_GUID, () => DirectIPConnect(lastIP))); } internal static string GetConnectionName(int guid) { // Connection identifier is constructed in the PlayerConnection::ConstructWhoamiString() // in a form "{platform name}(host name or ip)[:port] var name = ProfilerDriver.GetConnectionIdentifier(guid); // Ignore Editor connections which named explicitly after project name. var portSpacerIndex = name.LastIndexOf(')'); if (portSpacerIndex == -1) return name; // Port already specified if (name.Length > (portSpacerIndex + 1) && name[portSpacerIndex + 1] == ':') return name; // If port hasn't been specified in the connection identifier, we place it with "host name or ip" segment. var port = ProfilerDriver.GetConnectionPort(guid); return string.Format("{0}:{1})", name.Substring(0, portSpacerIndex), port); } void AddAvailablePlayerConnections(ConnectionTreeViewWindow menuOptions, ref bool hasOpenConnection, Func<bool> disabler = null) { int[] connectionGuids = ProfilerDriver.GetAvailableProfilers(); for (int index = 0; index < connectionGuids.Length; index++) { int guid = connectionGuids[index]; string name = GetConnectionName(guid); bool isProhibited = ProfilerDriver.IsIdentifierOnLocalhost(guid) && (name.Contains("MetroPlayerX") || name.Contains("UWPPlayerX")); bool enabled = !isProhibited && ProfilerDriver.IsIdentifierConnectable(guid); bool isConnected = ProfilerDriver.connectedProfiler == guid; hasOpenConnection |= isConnected; if (!enabled) { if (isProhibited) name += Content.LocalHostProhibited; else name += Content.VersionMismatch; } if (enabled) { if (m_EditorModeTargetState.HasValue && name.Contains(k_EditorConnectionName)) { if (!menuOptions.HasItem(Content.Playmode.text) && !name.StartsWith("Profiler-")) { menuOptions.AddItem(new ConnectionDropDownItem(Content.Playmode.text, guid, Content.Editor, ConnectionDropDownItem.ConnectionMajorGroup.Editor, () => ProfilerDriver.connectedProfiler == guid && !m_EditorModeTargetConnectionStatus(EditorConnectionTarget .MainEditorProcessPlaymode), () => { ProfilerDriver.connectedProfiler = guid; SuccessfullyConnectedToPlayer(connectionName, EditorConnectionTarget.MainEditorProcessPlaymode); })); menuOptions.AddItem(new ConnectionDropDownItem(Content.Editmode.text, guid, Content.Editor, ConnectionDropDownItem.ConnectionMajorGroup.Editor, () => ProfilerDriver.connectedProfiler == guid && m_EditorModeTargetConnectionStatus(EditorConnectionTarget .MainEditorProcessEditmode), () => { ProfilerDriver.connectedProfiler = guid; SuccessfullyConnectedToPlayer(connectionName, EditorConnectionTarget.MainEditorProcessEditmode); })); } } else { menuOptions.AddItem(new ConnectionDropDownItem( name, guid, null, ConnectionDropDownItem.ConnectionMajorGroup.Unknown, () => ProfilerDriver.connectedProfiler == guid, () => { ProfilerDriver.connectedProfiler = guid; if (ProfilerDriver.connectedProfiler == guid) { SuccessfullyConnectedToPlayer(connectionName); } })); } } else menuOptions.AddDisabledItem(new ConnectionDropDownItem(name, guid, null, ConnectionDropDownItem.ConnectionMajorGroup.Unknown, () => ProfilerDriver.connectedProfiler == guid, null)); } } void AddAvailableDeviceConnections(ConnectionTreeViewWindow menuOptions, ref bool hasOpenConnection) { foreach (var device in DevDeviceList.GetDevices()) { bool supportsPlayerConnection = (device.features & DevDeviceFeatures.PlayerConnection) != 0; if (!device.isConnected || !supportsPlayerConnection) continue; var url = "device://" + device.id; bool isConnected = ProfilerDriver.connectedProfiler == PLAYER_DIRECT_URL_CONNECT_GUID && ProfilerDriver.directConnectionUrl == url; hasOpenConnection |= isConnected; //iphone handles the naming differently to android menuOptions.AddItem(new ConnectionDropDownItem( device.type == "Android" ? device.name.Substring(device.name.IndexOf('(') + 1).TrimEnd(')') : device.name, PLAYER_DIRECT_URL_CONNECT_GUID, "Devices" , ConnectionDropDownItem.ConnectionMajorGroup.Local, () => ProfilerDriver.connectedProfiler == PLAYER_DIRECT_URL_CONNECT_GUID && ProfilerDriver.directConnectionUrl == url, () => DirectURLConnect(url), true, device.type == "iOS" ? "IPhonePlayer" : device.type)); } } void AddConnectionViaEnterIPWindow(ConnectionTreeViewWindow menuOptions, Rect buttonScreenRect, Func<bool> disabler = null) { menuOptions.AddItem(new ConnectionDropDownItem(Content.EnterIPText.text, -2, Content.DirectConnection, ConnectionDropDownItem.ConnectionMajorGroup.Direct, () => false, () => { AttachToPlayerPlayerIPWindow.Show(buttonScreenRect); GUIUtility.ExitGUI(); // clear the gui state to prevent hot control issues })); } private bool disposed = false; // To detect redundant calls ~GeneralConnectionState() { if (!disposed) // Referring to the interface here, because the user only knows about the public IConnectionState interfaces and nothing about the internal GeneralConnectionState (except for the fact that it's about to show up in this error's callstack) Debug.LogError("IConnectionState was not Disposed! Please make sure to call Dispose in OnDisable of the EditorWindow in which it was used."); } public void Dispose() { if (!disposed) { if (s_AllGeneralAttachToPlayerStates != null) { for (int i = s_AllGeneralAttachToPlayerStates.Count - 1; i >= 0; i--) { if (!s_AllGeneralAttachToPlayerStates[i].IsAlive || s_AllGeneralAttachToPlayerStates[i].Target == this) { s_AllGeneralAttachToPlayerStates.RemoveAt(i); } } } parentWindow = null; disposed = true; } } } internal class AttachToPlayerPlayerIPWindow : EditorWindow { static class Content { public static readonly GUIContent ConnectButtonContent = UnityEditor.EditorGUIUtility.TrTextContent("Connect"); public static readonly string EnterPlayerIPWindowName = L10n.Tr("Enter Player IP"); } private const string k_TextFieldControlId = "IPWindow"; private const string k_LastIPEditorPrefKey = "ProfilerLastIP"; private string m_IPString; private bool m_DidFocus = false; public static void Show(Rect buttonScreenRect) { Rect rect = new Rect(buttonScreenRect.x, buttonScreenRect.yMax, 300, 50); AttachToPlayerPlayerIPWindow w = EditorWindow.GetWindowWithRect<AttachToPlayerPlayerIPWindow>(rect, true, Content.EnterPlayerIPWindowName); w.position = rect; w.m_Parent.window.m_DontSaveToLayout = true; } void OnEnable() { m_IPString = GetLastIPString(); } public static string GetLastIPString() { return EditorPrefs.GetString(k_LastIPEditorPrefKey, ""); } void OnGUI() { Event evt = Event.current; bool hitEnter = evt.type == EventType.KeyDown && (evt.keyCode == KeyCode.Return || evt.keyCode == KeyCode.KeypadEnter); UnityEditor.EditorGUILayout.BeginVertical(); { GUILayout.Space(5); GUI.SetNextControlName(k_TextFieldControlId); m_IPString = UnityEditor.EditorGUILayout.TextField(m_IPString); if (!m_DidFocus) { m_DidFocus = true; UnityEditor.EditorGUI.FocusTextInControl(k_TextFieldControlId); } GUI.enabled = m_IPString.Length != 0; if (GUILayout.Button(Content.ConnectButtonContent) || hitEnter) { Close(); // Save ip EditorPrefs.SetString(k_LastIPEditorPrefKey, m_IPString); GeneralConnectionState.DirectIPConnect(m_IPString); GUIUtility.ExitGUI(); } } UnityEditor.EditorGUILayout.EndVertical(); } } }
UnityCsReference/Editor/Mono/Networking/PlayerConnection/AttachToPlayerGUI.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Networking/PlayerConnection/AttachToPlayerGUI.cs", "repo_id": "UnityCsReference", "token_count": 9915 }
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 UnityEngine; namespace UnityEditor.Overlays { enum OverlayPriority { //Default overlays Tools = 0, ToolSettings = 1, GridAndSnap = 2, DrawModes = 5, ViewOptions = 6, Search = 11, Orientation = 12, Cameras = 13, //Additional overlays AINavigation = 20, LightingVisualization = 31, PBRValidation = 32, LightingVisualizationColor = 33, ClothConstraints = 41, ClothCollisions = 42, Default = 100 } [AttributeUsage(AttributeTargets.Class)] public sealed class OverlayAttribute : Attribute { Type m_EditorWindowType; string m_Id; string m_UssName; bool m_DefaultDisplay; string m_DisplayName; DockZone m_DefaultDockZone; DockPosition m_DefaultDockPosition; int m_DefaultDockIndex; Layout m_DefaultLayout; float m_DefaultWidth; float m_DefaultHeight; float m_MinWidth; float m_MinHeight; float m_MaxWidth; float m_MaxHeight; int m_Priority = (int)OverlayPriority.Default; public Type editorWindowType { get => m_EditorWindowType; set => m_EditorWindowType = value; } public string id { get => m_Id; set => m_Id = value; } public string displayName { get => m_DisplayName; set => m_DisplayName = value; } public string ussName { get => m_UssName; set => m_UssName = value; } public bool defaultDisplay { get => m_DefaultDisplay; set => m_DefaultDisplay = value; } public DockZone defaultDockZone { get => m_DefaultDockZone; set => m_DefaultDockZone = value; } public DockPosition defaultDockPosition { get => m_DefaultDockPosition; set => m_DefaultDockPosition = value; } public int defaultDockIndex { get => m_DefaultDockIndex; set => m_DefaultDockIndex = value; } public Layout defaultLayout { get => m_DefaultLayout; set => m_DefaultLayout = value; } public float defaultWidth { get => m_DefaultWidth; set => m_DefaultWidth = value; } public float defaultHeight { get => m_DefaultHeight; set => m_DefaultHeight = value; } public float minWidth { get => m_MinWidth; set => m_MinWidth = value; } public float minHeight { get => m_MinHeight; set => m_MinHeight = value; } public float maxWidth { get => m_MaxWidth; set => m_MaxWidth = value; } public float maxHeight { get => m_MaxHeight; set => m_MaxHeight = value; } internal Vector2 defaultSize => new Vector2(defaultWidth, defaultHeight); internal Vector2 minSize => new Vector2(minWidth, minHeight); internal Vector2 maxSize => new Vector2(maxWidth, maxHeight); public int priority { get => m_Priority; set => m_Priority = value; } public OverlayAttribute() { m_EditorWindowType = null; m_DefaultDisplay = true; m_Id = null; m_DisplayName = null; m_UssName = null; m_DefaultDockZone = DockZone.RightColumn; m_DefaultDockPosition = DockPosition.Bottom; m_DefaultDockIndex = int.MaxValue; m_DefaultLayout = Layout.Panel; m_DefaultWidth = float.NegativeInfinity; m_DefaultHeight = float.NegativeInfinity; m_MinWidth = float.NegativeInfinity; m_MinHeight = float.NegativeInfinity; m_MaxWidth = float.NegativeInfinity; m_MaxHeight = float.NegativeInfinity; if (string.IsNullOrEmpty(m_UssName)) m_UssName = m_Id; } public OverlayAttribute(Type editorWindowType, string id, string displayName, string ussName, bool defaultDisplay = false):this() { this.editorWindowType = editorWindowType; this.displayName = displayName; this.id = id; this.defaultDisplay = defaultDisplay; this.ussName = ussName; } public OverlayAttribute(Type editorWindowType, string id, string displayName, bool defaultDisplay = false) : this(editorWindowType, id, displayName, displayName, defaultDisplay) { } public OverlayAttribute(Type editorWindowType, string displayName, bool defaultDisplay = false) : this(editorWindowType, displayName, displayName, displayName, defaultDisplay) { } } }
UnityCsReference/Editor/Mono/Overlays/OverlayAttribute.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Overlays/OverlayAttribute.cs", "repo_id": "UnityCsReference", "token_count": 2526 }
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 System.Collections.Generic; using System.IO; using System.Linq; using UnityEditorInternal; using UnityEngine; using UnityEngine.UIElements; using Object = UnityEngine.Object; namespace UnityEditor.Overlays { // This is responsible for loading and saving OverlayPresets. It does not serialize presets in the manager, but // rather loads and saves from the various locations that presets can exist. sealed class OverlayPresetManager : ScriptableSingleton<OverlayPresetManager> { static Dictionary<Type, Dictionary<string, OverlayPreset>> loadedPresets => instance.m_Presets; [NonSerialized] Dictionary<Type, Dictionary<string, OverlayPreset>> m_Presets; const string k_FileExtension = "overlay"; const string k_PresetAssetsName = "OverlayPresets.asset"; static string k_PreferencesAssetPath => Path.Combine(InternalEditorUtility.unityPreferencesFolder, "OverlayPresets/" + k_PresetAssetsName); static string k_ResourcesAssetPath => Path.Combine(EditorApplication.applicationContentsPath, "Resources/OverlayPresets/" + k_PresetAssetsName); static string preferencesPath => FileUtil.CombinePaths(InternalEditorUtility.unityPreferencesFolder, "OverlayPresets"); void OnEnable() { AssemblyReloadEvents.beforeAssemblyReload += CleanUpPresets; ReloadAllPresets(); } internal static void SaveOverlayStateToFile(string path, EditorWindow window) { var preset = CreateInstance<OverlayPreset>(); preset.name = Path.GetFileNameWithoutExtension(path); preset.targetWindowType = window.GetType(); window.overlayCanvas.CopySaveData(out var saveData); preset.saveData = saveData; try { SaveToFile(new List<OverlayPreset> {preset}, path); } finally { DestroyImmediate(preset); } } internal static OverlayPreset CreatePresetFromOverlayState(string presetName, EditorWindow window) { var windowType = window.GetType(); if (!TryGetPreset(windowType, presetName, out var preset)) { preset = CreateInstance<OverlayPreset>(); preset.name = presetName; preset.targetWindowType = windowType; AddPreset(preset); } window.overlayCanvas.CopySaveData(out var data); preset.saveData = data; SaveAllPreferences(); return preset; } static void AddPreset(OverlayPreset preset) { if (!loadedPresets.TryGetValue(preset.targetWindowType, out var presets)) loadedPresets.Add(preset.targetWindowType, presets = new Dictionary<string, OverlayPreset>()); if (!presets.ContainsKey(preset.name)) presets.Add(preset.name, preset); else presets[preset.name] = preset; } // used by tests internal static void RevertPreferencesPresetsToDefault() { if (File.Exists(k_PreferencesAssetPath)) FileUtil.DeleteFileOrDirectory(k_PreferencesAssetPath); FileUtil.CopyFileOrDirectory(k_ResourcesAssetPath, k_PreferencesAssetPath); } static void SaveAllPreferences() { List<OverlayPreset> presets = new List<OverlayPreset>(); foreach (var presetsForWindow in loadedPresets) { foreach (var preset in presetsForWindow.Value) { presets.Add(preset.Value); } } SaveToFile(presets, k_PreferencesAssetPath); } internal static void DeletePreset(OverlayPreset preset) { if (preset != null && preset.targetWindowType != null && loadedPresets.TryGetValue(preset.targetWindowType, out var presets) && presets.Remove(preset.name)) { DestroyImmediate(preset); SaveAllPreferences(); } } internal static bool TryGetPreset(Type windowType, string presetName, out OverlayPreset preset) { var currentType = windowType; while (currentType != null) { if (loadedPresets.TryGetValue(currentType, out var p)) if (p.TryGetValue(presetName, out preset)) return true; currentType = currentType.BaseType; } foreach (var i in windowType.GetInterfaces()) { if (loadedPresets.TryGetValue(i, out var p)) if (p.TryGetValue(presetName, out preset)) return true; } preset = null; return false; } public static bool Exists(Type windowType, string presetName) { return TryGetPreset(windowType, presetName, out _); } public static OverlayPreset GetDefaultPreset(Type windowType) { var presets = GetAllPresets(windowType); return presets?.FirstOrDefault(); } internal static IEnumerable<OverlayPreset> GetAllPresets(Type windowType) { List<OverlayPreset> presets = new List<OverlayPreset>(); foreach (var i in windowType.GetInterfaces()) { if (loadedPresets.TryGetValue(i, out var p)) presets.AddRange(p.Values); } while (windowType != null && typeof(EditorWindow).IsAssignableFrom(windowType)) { if (loadedPresets.TryGetValue(windowType, out var p)) presets.AddRange(p.Values); windowType = windowType.BaseType; } return presets; } internal static void ReloadAllPresets() { CleanUpPresets(); instance.m_Presets = LoadAllPresets(); } static void CleanUpPresets() { // Ensure that no zombie overlay presets remains foreach (var preset in Resources.FindObjectsOfTypeAll<OverlayPreset>()) { if (!EditorUtility.IsPersistent(preset)) DestroyImmediate(preset); } } static Dictionary<Type, Dictionary<string, OverlayPreset>> LoadAllPresets() { var results = new Dictionary<Type, Dictionary<string, OverlayPreset>>(); if (!Directory.Exists(preferencesPath)) Directory.CreateDirectory(preferencesPath); if (!File.Exists(k_PreferencesAssetPath)) RevertPreferencesPresetsToDefault(); List<Object> loaded = new List<Object>(64); // load preference based presets var builtin = InternalEditorUtility.LoadSerializedFileAndForget(k_PreferencesAssetPath); // this is necessary for users who tried out overlays preview builds. the registered class ID changed // from 13987 to 13988 during development. we correct that case here. can remove this check in 2022. if (builtin.Length < 1) { RevertPreferencesPresetsToDefault(); builtin = InternalEditorUtility.LoadSerializedFileAndForget(k_PreferencesAssetPath); } loaded.AddRange(builtin); foreach (var rawPreset in loaded) { var preset = rawPreset as OverlayPreset; if (preset != null && preset.targetWindowType != null) { if (!results.TryGetValue(preset.targetWindowType, out var presets)) { presets = new Dictionary<string, OverlayPreset>(); results.Add(preset.targetWindowType, presets); } if (presets.ContainsKey(preset.name)) { Debug.LogWarning($"Failed to load the overlay preset with name {preset.name}. A preset with that name already existed in that window type."); continue; } presets.Add(preset.name, preset); } } return results; } internal static void SaveToFile(IList<OverlayPreset> presets, string path) { var parentLayoutFolder = Path.GetDirectoryName(path); if (!string.IsNullOrEmpty(parentLayoutFolder)) { if (!Directory.Exists(parentLayoutFolder)) Directory.CreateDirectory(parentLayoutFolder); InternalEditorUtility.SaveToSerializedFileAndForget(presets.Cast<Object>().ToArray(), path, true); } } internal static OverlayPreset LoadFromFile(string path) { if (Path.GetExtension(path) != "." + k_FileExtension) { Debug.LogFormat(L10n.Tr("Overlay preset files must have the {0} extension to be valid."), k_FileExtension); return null; } var rawPresets = InternalEditorUtility.LoadSerializedFileAndForget(path); if (rawPresets != null) { //Get the first preset in the file. .overlay files should only ever contained one foreach (var rawPreset in rawPresets) { if (rawPreset is OverlayPreset preset) { preset.name = Path.GetFileNameWithoutExtension(path); return preset; } } } return null; } public static void GenerateMenu(IGenericMenu menu, string pathPrefix, EditorWindow window) { var presets = GetAllPresets(window.GetType()); foreach (var preset in presets) { menu.AddItem(pathPrefix + preset.name, false, () => { window.overlayCanvas.ApplyPreset(preset); }); } menu.AddSeparator(pathPrefix); menu.AddItem(L10n.Tr($"{pathPrefix}Save Preset..."), false, () => { SaveOverlayPreset.ShowWindow(window, name => { var preset = CreatePresetFromOverlayState(name, window); SaveAllPreferences(); window.overlayCanvas.ApplyPreset(preset); }); }); menu.AddItem(L10n.Tr($"{pathPrefix}Save Preset To File..."), false, () => { string path = EditorUtility.SaveFilePanel("Save window preset to disk...", "", "NewOverlayPreset", k_FileExtension); if (!string.IsNullOrEmpty(path)) { SaveOverlayStateToFile(path, window); EditorUtility.RevealInFinder(path); } }); menu.AddItem(L10n.Tr($"{pathPrefix}Load Preset From File..."), false, () => { var filePath = EditorUtility.OpenFilePanel("Load preset from disk...", "", k_FileExtension); if (!string.IsNullOrEmpty(filePath)) { var preset = LoadFromFile(filePath); bool failed = false; if (preset == null) { EditorUtility.DisplayDialog( L10n.Tr("Load Overlay Preset From Disk"), string.Format(L10n.Tr("Failed to load the chosen preset, the file may not be a .{0} or was corrupted."), k_FileExtension), L10n.Tr("Ok")); failed = true; } else if (!preset.CanApplyToWindow(window.GetType())) { EditorUtility.DisplayDialog( L10n.Tr("Load Overlay Preset From Disk"), string.Format(L10n.Tr("Trying to load an overlay preset with the name {0}. This preset targets the window type {0} which isn't valid for this window."), preset.targetWindowType), L10n.Tr("Ok")); failed = true; } if (Exists(preset.targetWindowType, preset.name)) { if (!EditorUtility.DisplayDialog( L10n.Tr("Load Overlay Preset From Disk"), string.Format(L10n.Tr("Trying to load an overlay preset with the name {0}. This name is already in used in the window, do you want to overwrite it?"), preset.name), L10n.Tr("Yes"), L10n.Tr("No"))) { failed = true; } } if (failed) { if (!EditorUtility.IsPersistent(preset)) DestroyImmediate(preset); return; } AddPreset(preset); window.overlayCanvas.ApplyPreset(preset); } }); foreach (var preset in presets) { menu.AddItem(L10n.Tr($"{pathPrefix}Delete Preset/{preset.name}"), false, () => { DeletePreset(preset); }); } menu.AddItem(L10n.Tr($"{pathPrefix}Revert All Saved Presets"), false, () => { if (EditorUtility.DisplayDialog( L10n.Tr("Revert All Saved Presets"), L10n.Tr("Unity is about to delete all overlay presets that are not loaded from files in project and restore default settings."), L10n.Tr("Continue"), L10n.Tr("Cancel"))) { RevertPreferencesPresetsToDefault(); ReloadAllPresets(); } }); } } }
UnityCsReference/Editor/Mono/Overlays/OverlayPresetManager.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Overlays/OverlayPresetManager.cs", "repo_id": "UnityCsReference", "token_count": 7243 }
332
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEditor; namespace UnityEditorInternal.FrameDebuggerInternal { internal static class FrameDebuggerStyles { // match enum FrameEventType on C++ side! internal static readonly string[] s_FrameEventTypeNames = new[] { "Clear (nothing)", "Clear (color)", "Clear (Depth)", "Clear (color+depth)", "Clear (stencil)", "Clear (color+stencil)", "Clear (depth+stencil)", "Clear (color+depth+stencil)", "SetRenderTarget", "Resolve Color", "Resolve Depth", "Grab RenderTexture", "Static Batch", "Dynamic Batch", "Draw Mesh", "Draw Dynamic", "Draw GL", "GPU Skinning", "Draw Procedural", "Draw Procedural Indirect", "Draw Procedural Indexed", "Draw Procedural Indexed Indirect", "Compute", "Ray Tracing Dispatch", "Plugin Event", "Draw Mesh (instanced)", "Begin Subpass", "SRP Batch", "", // on purpose empty string for kFrameEventHierarchyLevelBreak "Hybrid Batch Group", "Configure Foveated Rendering", }; // General settings for the Frame Debugger Window and layout internal struct Window { internal const int k_StartWindowWidth = 1024; internal const float k_MinTreeWidth = k_StartWindowWidth * 0.33f; internal const float k_ResizerWidth = 5f; internal const float k_MinDetailsWidth = 200f; } // Tree internal struct Tree { internal static readonly GUIStyle s_RowText = new GUIStyle(EditorStyles.label); internal static readonly GUIStyle s_RowTextBold = new GUIStyle(EditorStyles.boldLabel); internal static readonly GUIStyle s_RowTextRight = new GUIStyle(EditorStyles.boldLabel) { alignment = TextAnchor.MiddleRight }; internal const string k_UnknownScopeString = "<unknown scope>"; } // Top Toolbar internal struct TopToolbar { internal static readonly GUIContent s_RecordButtonEnable = EditorGUIUtility.TrTextContent(L10n.Tr("Enable")); internal static readonly GUIContent s_RecordButtonDisable = EditorGUIUtility.TrTextContent(L10n.Tr("Disable")); internal static readonly GUIContent s_PrevFrame = EditorGUIUtility.TrIconContent("Profiler.PrevFrame", "Go back one frame"); internal static readonly GUIContent s_NextFrame = EditorGUIUtility.TrIconContent("Profiler.NextFrame", "Go one frame forwards"); internal static readonly GUIContent s_LevelsHeader = EditorGUIUtility.TrTextContent("Levels", "Render target display black/white intensity levels"); } // Event Toolbar in the Event Details window internal struct EventToolbar { private const float k_ToolbarHeight = 22f; private const float k_ChannelButtonWidth = 30f; internal static readonly GUIStyle s_HorizontalStyle = new GUIStyle(EditorStyles.toolbar) { fixedHeight = k_ToolbarHeight + 1f }; internal static readonly GUIStyle s_ChannelHeaderStyle = new GUIStyle(EditorStyles.toolbarLabel) { fixedHeight = k_ToolbarHeight }; internal static readonly GUIStyle s_ChannelStyle = new GUIStyle(EditorStyles.miniButtonMid) { fixedWidth = k_ChannelButtonWidth, }; internal static readonly GUIStyle s_ChannelAllStyle = new GUIStyle(EditorStyles.miniButtonLeft) { fixedWidth = k_ChannelButtonWidth, }; internal static readonly GUIStyle s_ChannelAStyle = new GUIStyle(EditorStyles.miniButtonRight) { fixedWidth = k_ChannelButtonWidth, }; internal static readonly GUIStyle s_PopupLeftStyle = new GUIStyle(EditorStyles.toolbarPopupLeft) { fixedHeight = k_ToolbarHeight }; internal static readonly GUIStyle s_LevelsHorizontalStyle = new GUIStyle(EditorStyles.toolbarButton) { margin = new RectOffset(4, 4, 0, 0), padding = new RectOffset(4, 4, 0, 0), fixedHeight = k_ToolbarHeight }; internal static readonly GUIContent s_DepthLabel = EditorGUIUtility.TrTextContent("Depth", "Show depth buffer"); internal static readonly GUIContent s_StencilLabel = EditorGUIUtility.TrTextContent("Stencil", "Show stencil buffer"); internal static readonly GUIContent s_ChannelHeader = EditorGUIUtility.TrTextContent("Channels", "Which render target color channels to show"); internal static readonly GUIContent s_ChannelAll = EditorGUIUtility.TrTextContent("All"); internal static readonly GUIContent s_ChannelR = EditorGUIUtility.TrTextContent("R"); internal static readonly GUIContent s_ChannelG = EditorGUIUtility.TrTextContent("G"); internal static readonly GUIContent s_ChannelB = EditorGUIUtility.TrTextContent("B"); internal static readonly GUIContent s_ChannelA = EditorGUIUtility.TrTextContent("A"); internal static readonly GUIContent s_LevelsHeader = EditorGUIUtility.TrTextContent("Levels", "Render target display black/white intensity levels"); internal static readonly GUIContent[] s_MRTLabels = new[] { EditorGUIUtility.TrTextContent("RT 0", "Show render target #0"), EditorGUIUtility.TrTextContent("RT 1", "Show render target #1"), EditorGUIUtility.TrTextContent("RT 2", "Show render target #2"), EditorGUIUtility.TrTextContent("RT 3", "Show render target #3"), EditorGUIUtility.TrTextContent("RT 4", "Show render target #4"), EditorGUIUtility.TrTextContent("RT 5", "Show render target #5"), EditorGUIUtility.TrTextContent("RT 6", "Show render target #6"), EditorGUIUtility.TrTextContent("RT 7", "Show render target #7") }; } // Event Details Window internal struct EventDetails { private const int k_Indent1 = 5; private const int k_Indent2 = 20; internal const float k_MaxViewportHeight = 355f; internal const float k_VerticalLabelWidth = 150f; internal const float k_VerticalValueWidth = 250f; internal const float k_MeshNameWidth = k_VerticalLabelWidth + k_VerticalValueWidth; internal const int k_PropertyNameMaxChars = 30; internal const int k_TextureFormatMaxChars = 19; internal const int k_ShaderLabelWidth = 155; internal const int k_ShaderObjectFieldWidth = 450; internal const float k_MeshBottomToolbarHeight = 21f; internal const float k_ArrayValuePopupBtnWidth = 2.0f; internal const string k_FloatFormat = "F7"; internal const string k_IntFormat = "d"; internal const string k_NotAvailable = "-"; internal static string s_DashesString = new string('-', 30); internal static string s_EqualsString = new string('=', 30); internal static readonly GUIStyle s_ArrayFoldoutStyle = new GUIStyle(EditorStyles.foldout) { margin = new RectOffset(-29, 0, 0, 0), }; internal static readonly GUIStyle s_TitleHorizontalStyle = new GUIStyle(EditorStyles.label) { margin = new RectOffset(0, 0, 0, 10), }; internal static readonly GUIStyle s_TitleStyle = new GUIStyle(EditorStyles.largeLabel) { padding = new RectOffset(k_Indent1, 0, k_Indent1, 0), fontStyle = FontStyle.Bold, fontSize = 18, fixedHeight = 50, }; internal static readonly GUIStyle s_FoldoutCategoryBoxStyle = new GUIStyle(EditorStyles.helpBox); internal static readonly GUIStyle s_MonoLabelStyle = new GUIStyle(EditorStyles.label) { alignment = TextAnchor.UpperLeft }; internal static readonly GUIStyle s_MonoLabelStylePadding = new GUIStyle(EditorStyles.label) { alignment = TextAnchor.UpperLeft, padding = new RectOffset(25, 0, 0, 0), }; internal static readonly GUIStyle s_MonoLabelBoldPaddingStyle = new GUIStyle(EditorStyles.label) { alignment = TextAnchor.UpperLeft, padding = new RectOffset(25, 0, 0, 0), }; internal static readonly GUIStyle s_MonoLabelNoWrapStyle = new GUIStyle(EditorStyles.label) { padding = new RectOffset(0, 0, 0, 0), margin = new RectOffset(0, 0, 2, 0), }; internal static readonly GUIStyle s_MonoLabelBoldStyle = new GUIStyle(EditorStyles.label) { padding = new RectOffset(0, 0, 0, 0), margin = new RectOffset(0, 0, 0, 0), }; internal static readonly GUIStyle s_OutputMeshTabStyle = new GUIStyle("LargeButton") { padding = new RectOffset(0, 0, 0, 0), margin = new RectOffset(-2, 0, 0, 0), }; internal static readonly GUIStyle s_RenderTargetMeshBackgroundStyle = new GUIStyle(); internal static readonly GUIStyle s_PropertiesBottomMarginStyle = new GUIStyle(EditorStyles.label) { margin = new RectOffset(0, 0, 0, 10) }; internal static readonly GUIStyle s_PropertiesLeftMarginStyle = new GUIStyle(EditorStyles.label) { margin = new RectOffset(k_Indent2, 0, 0, 0), padding = new RectOffset(0, 0, 0, 0), }; internal static readonly GUIStyle s_TextureButtonStyle = new GUIStyle() { fixedWidth = 20f, margin = new RectOffset(0, 10, 0, 0), }; internal const string k_WarningMultiThreadedMsg = "The Frame Debugger requires multi-threaded renderer. If this error persists, try starting the Editor with -force-gfx-mt command line argument."; internal const string k_WarningLinuxOpenGLMsg = k_WarningMultiThreadedMsg + " On Linux, the editor does not support a multi-threaded renderer when using OpenGL."; internal const string k_DescriptionString = "Frame Debugger lets you step through draw calls and see how exactly frame is rendered. Click Enable!"; internal const string k_TabbedWithPlaymodeErrorString = "Frame Debugger can not be docked with the Game Window when trying to debug the editor."; internal static readonly GUIContent s_RenderTargetText = EditorGUIUtility.TrTextContent("RenderTarget"); internal static readonly GUIContent s_CopyEventText = EditorGUIUtility.TrTextContent("Copy Event Info"); internal static readonly GUIContent s_CopyPropertyText = EditorGUIUtility.TrTextContent("Copy Property"); internal static readonly GUIContent[] s_FoldoutCopyText = { EditorGUIUtility.TrTextContent("Copy Output"), EditorGUIUtility.TrTextContent("Copy All Details"), EditorGUIUtility.TrTextContent("Copy All Keyword Properties"), EditorGUIUtility.TrTextContent("Copy All Texture Properties"), EditorGUIUtility.TrTextContent("Copy All Integer Properties"), EditorGUIUtility.TrTextContent("Copy All Float Properties"), EditorGUIUtility.TrTextContent("Copy All Vector Properties"), EditorGUIUtility.TrTextContent("Copy All Matrix Properties"), EditorGUIUtility.TrTextContent("Copy All Buffer Properties"), EditorGUIUtility.TrTextContent("Copy All Constant Buffer Properties") }; internal static readonly GUIContent s_RealShaderText = EditorGUIUtility.TrTextContent("Used Shader", "The shader used in this draw call."); internal static readonly GUIContent s_OriginalShaderText = EditorGUIUtility.TrTextContent("Original Shader", "The shader originally set to be used in this draw call."); internal static readonly GUIContent s_RayTracingShaderText = EditorGUIUtility.TrTextContent("Ray Tracing Shader", ""); internal static readonly GUIContent s_RayTracingGenerationShaderText = EditorGUIUtility.TrTextContent("Ray Generation Shader", ""); internal static readonly GUIContent s_ComputeShaderText = EditorGUIUtility.TrTextContent("Compute Shader", ""); internal static readonly GUIContent s_BatchCauseText = EditorGUIUtility.TrTextContent("Batch cause"); internal static readonly GUIContent s_PassLightModeText = EditorGUIUtility.TrTextContent("Pass\nLightMode"); internal static readonly GUIContent s_ArrayPopupButtonText = EditorGUIUtility.TrTextContent("..."); internal static readonly GUIContent s_FoldoutOutputText = EditorGUIUtility.TrTextContent("Output"); internal static readonly GUIContent s_FoldoutMeshText = EditorGUIUtility.TrTextContent("Meshes"); internal static readonly GUIContent s_FoldoutMeshNotSupportedText = EditorGUIUtility.TrTextContent("Meshes - Not supported"); internal static readonly GUIContent s_FoldoutEventDetailsText = EditorGUIUtility.TrTextContent("Details"); internal static readonly GUIContent s_FoldoutTexturesText = EditorGUIUtility.TrTextContent("Textures"); internal static readonly GUIContent s_FoldoutKeywordsText = EditorGUIUtility.TrTextContent("Keywords"); internal static readonly GUIContent s_FoldoutFloatsText = EditorGUIUtility.TrTextContent("Floats"); internal static readonly GUIContent s_FoldoutIntsText = EditorGUIUtility.TrTextContent("Ints"); internal static readonly GUIContent s_FoldoutVectorsText = EditorGUIUtility.TrTextContent("Vectors"); internal static readonly GUIContent s_FoldoutMatricesText = EditorGUIUtility.TrTextContent("Matrices"); internal static readonly GUIContent s_FoldoutBuffersText = EditorGUIUtility.TrTextContent("Buffers"); internal static readonly GUIContent s_FoldoutCBufferText = EditorGUIUtility.TrTextContent("Constant Buffers"); internal static readonly GUIContent s_NotAvailableText = EditorGUIUtility.TrTextContent(k_NotAvailable); internal static Texture2D s_RenderTargetMeshBackgroundTexture = null; internal static readonly string[] s_BatchBreakCauses = FrameDebuggerUtility.GetBatchBreakCauseStrings(); } // Constructor static FrameDebuggerStyles() { float greyVal = 0.2196079f; EventDetails.s_RenderTargetMeshBackgroundTexture = MakeTex(1, 1, new Color(greyVal, greyVal, greyVal, 1f)); EventDetails.s_RenderTargetMeshBackgroundStyle.normal.background = EventDetails.s_RenderTargetMeshBackgroundTexture; Font monospacedFont = EditorGUIUtility.Load("Fonts/RobotoMono/RobotoMono-Regular.ttf") as Font; Font monospacedBoldFont = EditorGUIUtility.Load("Fonts/RobotoMono/RobotoMono-Bold.ttf") as Font; EventDetails.s_MonoLabelStyle.font = monospacedFont; EventDetails.s_MonoLabelStylePadding.font = monospacedFont; EventDetails.s_MonoLabelNoWrapStyle.font = monospacedFont; EventDetails.s_ArrayFoldoutStyle.font = monospacedFont; EventDetails.s_MonoLabelBoldStyle.font = monospacedBoldFont; EventDetails.s_MonoLabelBoldPaddingStyle.font = monospacedBoldFont; } private static Texture2D MakeTex(int width, int height, Color col) { Color[] pix = new Color[width * height]; for (int i = 0; i < pix.Length; i++) pix[i] = col; Texture2D result = new Texture2D(width, height); result.SetPixels(pix); result.Apply(); return result; } internal static void OnDisable() { UnityEngine.Object.DestroyImmediate(EventDetails.s_RenderTargetMeshBackgroundTexture); EventDetails.s_RenderTargetMeshBackgroundTexture = null; } } }
UnityCsReference/Editor/Mono/PerformanceTools/FrameDebuggerStyles.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/PerformanceTools/FrameDebuggerStyles.cs", "repo_id": "UnityCsReference", "token_count": 7170 }
333
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEditor; namespace UnityEditor { internal class PlayerPrefsSettings { [MenuItem("Edit/Clear All PlayerPrefs", false, 270, false)] static void ClearPlayerPrefs() { if (EditorUtility.DisplayDialog("Clear All PlayerPrefs", "Are you sure you want to clear all PlayerPrefs? " + "This action cannot be undone.", "Yes", "No")) { PlayerPrefs.DeleteAll(); } } } }
UnityCsReference/Editor/Mono/PlayerPrefsSettings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/PlayerPrefsSettings.cs", "repo_id": "UnityCsReference", "token_count": 280 }
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.Collections.Generic; using UnityEditor.Build; using UnityEngine; using UnityEngine.Bindings; namespace UnityEditor { public enum VisionOSSdkVersion { Device = 0, Simulator = 1 } // 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 partial class PlayerSettings : UnityEngine.Object { // VisionOS specific player settings [NativeHeader("Runtime/Misc/PlayerSettings.h")] [NativeHeader("Editor/Src/EditorUserBuildSettings.h")] [StaticAccessor("GetPlayerSettings()")] public sealed partial class VisionOS { private static extern int sdkVersionInt { [NativeMethod("GetVisionOSSdkVersion")] get; [NativeMethod("SetVisionOSSdkVersion")] set; } public static VisionOSSdkVersion sdkVersion { get { return (VisionOSSdkVersion)sdkVersionInt; } set { sdkVersionInt = (int)value; } } // visionos bundle build number public static string buildNumber { get { return PlayerSettings.GetBuildNumber(NamedBuildTarget.VisionOS.TargetName); } set { PlayerSettings.SetBuildNumber(NamedBuildTarget.VisionOS.TargetName, value); } } [StaticAccessor("GetPlayerSettings().GetEditorOnly()", StaticAccessorType.Dot)] [NativeMethod("GetVisionOSMinimumVersionString")] static extern string GetMinimumVersionString(); internal static readonly Version minimumOsVersion = new Version(GetMinimumVersionString()); public static extern string targetOSVersionString { [NativeMethod("GetVisionOSTargetOSVersion")] get; [NativeMethod("SetVisionOSTargetOSVersion")] set; } } } }
UnityCsReference/Editor/Mono/PlayerSettingsVisionOS.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/PlayerSettingsVisionOS.bindings.cs", "repo_id": "UnityCsReference", "token_count": 941 }
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.Collections.Generic; using UnityEngine; using UnityEngine.Assertions; using UnityObject = UnityEngine.Object; namespace UnityEditor.SceneManagement { public abstract class PrefabOverride { public abstract void Apply(string prefabAssetPath, InteractionMode mode); public abstract void Revert(InteractionMode mode); public void Apply() { var asset = GetAssetObject(); Apply(AssetDatabase.GetAssetPath(asset), InteractionMode.UserAction); } public void Apply(string prefabAssetPath) { Apply(prefabAssetPath, InteractionMode.UserAction); } public void Apply(InteractionMode mode) { var asset = GetAssetObject(); Apply(AssetDatabase.GetAssetPath(asset), mode); } public void Revert() { Revert(InteractionMode.UserAction); } protected UnityObject FindApplyTargetAssetObject(string prefabAssetPath) { var assetObject = GetAssetObject(); while (assetObject != null) { string assetPath = AssetDatabase.GetAssetPath(assetObject); if (assetPath == prefabAssetPath) return assetObject; assetObject = PrefabUtility.GetCorrespondingObjectFromSource(assetObject); } return null; } public abstract UnityObject GetAssetObject(); // Returns the object the override relates to. // For ObjectOverride, it's the object on the instance that has the overrides. // For AddedComponent, it's the added component on the instance. // For AddedGameObject, it's the added GameObject on the instance. // For RemovedComponent, it's the component on the Prefab Asset corresponding to the removed component on the instance. // For RemovedGameObject, it's the GameObject on the Prefab Asset corresponding to the removed GameObject on the instance. internal abstract UnityObject GetObject(); internal void HandleApplyMenuItems(GenericMenu menu, GenericMenu.MenuFunction2 applyAction) { bool isObjectOverride = this is ObjectOverride; Object obj = isObjectOverride ? GetObject() : GetAssetObject(); bool isObjectOverrideAllDefaultOverridesComparedToOriginalSource = isObjectOverride ? PrefabUtility.IsObjectOverrideAllDefaultOverridesComparedToOriginalSource(obj) : false; bool isRemovedGameObjectOverride = this is RemovedGameObject; bool isRemovedNestedPrefabRoot = isRemovedGameObjectOverride && PrefabUtility.IsAssetANestedPrefabRoot(obj); PrefabUtility.HandleApplyMenuItems( null, obj, (menuItemContent, sourceObject, instanceOrAssetObject) => { string prefabAssetPath = AssetDatabase.GetAssetPath(sourceObject); GameObject rootObject = PrefabUtility.GetRootGameObject(sourceObject); bool isPersistent = EditorUtility.IsPersistent(instanceOrAssetObject); if (!PrefabUtility.IsPartOfPrefabThatCanBeAppliedTo(rootObject) || (!isPersistent && !PrefabUtility.HasApplicableObjectOverridesForTarget(instanceOrAssetObject, sourceObject, false))) menu.AddDisabledItem(menuItemContent); else menu.AddItem(menuItemContent, false, applyAction, prefabAssetPath); }, isObjectOverrideAllDefaultOverridesComparedToOriginalSource, !isObjectOverride, !isRemovedNestedPrefabRoot); } } public class ObjectOverride : PrefabOverride { public UnityObject instanceObject { get; set; } public PrefabOverride coupledOverride { get; set; } public override void Apply(string prefabAssetPath, InteractionMode mode) { PrefabUtility.ApplyObjectOverride( instanceObject, prefabAssetPath, mode); } public override void Revert(InteractionMode mode) { PrefabUtility.RevertObjectOverride( instanceObject, mode); } public override UnityObject GetAssetObject() { return PrefabUtility.GetCorrespondingObjectFromSource(instanceObject); } internal override UnityObject GetObject() { return instanceObject; } } public class AddedComponent : PrefabOverride { public Component instanceComponent { get; set; } public override void Apply(string prefabAssetPath, InteractionMode mode) { PrefabUtility.ApplyAddedComponent( instanceComponent, prefabAssetPath, mode); } public override void Revert(InteractionMode mode) { PrefabUtility.RevertAddedComponent( instanceComponent, mode); } public override UnityObject GetAssetObject() { return PrefabUtility.GetCorrespondingObjectFromSource(instanceComponent.gameObject); } internal override UnityObject GetObject() { return instanceComponent; } } public class RemovedComponent : PrefabOverride { public GameObject containingInstanceGameObject { get; set; } public Component assetComponent { get; set; } public override void Apply(string prefabAssetPath, InteractionMode mode) { PrefabUtility.ApplyRemovedComponent( containingInstanceGameObject, (Component)FindApplyTargetAssetObject(prefabAssetPath), mode); } public override void Revert(InteractionMode mode) { PrefabUtility.RevertRemovedComponent( containingInstanceGameObject, assetComponent, mode); } public override UnityObject GetAssetObject() { return assetComponent; } internal override UnityObject GetObject() { return assetComponent; } } public class AddedGameObject : PrefabOverride { public GameObject instanceGameObject { get; set; } public int siblingIndex { get; set; } public override void Apply(string prefabAssetPath, InteractionMode mode) { PrefabUtility.ApplyAddedGameObject( instanceGameObject, prefabAssetPath, mode); } public override void Revert(InteractionMode mode) { PrefabUtility.RevertAddedGameObject( instanceGameObject, mode); } public override UnityObject GetAssetObject() { GameObject parent = instanceGameObject.transform.parent.gameObject; return PrefabUtility.GetCorrespondingObjectFromSource(parent); } internal override UnityObject GetObject() { return instanceGameObject; } } public class RemovedGameObject : PrefabOverride { public GameObject parentOfRemovedGameObjectInInstance { get; set; } public GameObject assetGameObject { get; set; } public override void Apply(string prefabAssetPath, InteractionMode mode) { PrefabUtility.ApplyRemovedGameObject( parentOfRemovedGameObjectInInstance, (GameObject)FindApplyTargetAssetObject(prefabAssetPath), mode); } public override void Revert(InteractionMode mode) { PrefabUtility.RevertRemovedGameObject( parentOfRemovedGameObjectInInstance, assetGameObject, mode); } public override UnityObject GetAssetObject() { return assetGameObject; } internal override UnityObject GetObject() { return assetGameObject; } } }
UnityCsReference/Editor/Mono/Prefabs/PrefabOverrides/PrefabOverride.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Prefabs/PrefabOverrides/PrefabOverride.cs", "repo_id": "UnityCsReference", "token_count": 3591 }
336
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Collections.Generic; using UnityEngine; namespace UnityEditor { [System.Serializable] class DoubleCurve { [SerializeField] AnimationCurve m_MinCurve; [SerializeField] AnimationCurve m_MaxCurve; [SerializeField] bool m_SignedRange; public DoubleCurve(AnimationCurve minCurve, AnimationCurve maxCurve, bool signedRange) { // Ensure not to hold references to other curves AnimationCurve copy; if (minCurve != null) { copy = new AnimationCurve(minCurve.keys); m_MinCurve = copy; } if (maxCurve != null) { copy = new AnimationCurve(maxCurve.keys); m_MaxCurve = copy; } else { Debug.LogError("Ensure that maxCurve is not null when creating a double curve. The minCurve can be null for single curves"); } m_SignedRange = signedRange; } public AnimationCurve minCurve { get { return m_MinCurve; } set { m_MinCurve = value; } } public AnimationCurve maxCurve { get { return m_MaxCurve; } set { m_MaxCurve = value; } } public bool signedRange { get { return m_SignedRange; } set { m_SignedRange = value; } } public bool IsSingleCurve() { return minCurve == null || minCurve.length == 0; } } [ExcludeFromPreset] class DoubleCurvePresetLibrary : PresetLibrary { [SerializeField] List<DoubleCurvePreset> m_Presets = new List<DoubleCurvePreset>(); readonly Rect kUnsignedRange = new Rect(0, 0, 1, 1); // Vertical range 0...1 readonly Rect kSignedRange = new Rect(0, -1, 1, 2); // Vertical range -1...1 readonly Rect kDefaultRange = new Rect(0, 0, -1, -1); // Default range triggers a range to be calculated. bool m_UseRanges = true; public bool useRanges { get { return m_UseRanges; } set { m_UseRanges = value; } } public override int Count() { return m_Presets.Count; } public override object GetPreset(int index) { return m_Presets[index].doubleCurve; } public override void Add(object presetObject, string presetName) { DoubleCurve doubleCurve = presetObject as DoubleCurve; if (doubleCurve == null) { Debug.LogError("Wrong type used in DoubleCurvePresetLibrary: Should be a DoubleCurve"); return; } m_Presets.Add(new DoubleCurvePreset(doubleCurve, presetName)); } public override void Replace(int index, object newPresetObject) { DoubleCurve doubleCurve = newPresetObject as DoubleCurve; if (doubleCurve == null) { Debug.LogError("Wrong type used in DoubleCurvePresetLibrary"); return; } m_Presets[index].doubleCurve = doubleCurve; } 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].doubleCurve); } public override void Draw(Rect rect, object presetObject) { DrawInternal(rect, presetObject as DoubleCurve); } private void DrawInternal(Rect rect, DoubleCurve doubleCurve) { if (doubleCurve == null) { Debug.Log("DoubleCurve is null"); return; } if (m_UseRanges) EditorGUIUtility.DrawRegionSwatch(rect, doubleCurve.maxCurve, doubleCurve.minCurve, new Color(0.8f, 0.8f, 0.8f, 1.0f), EditorGUI.kCurveBGColor, doubleCurve.signedRange ? kSignedRange : kUnsignedRange); else EditorGUIUtility.DrawRegionSwatch(rect, doubleCurve.maxCurve, doubleCurve.minCurve, new Color(0.8f, 0.8f, 0.8f, 1.0f), EditorGUI.kCurveBGColor, kDefaultRange); } 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 DoubleCurvePreset { [SerializeField] string m_Name; [SerializeField] DoubleCurve m_DoubleCurve; public DoubleCurvePreset(DoubleCurve doubleCurvePreset, string presetName) { doubleCurve = doubleCurvePreset; name = presetName; } public DoubleCurve doubleCurve { get { return m_DoubleCurve; } set { m_DoubleCurve = value; } } public string name { get { return m_Name; } set { m_Name = value; } } } } }
UnityCsReference/Editor/Mono/PresetLibraries/DoubleCurvePresetLibrary.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/PresetLibraries/DoubleCurvePresetLibrary.cs", "repo_id": "UnityCsReference", "token_count": 2785 }
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 System.IO; using UnityEditor.Experimental; using UnityEditor.IMGUI.Controls; using UnityEditorInternal; using UnityEngine; namespace UnityEditor { // Used for type check class SearchFilterTreeItem : TreeViewItem { bool m_IsFolder; public SearchFilterTreeItem(int id, int depth, TreeViewItem parent, string displayName, bool isFolder) : base(id, depth, parent, displayName) { m_IsFolder = isFolder; } public bool isFolder {get {return m_IsFolder; }} } //------------------------------------------------ // GUI section internal class ProjectBrowserColumnOneTreeViewGUI : AssetsTreeViewGUI { const float k_DistBetweenRootTypes = 15f; Texture2D k_FavoritesIcon = EditorGUIUtility.FindTexture("Favorite Icon"); Texture2D k_FavoriteFolderIcon = EditorGUIUtility.FindTexture("FolderFavorite Icon"); Texture2D k_FavoriteFilterIcon = EditorGUIUtility.FindTexture("Search Icon"); bool m_IsCreatingSavedFilter = false; public ProjectBrowserColumnOneTreeViewGUI(TreeViewController treeView) : base(treeView) { } // ------------------ // Size section override public Vector2 GetTotalSize() { Vector2 totalSize = base.GetTotalSize(); totalSize.y += k_DistBetweenRootTypes * 1; // assumes that we have two root return totalSize; } public override Rect GetRowRect(int row, float rowWidth) { var rows = m_TreeView.data.GetRows(); return new Rect(0, GetTopPixelOfRow(row, rows), rowWidth, k_LineHeight); } float GetTopPixelOfRow(int row, IList<TreeViewItem> rows) { float topPixel = row * k_LineHeight; // Assumes Saved filter are second root TreeViewItem item = rows[row]; ProjectBrowser.ItemType type = ProjectBrowser.GetItemType(item.id); if (type == ProjectBrowser.ItemType.Asset) topPixel += k_DistBetweenRootTypes; return topPixel; } override public int GetNumRowsOnPageUpDown(TreeViewItem fromItem, bool pageUp, float heightOfTreeView) { return (int)Mathf.Floor(heightOfTreeView / k_LineHeight) - 1; // -1 is fast fix for space between roots } // Should return the row number of the first and last row thats fits in the pixel rect defined by top and height override public void GetFirstAndLastRowVisible(out int firstRowVisible, out int lastRowVisible) { float topPixel = m_TreeView.state.scrollPos.y; float heightInPixels = m_TreeView.GetTotalRect().height; firstRowVisible = (int)Mathf.Floor(topPixel / k_LineHeight); lastRowVisible = firstRowVisible + (int)Mathf.Ceil(heightInPixels / k_LineHeight); float rowsPerSpaceBetween = k_DistBetweenRootTypes / k_LineHeight; firstRowVisible -= (int)Mathf.Ceil(2 * rowsPerSpaceBetween); // for now we just add extra rows to ensure all rows are visible lastRowVisible += (int)Mathf.Ceil(2 * rowsPerSpaceBetween); firstRowVisible = Mathf.Max(firstRowVisible, 0); lastRowVisible = Mathf.Min(lastRowVisible, m_TreeView.data.rowCount - 1); } // ------------------ // Row Gui section override public void OnRowGUI(Rect rowRect, TreeViewItem item, int row, bool selected, bool focused) { bool useBoldFont = IsVisibleRootNode(item); DoItemGUI(rowRect, row, item, selected, focused, useBoldFont); } bool IsVisibleRootNode(TreeViewItem item) { return (m_TreeView.data as ProjectBrowserColumnOneTreeViewDataSource).IsVisibleRootNode(item); } protected override Texture GetIconForItem(TreeViewItem item) { if (item != null && item.icon != null) { var icon = item.icon; var folderItem = item as AssetsTreeViewDataSource.FolderTreeItemBase; if (folderItem != null) { if (folderItem.IsEmpty) icon = emptyFolderTexture; else if (m_TreeView.data.IsExpanded(folderItem)) icon = openFolderTexture; } return icon; } SearchFilterTreeItem searchFilterItem = item as SearchFilterTreeItem; if (searchFilterItem != null) { if (IsVisibleRootNode(item)) return k_FavoritesIcon; if (searchFilterItem.isFolder) return k_FavoriteFolderIcon; else return k_FavoriteFilterIcon; } return base.GetIconForItem(item); } public static float GetListAreaGridSize() { float previewSize = -1f; if (ProjectBrowser.s_LastInteractedProjectBrowser != null) previewSize = ProjectBrowser.s_LastInteractedProjectBrowser.listAreaGridSize; return previewSize; } virtual internal void BeginCreateSavedFilter(SearchFilter filter) { string savedFilterName = "New Saved Search"; m_IsCreatingSavedFilter = true; int instanceID = SavedSearchFilters.AddSavedFilter(savedFilterName, filter, GetListAreaGridSize()); m_TreeView.Frame(instanceID, true, false); // Start naming the asset m_TreeView.state.renameOverlay.BeginRename(savedFilterName, instanceID, 0f); } override protected void RenameEnded() { int instanceID = GetRenameOverlay().userData; ProjectBrowser.ItemType type = ProjectBrowser.GetItemType(instanceID); if (m_IsCreatingSavedFilter) { // Create saved filter m_IsCreatingSavedFilter = false; if (GetRenameOverlay().userAcceptedRename) { SavedSearchFilters.SetName(instanceID, GetRenameOverlay().name); m_TreeView.SetSelection(new[] { instanceID }, true); } else SavedSearchFilters.RemoveSavedFilter(instanceID); } else if (type == ProjectBrowser.ItemType.SavedFilter) { // Renamed saved filter if (GetRenameOverlay().userAcceptedRename) { SavedSearchFilters.SetName(instanceID, GetRenameOverlay().name); } } else { // Let base handle renaming of folders base.RenameEnded(); // Ensure to sync filter to new folder name (so we still show the contents of the folder) if (GetRenameOverlay().userAcceptedRename) m_TreeView.NotifyListenersThatSelectionChanged(); } } } //------------------------------------------------ // DataSource section internal class ProjectBrowserColumnOneTreeViewDataSource : LazyTreeViewDataSource { static string kProjectBrowserString = "ProjectBrowser"; static Texture2D s_FolderIcon = EditorGUIUtility.FindTexture(EditorResources.folderIconName); public bool skipHiddenPackages { get; set; } public ProjectBrowserColumnOneTreeViewDataSource(TreeViewController treeView, bool skipHidden) : base(treeView) { showRootItem = false; rootIsCollapsable = false; skipHiddenPackages = skipHidden; SavedSearchFilters.AddChangeListener(ReloadData); // We reload on change } public override bool IsExpandable(TreeViewItem item) { return item.hasChildren && (item != m_RootItem || rootIsCollapsable); } public override bool CanBeMultiSelected(TreeViewItem item) { return ProjectBrowser.GetItemType(item.id) != ProjectBrowser.ItemType.SavedFilter; } public override bool CanBeParent(TreeViewItem item) { return !(item is SearchFilterTreeItem) || SavedSearchFilters.AllowsHierarchy(); } public bool IsVisibleRootNode(TreeViewItem item) { // The main root Item is invisible the next level is visible root items return (item.parent != null && item.parent.parent == null); } public override bool IsRenamingItemAllowed(TreeViewItem item) { // The 'Assets' root and 'Filters' roots are not allowed to be renamed if (IsVisibleRootNode(item)) return false; switch (ProjectBrowser.GetItemType(item.id)) { case ProjectBrowser.ItemType.Asset: return InternalEditorUtility.CanRenameAsset(item.id); case ProjectBrowser.ItemType.SavedFilter: return true; default: return false; } } public override void FetchData() { bool firstInitialize = !isInitialized; m_RootItem = new TreeViewItem(0, 0, null, "Invisible Root Item"); SetExpanded(m_RootItem, true); // ensure always visible // We want three roots: Favorites, Assets, and Packages List<TreeViewItem> visibleRoots = new List<TreeViewItem>(); // Favorites root TreeViewItem savedFiltersRootItem = SavedSearchFilters.ConvertToTreeView(); visibleRoots.Add(savedFiltersRootItem); // Assets root int assetsFolderInstanceID = AssetDatabase.GetMainAssetOrInProgressProxyInstanceID("Assets"); int depth = 0; string displayName = "Assets"; AssetsTreeViewDataSource.RootTreeItem assetRootItem = new AssetsTreeViewDataSource.RootTreeItem(assetsFolderInstanceID, depth, m_RootItem, displayName); assetRootItem.icon = s_FolderIcon; visibleRoots.Add(assetRootItem); // Packages root displayName = PackageManager.Folders.GetPackagesPath(); AssetsTreeViewDataSource.RootTreeItem packagesRootItem = new AssetsTreeViewDataSource.RootTreeItem(ProjectBrowser.kPackagesFolderInstanceId, depth, m_RootItem, displayName); packagesRootItem.icon = s_FolderIcon; visibleRoots.Add(packagesRootItem); m_RootItem.children = visibleRoots; // Set global expanded state for roots from EditorPrefs (must be before building the rows) if (firstInitialize) { foreach (TreeViewItem item in m_RootItem.children) { bool expanded = EditorPrefs.GetBool(kProjectBrowserString + item.displayName, true); SetExpanded(item, expanded); } } // Build rows //----------- m_Rows = new List<TreeViewItem>(100); // Favorites savedFiltersRootItem.parent = m_RootItem; m_Rows.Add(savedFiltersRootItem); if (IsExpanded(savedFiltersRootItem)) { foreach (var f in savedFiltersRootItem.children) m_Rows.Add(f); } else { savedFiltersRootItem.children = CreateChildListForCollapsedParent(); } // Asset folders m_Rows.Add(assetRootItem); ReadAssetDatabase("Assets", assetRootItem, depth + 1, m_Rows); // Individual Package folders (under the Packages root item) m_Rows.Add(packagesRootItem); var packages = PackageManagerUtilityInternal.GetAllVisiblePackages(skipHiddenPackages); if (IsExpanded(packagesRootItem)) { depth++; foreach (var package in packages) { var packageFolderInstanceId = AssetDatabase.GetMainAssetOrInProgressProxyInstanceID(package.assetPath); displayName = !string.IsNullOrEmpty(package.displayName) ? package.displayName : package.name; AssetsTreeViewDataSource.PackageTreeItem packageItem = new AssetsTreeViewDataSource.PackageTreeItem(packageFolderInstanceId, depth, packagesRootItem, displayName); packageItem.icon = s_FolderIcon; packagesRootItem.AddChild(packageItem); m_Rows.Add(packageItem); ReadAssetDatabase(package.assetPath, packageItem, depth + 1, m_Rows); } } else { if (packages.Length > 0) packagesRootItem.children = CreateChildListForCollapsedParent(); } m_NeedRefreshRows = false; } static bool HasSubFolders(IHierarchyProperty property) { var path = AssetDatabase.GUIDToAssetPath(property.guid); var subFolders = AssetDatabase.GetSubFolders(path); return subFolders.Length > 0; } private void ReadAssetDatabase(string assetFolderRootPath, TreeViewItem parent, int baseDepth, IList<TreeViewItem> allRows) { // Read from Assets directory IHierarchyProperty property = new HierarchyProperty(assetFolderRootPath); property.Reset(); if (!IsExpanded(parent)) { if (HasSubFolders(property)) parent.children = CreateChildListForCollapsedParent(); return; } Texture2D folderIcon = EditorGUIUtility.FindTexture(EditorResources.folderIconName); List<TreeViewItem> allFolders = new List<TreeViewItem>(); var expandedIDs = m_TreeView.state.expandedIDs.ToArray(); while (property.Next(expandedIDs)) { if (property.isFolder) { AssetsTreeViewDataSource.FolderTreeItem folderItem = new AssetsTreeViewDataSource.FolderTreeItem(property.guid, !property.hasChildren, property.GetInstanceIDIfImported(), baseDepth + property.depth, null, property.name); folderItem.icon = folderIcon; allFolders.Add(folderItem); allRows.Add(folderItem); if (!IsExpanded(folderItem)) { if (HasSubFolders(property)) folderItem.children = CreateChildListForCollapsedParent(); } else // expanded status does not get updated when deleting/moving folders. We need to check if the expanded folder still has subFolders when reading the AssetDatabase { if (!HasSubFolders(property)) SetExpanded(folderItem, false); } } } // Fix references TreeViewUtility.SetChildParentReferences(allFolders, parent); } public override void SetExpandedWithChildren(int id, bool expand) { base.SetExpandedWithChildren(id, expand); PersistExpandedState(id, expand); } public override bool SetExpanded(int id, bool expand) { if (base.SetExpanded(id, expand)) { PersistExpandedState(id, expand); return true; } return false; } void PersistExpandedState(int id, bool expand) { // Persist expanded state for ProjectBrowsers InternalEditorUtility.expandedProjectWindowItems = expandedIDs.ToArray(); if (m_RootItem.hasChildren) { // Set global expanded state of roots (Assets folder and Favorites root) foreach (TreeViewItem item in m_RootItem.children) if (item.id == id) EditorPrefs.SetBool(kProjectBrowserString + item.displayName, expand); } } protected override void GetParentsAbove(int id, HashSet<int> parentsAbove) { if (SavedSearchFilters.IsSavedFilter(id)) { parentsAbove.Add(SavedSearchFilters.GetRootInstanceID()); } else { // AssetDatabase folders (in Assets or Packages) var path = AssetDatabase.GetAssetPath(id); if (Directory.Exists(path)) parentsAbove.UnionWith(ProjectWindowUtil.GetAncestors(id)); } } protected override void GetParentsBelow(int id, HashSet<int> parentsBelow) { var extra = GetParentsBelow(id); parentsBelow.UnionWith(extra); } private HashSet<int> GetParentsBelow(int id) { // Add all children expanded ids to hashset HashSet<int> parentsBelow = new HashSet<int>(); // Check if packages instance if (id == ProjectBrowser.kPackagesFolderInstanceId) { parentsBelow.Add(id); var packages = PackageManagerUtilityInternal.GetAllVisiblePackages(skipHiddenPackages); foreach (var package in packages) { var packageFolderInstanceId = AssetDatabase.GetMainAssetOrInProgressProxyInstanceID(package.assetPath); parentsBelow.UnionWith(GetParentsBelow(packageFolderInstanceId)); } return parentsBelow; } var path = AssetDatabase.GetAssetPath(id); IHierarchyProperty search = new HierarchyProperty(path); if (search.Find(id, null)) { parentsBelow.Add(id); int depth = search.depth; while (search.Next(null) && search.depth > depth) { if (search.isFolder && search.hasChildren) parentsBelow.Add(search.instanceID); } } return parentsBelow; } } internal class ProjectBrowserColumnOneTreeViewDragging : AssetsTreeViewDragging { public ProjectBrowserColumnOneTreeViewDragging(TreeViewController treeView) : base(treeView) { } public override void StartDrag(TreeViewItem draggedItem, List<int> draggedItemIDs) { if (SavedSearchFilters.IsSavedFilter(draggedItem.id)) { // Root Filters Item is not allowed to be dragged if (draggedItem.id == SavedSearchFilters.GetRootInstanceID()) return; } ProjectWindowUtil.StartDrag(draggedItem.id, draggedItemIDs); } public override DragAndDropVisualMode DoDrag(TreeViewItem parentItem, TreeViewItem targetItem, bool perform, DropPosition dropPos) { if (targetItem == null) return DragAndDropVisualMode.None; object savedFilterData = DragAndDrop.GetGenericData(ProjectWindowUtil.k_DraggingFavoriteGenericData); // Dragging saved filter if (savedFilterData != null) { int instanceID = (int)savedFilterData; if (targetItem is SearchFilterTreeItem && parentItem is SearchFilterTreeItem)// && targetItem.id != draggedInstanceID && parentItem.id != draggedInstanceID) { bool validMove = SavedSearchFilters.CanMoveSavedFilter(instanceID, parentItem.id, targetItem.id, dropPos == DropPosition.Below); if (validMove && perform) { SavedSearchFilters.MoveSavedFilter(instanceID, parentItem.id, targetItem.id, dropPos == DropPosition.Below); m_TreeView.SetSelection(new[] { instanceID }, false); m_TreeView.NotifyListenersThatSelectionChanged(); } return validMove ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.None; } return DragAndDropVisualMode.None; } // Dragging of folders into filters else { // Check if we are dragging a single folder if (targetItem is SearchFilterTreeItem) { string genericData = DragAndDrop.GetGenericData(ProjectWindowUtil.k_IsFolderGenericData) as string; if (genericData == "isFolder") { if (perform) { Object[] objs = DragAndDrop.objectReferences; if (objs.Length > 0) { string path = AssetDatabase.GetAssetPath(objs[0].GetInstanceID()); if (!string.IsNullOrEmpty(path)) { // TODO: Fix with new AssetDatabase API when it is ready (GetName) string folderName = new DirectoryInfo(path).Name; SearchFilter searchFilter = new SearchFilter(); searchFilter.folders = new[] {path}; bool addAsChild = targetItem == parentItem; float previewSize = ProjectBrowserColumnOneTreeViewGUI.GetListAreaGridSize(); int instanceID = SavedSearchFilters.AddSavedFilterAfterInstanceID(folderName, searchFilter, previewSize, targetItem.id, addAsChild); m_TreeView.SetSelection(new[] { instanceID }, false); m_TreeView.NotifyListenersThatSelectionChanged(); } else { Debug.Log("Could not get asset path from id " + objs[0].GetInstanceID()); } } } return DragAndDropVisualMode.Copy; // Allow dragging folders to filters } return DragAndDropVisualMode.None; // Assets that are not folders are not allowed to be dragged to filters } } // Assets are handled by base return base.DoDrag(parentItem, targetItem, perform, dropPos); } } }
UnityCsReference/Editor/Mono/ProjectBrowser/ProjectBrowserColumnOne.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/ProjectBrowser/ProjectBrowserColumnOne.cs", "repo_id": "UnityCsReference", "token_count": 10913 }
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.Runtime.InteropServices; using UnityEngine.Bindings; namespace UnityEngine { [StructLayout(LayoutKind.Sequential)] internal sealed partial class RuntimeInitializeMethodInfo { string m_FullClassName; string m_MethodName; int m_OrderNumber = 0; bool m_IsUnityClass = false; internal string fullClassName { get { return m_FullClassName; } set { m_FullClassName = value; } } internal string methodName { get { return m_MethodName; } set { m_MethodName = value; } } internal int orderNumber { get { return m_OrderNumber; } set { m_OrderNumber = value; } } internal bool isUnityClass { get { return m_IsUnityClass; } set { m_IsUnityClass = value; } } } [StructLayout(LayoutKind.Sequential)] [Serializable] internal class RuntimeInitializeClassInfo { public string assemblyName; public string nameSpace; public string className; public string methodName; public int loadTypes; } [NativeHeader("Runtime/Misc/RuntimeInitializeOnLoadManager.h")] [StaticAccessorAttribute("GetRuntimeInitializeOnLoadManager()")] internal sealed partial class RuntimeInitializeOnLoadManager { extern internal static string[] dontStripClassNames { get; } } }
UnityCsReference/Editor/Mono/RuntimeInitializeOnLoadManager.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/RuntimeInitializeOnLoadManager.bindings.cs", "repo_id": "UnityCsReference", "token_count": 541 }
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.Collections.ObjectModel; using System.IO; using System.Linq; using UnityEditor.Callbacks; using UnityEditor.IMGUI.Controls; using UnityEngine; using UnityEngine.Assertions; using UnityEngine.SceneManagement; using UnityEngine.Scripting.APIUpdating; namespace UnityEditor.SceneManagement { [Serializable] [MovedFrom("UnityEditor.Experimental.SceneManagement")] public sealed partial class PrefabStage : PreviewSceneStage { static class Styles { public static GUIContent autoSaveGUIContent = EditorGUIUtility.TrTextContent("Auto Save", "When Auto Save is enabled, every change you make is automatically saved to the Prefab Asset. Disable Auto Save if you experience long import times."); public static GUIContent saveButtonContent = EditorGUIUtility.TrTextContent("Save"); public static GUIContent checkoutButtonContent = EditorGUIUtility.TrTextContent("Check Out"); public static GUIContent autoSavingBadgeContent = EditorGUIUtility.TrTextContent("Auto Saving..."); public static GUIContent immutablePrefabContent = EditorGUIUtility.TrTextContent("Immutable Prefab"); public static GUIStyle saveToggle; public static GUIStyle button; public static GUIStyle savingBadge = "Badge"; public static GUIStyle exposablePopup = "ExposablePopupMenu"; public static GUIStyle exposablePopupItem = "ExposablePopupItem"; public static GUIContent contextLabel = EditorGUIUtility.TrTextContent("Context:"); public static GUIContent[] contextRenderModeTexts = new[] { EditorGUIUtility.TrTextContent("Normal"), EditorGUIUtility.TrTextContent("Gray"), EditorGUIUtility.TrTextContent("Hidden") }; public static StageUtility.ContextRenderMode[] contextRenderModeOptions = new[] { StageUtility.ContextRenderMode.Normal, StageUtility.ContextRenderMode.GreyedOut, StageUtility.ContextRenderMode.Hidden }; public static GUIContent showOverridesLabel = EditorGUIUtility.TrTextContent("Show Overrides", "Visualize overrides from the Prefab instance on the Prefab Asset. Overrides on the root Transform are always visualized."); public static GUIContent showOverridesLabelWithTooManyOverridesTooltip = EditorGUIUtility.TrTextContent("Show Overrides", "Show Overrides are disabled because there are too many overrides to visualize. Overrides on the root Transform are always visualized though."); static Styles() { saveToggle = EditorStyles.toggle; button = EditorStyles.miniButton; button.margin.top = button.margin.bottom = 0; } } internal static string s_PrefabInContextPreviewValuesTooltip = L10n.Tr("This property is previewing the overridden value on the Prefab instance.\n\nTo edit this property, open this Prefab Asset in isolation by pressing the modifier key [Alt] while you open it."); public enum Mode { InIsolation, InContext } public static event Action<PrefabStage> prefabStageOpened; public static event Action<PrefabStage> prefabStageClosing; public static event Action<PrefabStage> prefabStageDirtied; public static event Action<GameObject> prefabSaving; public static event Action<GameObject> prefabSaved; internal static event Action<PrefabStage> prefabStageSavedAsNewPrefab; internal static event Action<PrefabStage> prefabStageReloaded; // Used by tests. internal static List<PrefabStage> m_AllPrefabStages = new List<PrefabStage>(); static StateCache<PrefabStageHierarchyState> s_StateCache = new StateCache<PrefabStageHierarchyState>("Library/StateCache/PrefabStageHierarchy/"); GameObject m_PrefabContentsRoot; // Prefab asset being edited string m_PrefabAssetPath; GameObject m_OpenedFromInstanceRoot; GameObject m_OpenedFromInstanceObject; ulong m_FileIdForOpenedFromInstanceObject; Stage m_ContextStage = null; Mode m_Mode; int m_InitialSceneDirtyID; int m_LastSceneDirtyID; bool m_IgnoreNextAssetImportedEventForCurrentPrefab; bool m_PrefabWasChangedOnDisk; bool m_StageDirtiedFired; bool m_IsPrefabInImmutableFolder; bool m_IsPrefabInValidAssetFolder; HideFlagUtility m_HideFlagUtility; Texture2D m_PrefabFileIcon; bool m_TemporarilyDisableAutoSave; float m_LastSavingDuration = 0f; Transform m_LastRootTransform; const float kDurationBeforeShowingSavingBadge = 1.0f; static ExposablePopupMenu s_ContextRenderModeSelector; Hash128 m_InitialFileHash; byte[] m_InitialFileContent; Hash128 m_LastPrefabSourceFileHash; bool m_NeedsReloadingWhenReturningToStage; bool m_IsAssetMissing; bool m_TemporarilyDisablePatchAllOverridenProperties; const int k_MaxNumberOfOverridesToVisualize = 2000; internal static SavedBool s_PatchAllOverriddenProperties = new SavedBool("InContextEditingPatchOverriddenProperties", false); [System.Serializable] struct PatchedProperty { public PropertyModification modification; public UnityEngine.Object targetInContent; } List<PatchedProperty> m_PatchedProperties; bool m_AnalyticsDidUserModify; bool m_AnalyticsDidUserSave; internal static PrefabStage CreatePrefabStage(string prefabAssetPath, GameObject openedFromInstanceObject, PrefabStage.Mode prefabStageMode, Stage contextStage) { PrefabStage prefabStage = CreateInstance<PrefabStage>(); try { prefabStage.OneTimeInitialize(prefabAssetPath, openedFromInstanceObject, prefabStageMode, contextStage); } catch { DestroyImmediate(prefabStage); throw; } return prefabStage; } // Used for tests, if nothing else. internal static ReadOnlyCollection<PrefabStage> allPrefabStages { get { return m_AllPrefabStages.AsReadOnly(); } } private PrefabStage() { } void OneTimeInitialize(string prefabAssetPath, GameObject openedFromInstanceGameObject, PrefabStage.Mode prefabStageMode, Stage contextStage) { if (scene.IsValid()) Debug.LogError("PrefabStage is already initialized. Please report a bug."); m_PrefabAssetPath = prefabAssetPath; CachePrefabFolderInfo(); SetOpenedFromInstanceObject(openedFromInstanceGameObject); if (prefabStageMode == PrefabStage.Mode.InContext) m_ContextStage = contextStage; m_Mode = prefabStageMode; } bool IsOpenedFromInstanceObjectValid() { return m_OpenedFromInstanceObject != null && PrefabUtility.IsPartOfPrefabInstance(m_OpenedFromInstanceObject); } static GameObject FindPrefabInstanceRootThatMatchesPrefabAssetPath(GameObject prefabInstanceObject, string prefabAssetPath) { if (prefabInstanceObject == null) throw new ArgumentNullException(nameof(prefabInstanceObject)); if (string.IsNullOrEmpty(prefabAssetPath)) throw new ArgumentNullException(nameof(prefabAssetPath)); if (PrefabUtility.GetCorrespondingObjectFromSourceAtPath(prefabInstanceObject, prefabAssetPath) == null) { //Variants with broken parents if (AssetDatabase.LoadMainAssetAtPath(prefabAssetPath) is BrokenPrefabAsset) return prefabInstanceObject; else throw new ArgumentException($"'{nameof(prefabInstanceObject)}' is not related to the Prefab at path: '{prefabAssetPath}'"); } Transform transform = prefabInstanceObject.transform; while (transform != null) { var assetObject = PrefabUtility.GetCorrespondingObjectFromSourceAtPath(transform, prefabAssetPath); if (assetObject != null && assetObject.parent == null) return transform.gameObject; transform = transform.parent; } return null; } void SetOpenedFromInstanceObject(GameObject go) { if (go != null) { if (!PrefabUtility.IsPartOfPrefabInstance(go)) throw new ArgumentException("Prefab Mode: GameObject must be part of a Prefab instance, or null.", nameof(go)); m_OpenedFromInstanceObject = go; m_OpenedFromInstanceRoot = FindPrefabInstanceRootThatMatchesPrefabAssetPath(go, m_PrefabAssetPath); if (m_OpenedFromInstanceRoot == null) throw new ArgumentException($"Prefab Mode: The 'openedFromInstance' GameObject '{go.name}' is unrelated to the Prefab Asset '{m_PrefabAssetPath}'."); m_FileIdForOpenedFromInstanceObject = Unsupported.GetOrGenerateFileIDHint(go); } else { m_OpenedFromInstanceObject = null; m_OpenedFromInstanceRoot = null; m_FileIdForOpenedFromInstanceObject = 0; } } void ReconstructInContextStateIfNeeded() { // The previous PrefabStage can have been reloaded if user chose to discard changes when entering this PrefabStage, // which means we need to update our reference to m_OpenedFromInstanceObject to the newly loaded GameObject // (the old GameObject was deleted as part of reloading the PrefabStage). bool needsReconstruction = m_OpenedFromInstanceObject == null && m_FileIdForOpenedFromInstanceObject != 0; if (!needsReconstruction) return; var history = StageNavigationManager.instance.stageHistory; int index = history.IndexOf(this); int previousIndex = index - 1; var previousStage = history[previousIndex]; var previousPrefabStage = previousStage as PrefabStage; if (previousPrefabStage) { var go = PrefabStageUtility.FindFirstGameObjectThatMatchesFileID(previousPrefabStage.prefabContentsRoot.transform, m_FileIdForOpenedFromInstanceObject, true); if (go != null) { if (PrefabUtility.IsPartOfPrefabInstance(go)) SetOpenedFromInstanceObject(go); } else { // Could not find GameObject with fileID: m_FileIdForOpenedFromInstanceObject, this can happen if inserting a variant parent in a Variant and then discarding changes when entering in-context of the new base } } } internal bool analyticsDidUserModify { get { return m_AnalyticsDidUserModify; } } internal bool analyticsDidUserSave { get { return m_AnalyticsDidUserSave; } } static class Icons { public static Texture2D prefabVariantIcon = EditorGUIUtility.LoadIconRequired("PrefabVariant Icon"); public static Texture2D prefabIcon = EditorGUIUtility.LoadIconRequired("Prefab Icon"); } protected override void OnEnable() { base.OnEnable(); PrefabUtility.savingPrefab += OnSavingPrefab; PrefabUtility.prefabInstanceUpdated += OnPrefabInstanceUpdated; AssetEvents.assetsChangedOnHDD += OnAssetsChangedOnHDD; Undo.undoRedoEvent += UndoRedoPerformed; EditorApplication.playModeStateChanged += OnPlayModeStateChanged; m_AllPrefabStages.Add(this); } protected override void OnDisable() { base.OnDisable(); PrefabUtility.savingPrefab -= OnSavingPrefab; PrefabUtility.prefabInstanceUpdated -= OnPrefabInstanceUpdated; AssetEvents.assetsChangedOnHDD -= OnAssetsChangedOnHDD; Undo.undoRedoEvent -= UndoRedoPerformed; EditorApplication.playModeStateChanged -= OnPlayModeStateChanged; // Also cleanup any potential registered event handlers EditorApplication.update -= DelayedFraming; EditorApplication.update -= PerformDelayedAutoSave; m_AllPrefabStages.Remove(this); } public GameObject prefabContentsRoot { get { if (m_PrefabContentsRoot == null) throw new InvalidOperationException("Requesting 'prefabContentsRoot' from Awake and OnEnable is not supported"); // The Prefab stage's m_PrefabContentsRoot is not yet set when we call Awake and OnEnable on user scripts when loading a Prefab return m_PrefabContentsRoot; } } public GameObject openedFromInstanceRoot { get { return m_OpenedFromInstanceRoot; } } public GameObject openedFromInstanceObject { get { return m_OpenedFromInstanceObject; } } public Mode mode { get { return m_Mode; } } bool isCurrentStage { get { return StageUtility.GetCurrentStage() == this; } } public override ulong GetCombinedSceneCullingMaskForCamera() { if (m_Mode == Mode.InIsolation) { return GetSceneCullingMask(); } else if (m_Mode == Mode.InContext) { var stageHistory = StageNavigationManager.instance.stageHistory; if (this == stageHistory.Last()) { ulong mask = GetSceneCullingMask(); int count = stageHistory.Count; for (int i = count - 2; i >= 0; i--) { var stage = stageHistory[i]; if (stage) { mask |= stage.GetSceneCullingMask(); var prefabStage = stage as PrefabStage; if (prefabStage) { if (prefabStage.mode != Mode.InContext) break; } } } // Remove the MainStagePrefabInstanceObjectsOpenInPrefabMode bit from the camera's scenecullingmask. By removing that bit we ensure we hide the MainStage Prefab instance // when editing its Prefab Asset in context. Since the MainStage Prefab instance GameObjects have the MainStagePrefabInstanceObjectsOpenInPrefabMode // set when as override-scenecullingmask when entering Prefab Mode in Context for MainStage instances. mask &= ~SceneCullingMasks.MainStagePrefabInstanceObjectsOpenInPrefabMode; return mask; } else { Debug.LogError("We should only call GetOverrideSceneCullingMask() for the current stage"); return 0; } } else { Debug.LogError("Unhandled PrefabStage.Mode"); return 0; } } internal override Stage GetContextStage() { if (m_ContextStage != null) return m_ContextStage; return this; } internal override Color GetBackgroundColor() { // Case 1255995 - Workaround for OSX 10.15 driver issue with Intel 630 cards Color opaqueBackground = SceneView.kSceneViewPrefabBackground.Color; opaqueBackground.a = 1; return opaqueBackground; } public bool IsPartOfPrefabContents(GameObject gameObject) { if (gameObject == null) return false; Transform tr = gameObject.transform; Transform instanceRootTransform = prefabContentsRoot.transform; while (tr != null) { if (tr == instanceRootTransform) return true; tr = tr.parent; } return false; } internal override bool showOptionsButton { get { return true; } } public override string assetPath { get { return m_PrefabAssetPath; } } internal override bool SupportsSaving() { return true; } internal override bool hasUnsavedChanges { get { return scene.dirtyID != m_InitialSceneDirtyID; } } internal bool showingSavingLabel { get; private set; } internal Texture2D prefabFileIcon { get { return m_PrefabFileIcon; } } string GetPrefabFileName() { return Path.GetFileNameWithoutExtension(m_PrefabAssetPath); } internal bool autoSave { get { return EditorSettings.prefabModeAllowAutoSave && !m_TemporarilyDisableAutoSave && StageNavigationManager.instance.autoSave; } set { if (!EditorSettings.prefabModeAllowAutoSave) return; m_TemporarilyDisableAutoSave = false; StageNavigationManager.instance.autoSave = value; } } internal bool temporarilyDisableAutoSave { get { return m_TemporarilyDisableAutoSave || isAssetMissing; } } internal override bool isValid { get { return m_PrefabContentsRoot != null && m_PrefabContentsRoot.scene == scene; } } internal override bool isAssetMissing { get { return m_IsAssetMissing; } } void OnPrefabInstanceUpdated(GameObject instance) { if (mode == Mode.InContext && m_OpenedFromInstanceRoot != null) { // We check against the outerMostInstanceRoot since that is what will be updated when // we change that or any nested prefabs. E.g having PrefabA instance (that have nested PrefabB) in the Scene and we can enter // Prefab Mode in Context for prefabB from the scene. Then adding a child; it will then be instanceA that will need to have // its objects visibility updated. var outerMostInstanceRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(m_OpenedFromInstanceRoot); bool canHaveChangedCurrentlyHiddenObjects = outerMostInstanceRoot == instance; if (canHaveChangedCurrentlyHiddenObjects) { SetPrefabInstanceHiddenForInContextEditing(true); // if new GameObjects was added to the instance this will ensure to mark them hidden as well } } } void SetPrefabInstanceHiddenForInContextEditing(bool hide) { // In Playmode all instances have been unpacked so we need to check if the PrefabInstanceHandle have been deleted if (m_OpenedFromInstanceRoot != null && PrefabUtility.GetPrefabInstanceHandle(m_OpenedFromInstanceRoot) != null) StageUtility.SetPrefabInstanceHiddenForInContextEditing(m_OpenedFromInstanceRoot, hide); } void UpdateSortableComponentsWithStagePriority(int stagePriority) { List<Renderer> rendererList = new List<Renderer>(); List<Canvas> canvasList = new List<Canvas>(); // Renderer components requires to know there is stage priority when entering context and isolation // mode. If this is not shared, their sorting order will not be evaluated accordingly since they are not // in the same layer. m_PrefabContentsRoot.GetComponentsInChildren<Renderer>(true, rendererList); m_PrefabContentsRoot.GetComponentsInChildren<Canvas>(true, canvasList); foreach (Renderer renderer in rendererList) renderer.stagePriority = (byte)stagePriority; foreach (Canvas canvas in canvasList) canvas.stagePriority = (byte)stagePriority; } bool LoadStage() { if (scene.IsValid()) { Debug.LogError("LoadStage: we haven't cleared the previous scene before loading a new scene"); return false; } if (!File.Exists(m_PrefabAssetPath)) { Debug.LogError("LoadStage: Prefab file not found " + m_PrefabAssetPath); return false; } ReconstructInContextStateIfNeeded(); if (m_Mode == Mode.InContext && !IsOpenedFromInstanceObjectValid()) { // The Prefab instance used for opening Prefab Mode In Context has become invalid. Opening in Isolation instead. SetOpenedFromInstanceObject(null); m_ContextStage = null; m_Mode = Mode.InIsolation; } // Ensure scene is set before calling LoadPrefabIntoPreviewScene() so the user can request the current // the PrefabStage in their OnEnable and other callbacks (if they use ExecuteInEditMode or ExecuteAlways) bool isUIPrefab = PrefabStageUtility.IsUIPrefab(m_PrefabAssetPath); switch (m_Mode) { case Mode.InIsolation: scene = PrefabStageUtility.GetEnvironmentSceneOrEmptyScene(isUIPrefab); break; case Mode.InContext: scene = EditorSceneManager.NewPreviewScene(); break; default: Debug.LogError("Unhandled enum"); break; } m_PrefabContentsRoot = PrefabStageUtility.LoadPrefabIntoPreviewScene(m_PrefabAssetPath, scene); if (m_PrefabContentsRoot != null) { // Corresponds to which breadcrumb this is. var stagePriority = StageNavigationManager.instance.stageHistory.IndexOf(this); if (isUIPrefab) { UpdateSortableComponentsWithStagePriority(stagePriority); if (m_Mode == Mode.InIsolation && m_PrefabContentsRoot.transform.parent == null) PrefabStageUtility.HandleUIReparentingIfNeeded(m_PrefabContentsRoot, stagePriority); } m_PrefabFileIcon = DeterminePrefabFileIconFromInstanceRootGameObject(); m_LastRootTransform = m_PrefabContentsRoot.transform; m_InitialSceneDirtyID = scene.dirtyID; m_StageDirtiedFired = false; UpdateEnvironmentHideFlags(); if (m_Mode == Mode.InContext) { SetPrefabInstanceHiddenForInContextEditing(true); Transform instanceParent = openedFromInstanceRoot.transform.parent; if (instanceParent != null) { // Insert dummy parent which ensure Prefab contents is aligned same as Prefab instance. GameObject dummyParent = new GameObject(PrefabUtility.kDummyPrefabStageRootObjectName); EditorSceneManager.MoveGameObjectToScene(dummyParent, scene); dummyParent.transform.SetParent(m_PrefabContentsRoot.transform.parent, false); // Make Prefab content parent match alignment of Prefab instance parent. // This code doesn't reliably handle cases where the parent matrix is non-orthogonal. dummyParent.transform.localScale = instanceParent.lossyScale; dummyParent.transform.rotation = instanceParent.rotation; dummyParent.transform.position = instanceParent.position; RectTransform instanceRectParent = instanceParent as RectTransform; if (instanceRectParent != null) { RectTransform rect = dummyParent.AddComponent<RectTransform>(); rect.sizeDelta = instanceRectParent.rect.size; rect.pivot = instanceRectParent.pivot; Canvas dummyCanvas = dummyParent.AddComponent<Canvas>(); Canvas instanceCanvas = openedFromInstanceRoot.GetComponentInParent<Canvas>(); if (instanceCanvas != null) { dummyCanvas.sortingOrder = instanceCanvas.sortingOrder; dummyCanvas.referencePixelsPerUnit = instanceCanvas.referencePixelsPerUnit; dummyCanvas.stagePriority = (byte)stagePriority; dummyCanvas.sortingLayerID = instanceCanvas.sortingLayerID; } } m_PrefabContentsRoot.transform.SetParent(dummyParent.transform, false); } } } else { // Invalid setup CleanupBeforeClosing(); } return isValid; } // Returns true if opened successfully (this method should only be called from the StageNavigationManager) protected internal override bool OnOpenStage() { if (!isCurrentStage) { Debug.LogError("Only opening the current PrefabStage is supported. Please report a bug"); return false; } bool success = OpenStage(); if (success) { var guid = AssetDatabase.AssetPathToGUID(m_PrefabAssetPath); m_InitialFileHash = AssetDatabase.GetSourceAssetFileHash(guid); if (!FileUtil.ReadFileContentBinary(assetPath, out m_InitialFileContent, out string errorMessage)) Debug.LogError($"No undo will be registered for {m_PrefabContentsRoot.name}. \nError: {errorMessage}"); } return success; } bool OpenStage() { bool reloading = scene.IsValid(); if (reloading) { CleanupBeforeReloading(); } if (LoadStage()) { if (mode == Mode.InContext) { RecordPatchedPropertiesForContent(); ApplyPatchedPropertiesToContent(); } prefabStageOpened?.Invoke(this); // Update environment scene objects after the 'prefabStageOpened' user callback so we can ensure: correct hideflags and // that our prefab root is not under a prefab instance (which would mark it as an added object). // Note: The user can have reparented and created new GameObjects in the environment scene during this callback. EnsureParentOfPrefabRootIsUnpacked(); UpdateEnvironmentHideFlags(); UpdateLastPrefabSourceFileHashIfNeeded(); var sceneHierarchyWindows = SceneHierarchyWindow.GetAllSceneHierarchyWindows(); foreach (SceneHierarchyWindow sceneHierarchyWindow in sceneHierarchyWindows) sceneHierarchyWindow.FrameObject(prefabContentsRoot.GetInstanceID(), false); return true; } return false; } protected override void OnCloseStage() { if (isValid) prefabStageClosing?.Invoke(this); var initialFileContent = m_InitialFileContent; var path = m_PrefabAssetPath; var guid = AssetDatabase.AssetPathToGUID(m_PrefabAssetPath); var currentPrefabSourceFileHash = AssetDatabase.GetSourceAssetFileHash(guid); CleanupBeforeClosing(); if (initialFileContent?.Length > 0 && currentPrefabSourceFileHash != m_InitialFileHash) { if (FileUtil.ReadFileContentBinary(path, out byte[] newFileContent, out string errorMessage)) Undo.RegisterFileChangeUndo(AssetDatabase.GUIDFromAssetPath(path), initialFileContent, newFileContent); else Debug.LogError($"No undo will be registered for {m_PrefabContentsRoot.name}. \nError: {errorMessage}"); } } protected internal override void OnReturnToStage() { if (m_NeedsReloadingWhenReturningToStage) { m_NeedsReloadingWhenReturningToStage = false; if (m_Mode == Mode.InContext && m_OpenedFromInstanceObject == null) { // By clearing the contents root this stage becomes invalid which // will be handled the StageNavigationManager by returning to the // main stage m_PrefabContentsRoot = null; return; } ReloadStage(); } } internal bool HasPatchedPropertyModificationsFor(UnityEngine.Object obj, string partialPropertyName) { if (m_PatchedProperties == null) return false; foreach (var patchedProperty in m_PatchedProperties) { if (patchedProperty.targetInContent == obj && patchedProperty.modification.propertyPath.Contains(partialPropertyName)) return true; } return false; } internal bool ContainsTransformPrefabPropertyPatchingFor(GameObject[] gameObjects, string partialPropertyName) { if (gameObjects == null || gameObjects.Length == 0 || m_PatchedProperties == null) return false; for (int i = 0; i < gameObjects.Length; i++) if (HasPatchedPropertyModificationsFor(gameObjects[i].transform, partialPropertyName)) return true; return false; } void RecordPatchedPropertiesForContent() { m_PatchedProperties = new List<PatchedProperty>(); if (openedFromInstanceRoot == null) return; if (PrefabUtility.GetPrefabInstanceStatus(openedFromInstanceRoot) != PrefabInstanceStatus.Connected) return; Dictionary<ulong, UnityEngine.Object> contentObjectsFromFileID = new Dictionary<ulong, UnityEngine.Object>(); Dictionary<ulong, Transform> instanceTransformsFromFileID = new Dictionary<ulong, Transform>(); TransformVisitor visitor = new TransformVisitor(); visitor.VisitAll(prefabContentsRoot.transform, (transform, dict) => { contentObjectsFromFileID[Unsupported.GetOrGenerateFileIDHint(transform.gameObject)] = transform.gameObject; Component[] components = transform.GetComponents<Component>(); for (int i = components.Length - 1; i >= 0; i--) { if (components[i] == null) continue; contentObjectsFromFileID[Unsupported.GetOrGenerateFileIDHint(components[i])] = components[i]; } }, null); visitor.VisitAndAllowEarlyOut(openedFromInstanceRoot.transform, (transform, dict) => { // If the GameObject is not hidden in the scene, it's not part of the Prefab instance // that we're hiding because we're opening its Asset. That means it's not an object we // should use as source for the patching of properties on the Prefab Asset content. if (!StageUtility.IsPrefabInstanceHiddenForInContextEditing(transform.gameObject)) return false; Transform assetTransform = PrefabUtility.GetCorrespondingObjectFromSourceAtPath(transform, assetPath); // Added GameObjects have no corresponding asset object if (assetTransform != null) instanceTransformsFromFileID[Unsupported.GetLocalIdentifierInFileForPersistentObject(assetTransform)] = transform; return true; }, null); // Note: openedFromInstance is not necessarily a Prefab root, as it might be a nested Prefab. var instanceAndCorrespondingObjectChain = new List<(GameObject prefabObject, PropertyModification[] mods)>(); GameObject prefabObject = openedFromInstanceRoot; int numOverrides = 0; while (AssetDatabase.GetAssetPath(prefabObject) != assetPath) { Assert.IsTrue(PrefabUtility.IsPartOfPrefabInstance(prefabObject)); PropertyModification[] mods = PrefabUtility.GetPropertyModifications(prefabObject); instanceAndCorrespondingObjectChain.Add((prefabObject, mods)); prefabObject = PrefabUtility.GetCorrespondingObjectFromSource(prefabObject); numOverrides += mods.Length; } // Patching properties is expensive therefore we disable patching when there is an excessive // amount of overrides (case 1370904) m_TemporarilyDisablePatchAllOverridenProperties = numOverrides >= k_MaxNumberOfOverridesToVisualize; bool onlyPatchRootTransform = !showOverrides; // Run through same objects, but from innermost out so outer overrides are applied last. for (int i = instanceAndCorrespondingObjectChain.Count - 1; i >= 0; i--) { prefabObject = instanceAndCorrespondingObjectChain[i].prefabObject; var mods = instanceAndCorrespondingObjectChain[i].mods; UnityEngine.Object lastTarget = null; UnityEngine.Object lastTargetInContent = null; SerializedObject lastInstanceTransformSO = null; foreach (PropertyModification mod in mods) { if (mod.target == null) continue; if (onlyPatchRootTransform && !(mod.target is Transform)) continue; UnityEngine.Object targetInContent = null; SerializedObject instanceTransformSO = null; // Optimization to avoid doing work to find matching object in Prefab contents // for a target we already saw. Performs best if modifications are sorted by target. if (mod.target == lastTarget) { targetInContent = lastTargetInContent; instanceTransformSO = lastInstanceTransformSO; } else { targetInContent = null; UnityEngine.Object targetInOpenAsset = PrefabUtility.GetCorrespondingObjectFromSourceAtPath(mod.target, assetPath); if (targetInOpenAsset != null) { ulong fileID = Unsupported.GetLocalIdentifierInFileForPersistentObject(targetInOpenAsset); contentObjectsFromFileID.TryGetValue(fileID, out targetInContent); Transform transform; if (instanceTransformsFromFileID.TryGetValue(fileID, out transform)) { instanceTransformSO = new SerializedObject(transform); } } lastTarget = mod.target; lastTargetInContent = targetInContent; lastInstanceTransformSO = instanceTransformSO; } if (targetInContent != null) { // Don't patch root name, as Prefab Mode doesn't support changing that. if (targetInContent == prefabContentsRoot && mod.propertyPath == "m_Name") continue; if (onlyPatchRootTransform && targetInContent != prefabContentsRoot.transform) continue; if (instanceTransformSO != null) { // If properties on a Prefab instance are driven, they are serialized as 0, // which means their Prefab override values will be 0 as well. // Patching over values of 0 for Prefab Mode in Context is no good, // so get the actual current value from the instance instead. PropertyModification modFromValue = instanceTransformSO.ExtractPropertyModification(mod.propertyPath); if (modFromValue != null) mod.value = modFromValue.value; } DrivenPropertyManager.TryRegisterProperty(this, targetInContent, mod.propertyPath); m_PatchedProperties.Add(new PatchedProperty() { modification = mod, targetInContent = targetInContent }); } } } // Apply patched properties from outer stage where applicable. // This is so that changes that were patched when going in Prefab Mode in Context // don't suddenly change when digging in deeper into nested Prefab or Variant bases. var stageHistory = StageNavigationManager.instance.stageHistory; int selfIndex = stageHistory.IndexOf(this); if (selfIndex >= 1) { PrefabStage previous = stageHistory[selfIndex - 1] as PrefabStage; if (previous != null && previous.mode == Mode.InContext && previous.m_PatchedProperties != null) { List<PatchedProperty> previousPatchedProperties = previous.m_PatchedProperties; UnityEngine.Object lastTarget = null; UnityEngine.Object lastTargetInContent = null; for (int i = previousPatchedProperties.Count - 1; i >= 0; i--) { PatchedProperty patch = previousPatchedProperties[i]; PropertyModification mod = patch.modification; if (mod.target == null) continue; UnityEngine.Object targetInContent = null; if (mod.target == lastTarget) { targetInContent = lastTargetInContent; } else { targetInContent = null; UnityEngine.Object targetInOpenAsset = PrefabUtility.GetCorrespondingObjectFromSourceAtPath(mod.target, assetPath); if (targetInOpenAsset != null) { ulong fileID = Unsupported.GetLocalIdentifierInFileForPersistentObject(targetInOpenAsset); contentObjectsFromFileID.TryGetValue(fileID, out targetInContent); } lastTarget = mod.target; lastTargetInContent = targetInContent; } if (targetInContent != null) { // Don't patch root name, as Prefab Mode doesn't support changing that. // Root can be a different object than it was in outer Stage, så check again here. if (targetInContent == prefabContentsRoot && mod.propertyPath == "m_Name") continue; // Root can be a different object than it was in outer Stage, så check again here. if (onlyPatchRootTransform && targetInContent != prefabContentsRoot.transform) continue; DrivenPropertyManager.TryRegisterProperty(this, targetInContent, mod.propertyPath); m_PatchedProperties.Add(new PatchedProperty() { modification = mod, targetInContent = targetInContent }); } } } } } void ApplyPatchedPropertiesToContent() { if (m_PatchedProperties.Count == 0) return; var modificationsPerTargetInContent = new Dictionary<UnityEngine.Object, List<PropertyModification>>(); UnityEngine.Object lastTargetInContent = null; int lastTargetID = 0; for (int i = m_PatchedProperties.Count - 1; i >= 0; i--) { PatchedProperty patchedProperty = m_PatchedProperties[i]; PropertyModification modification = patchedProperty.modification; UnityEngine.Object targetInContent = patchedProperty.targetInContent; // If an object was destroyed, but later recreated with undo or redo, we have to recreate the reference to it. if (targetInContent == null) { // Patched properties are grouped by targetInContent, so we can easily ensure we // only make one attempt per target just by comparing with the previous target. int targetID = targetInContent.GetInstanceID(); if (targetID == lastTargetID) targetInContent = lastTargetInContent; else targetInContent = UnityEditorInternal.InternalEditorUtility.GetObjectFromInstanceID(targetID); // Assign the struct back to the array if it worked. if (targetInContent != null) { patchedProperty.targetInContent = targetInContent; m_PatchedProperties[i] = patchedProperty; } lastTargetInContent = targetInContent; lastTargetID = targetID; } // Group modifications per target for batch apply if (targetInContent != null) { List<PropertyModification> list; if (!modificationsPerTargetInContent.TryGetValue(targetInContent, out list)) { list = new List<PropertyModification>(); modificationsPerTargetInContent[targetInContent] = list; } list.Add(modification); } // If GameObject.active is an override, applying the value via PropertyModification // is not sufficient to actually change active state of the object, // nor is calling AwakeFromLoad(kAnimationAwakeFromLoad) afterwards, // so explicitly set it here. GameObject targetGameObject = targetInContent as GameObject; if (targetGameObject != null && modification.propertyPath == "m_IsActive") targetGameObject.SetActive(modification.value != "0"); } // Batch apply modifications per object (to optimize for large objects, case 1370904) foreach (var kvp in modificationsPerTargetInContent) { var targetInContent = kvp.Key; var mods = kvp.Value; PropertyModification.ApplyPropertyModificationsToObject(targetInContent, mods.ToArray()); } StageUtility.CallAwakeFromLoadOnSubHierarchy(m_PrefabContentsRoot); } void UndoRedoPerformed(in UndoRedoInfo info) { if (m_Mode == Mode.InContext) { ApplyPatchedPropertiesToContent(); } } void CleanupBeforeReloading() { // Only clear state that is being reloaded but keep InContext editing state etc PrefabStageUtility.DestroyPreviewScene(scene); m_HideFlagUtility = null; } void CleanupBeforeClosing() { if (m_Mode == Mode.InContext) { SetPrefabInstanceHiddenForInContextEditing(false); } if (m_PrefabContentsRoot != null && m_PrefabContentsRoot.scene != scene) { UnityEngine.Object.DestroyImmediate(m_PrefabContentsRoot); } if (scene.IsValid()) PrefabStageUtility.DestroyPreviewScene(scene); // Automatically deletes all GameObjects in scene m_PrefabContentsRoot = null; m_OpenedFromInstanceRoot = null; m_OpenedFromInstanceObject = null; m_HideFlagUtility = null; m_PrefabAssetPath = null; m_InitialFileContent = null; m_InitialFileHash = new Hash128(); m_InitialSceneDirtyID = 0; m_StageDirtiedFired = false; m_LastSceneDirtyID = 0; m_IgnoreNextAssetImportedEventForCurrentPrefab = false; m_PrefabWasChangedOnDisk = false; } void ReloadStage() { if (SceneHierarchy.s_DebugPrefabStage) Debug.Log("RELOADING Prefab at " + m_PrefabAssetPath); if (!isCurrentStage) { Debug.LogError("Only reloading the current PrefabStage is supported. Please report a bug"); return; } var sceneHierarchyWindows = SceneHierarchyWindow.GetAllSceneHierarchyWindows(); foreach (SceneHierarchyWindow sceneHierarchyWindow in sceneHierarchyWindows) SaveHierarchyState(sceneHierarchyWindow); if (OpenStage()) { foreach (SceneView sceneView in SceneView.sceneViews) SyncSceneViewToStage(sceneView); foreach (SceneHierarchyWindow sceneHierarchyWindow in sceneHierarchyWindows) { SyncSceneHierarchyToStage(sceneHierarchyWindow); LoadHierarchyState(sceneHierarchyWindow); } prefabStageReloaded?.Invoke(this); } if (SceneHierarchy.s_DebugPrefabStage) Debug.Log("RELOADING done"); } internal override void SyncSceneViewToStage(SceneView sceneView) { // The reason we need to set customScene even though we also set overrideSceneCullingMask is // because the RenderSettings of the customScene is used to override lighting settings for this SceneView. PrefabStage prefabStage = GetContextStage() as PrefabStage; sceneView.customScene = prefabStage == null ? default(Scene) : prefabStage.scene; sceneView.customParentForNewGameObjects = prefabContentsRoot.transform; switch (mode) { case PrefabStage.Mode.InIsolation: sceneView.overrideSceneCullingMask = 0; break; case PrefabStage.Mode.InContext: sceneView.overrideSceneCullingMask = GetCombinedSceneCullingMaskForCamera(); break; default: Debug.LogError("Unhandled enum"); break; } } internal override void SyncSceneHierarchyToStage(SceneHierarchyWindow sceneHierarchyWindow) { var sceneHierarchy = sceneHierarchyWindow.sceneHierarchy; sceneHierarchy.customScenes = new[] { scene }; sceneHierarchy.customParentForNewGameObjects = prefabContentsRoot.transform; sceneHierarchy.SetCustomDragHandler(PrefabModeDraggingHandler); } protected internal override void OnFirstTimeOpenStageInSceneView(SceneView sceneView) { // Default to scene view lighting if scene itself does not have any lights if (!HasAnyActiveLights(scene)) sceneView.sceneLighting = false; // Default to not showing skybox if user did not specify a custom environment scene. if (string.IsNullOrEmpty(scene.path)) sceneView.sceneViewState.showSkybox = false; // For UI to frame properly we need to delay one full Update for the layouting to have been processed EditorApplication.update += DelayedFraming; } internal override void OnFirstTimeOpenStageInSceneHierachyWindow(SceneHierarchyWindow sceneHierarchyWindow) { var expandedIDs = new List<int>(); AddParentsBelowButIgnoreNestedPrefabsRecursive(prefabContentsRoot.transform, expandedIDs); expandedIDs.Sort(); sceneHierarchyWindow.sceneHierarchy.treeViewState.expandedIDs = expandedIDs; } void AddParentsBelowButIgnoreNestedPrefabsRecursive(Transform transform, List<int> gameObjectInstanceIDs) { gameObjectInstanceIDs.Add(transform.gameObject.GetInstanceID()); int count = transform.childCount; for (int i = 0; i < count; ++i) { var child = transform.GetChild(i); if (child.childCount > 0 && !PrefabUtility.IsAnyPrefabInstanceRoot(child.gameObject)) { AddParentsBelowButIgnoreNestedPrefabsRecursive(child, gameObjectInstanceIDs); } } } static DragAndDropVisualMode PrefabModeDraggingHandler(GameObjectTreeViewItem parentItem, GameObjectTreeViewItem targetItem, TreeViewDragging.DropPosition dropPos, bool perform) { var prefabStage = StageNavigationManager.instance.currentStage as PrefabStage; if (prefabStage == null) throw new InvalidOperationException("PrefabModeDraggingHandler should only be called in Prefab Mode"); // Disallow dropping as sibling to the prefab instance root (In Prefab Mode we only want to show one root). if (parentItem != null && parentItem.parent == null && dropPos != TreeViewDragging.DropPosition.Upon) return DragAndDropVisualMode.Rejected; // Disallow dragging scenes into the hierarchy when it is in Prefab Mode (we do not support multi-scenes for prefabs yet) foreach (var dragged in DragAndDrop.objectReferences) { if (dragged is SceneAsset) return DragAndDropVisualMode.Rejected; } // Check for cyclic nesting (only on perform since it is an expensive operation) if (perform) { var prefabAssetThatIsAddedTo = AssetDatabase.LoadMainAssetAtPath(prefabStage.assetPath); if (prefabAssetThatIsAddedTo is BrokenPrefabAsset) return DragAndDropVisualMode.None; foreach (var dragged in DragAndDrop.objectReferences) { if (dragged is GameObject && EditorUtility.IsPersistent(dragged)) { var prefabAssetThatWillBeAdded = dragged; if (PrefabUtility.CheckIfAddingPrefabWouldResultInCyclicNesting(prefabAssetThatIsAddedTo, prefabAssetThatWillBeAdded)) { PrefabUtility.ShowCyclicNestingWarningDialog(); return DragAndDropVisualMode.Rejected; } } } } return DragAndDropVisualMode.None; } static bool HasAnyActiveLights(Scene scene) { foreach (var gameObject in scene.GetRootGameObjects()) { if (gameObject.GetComponentsInChildren<Light>(false).Length > 0) return true; } return false; } int m_DelayCounter; void DelayedFraming() { if (m_DelayCounter++ == 1) { EditorApplication.update -= DelayedFraming; m_DelayCounter = 0; if(!IsPartOfPrefabContents(Selection.activeGameObject)) Selection.activeGameObject = prefabContentsRoot; // Frame the Prefab foreach (SceneView sceneView in SceneView.sceneViews) sceneView.FrameSelected(false, true); } } internal override string GetErrorMessage() { if (m_PrefabContentsRoot == null) return L10n.Tr("Error: The Prefab contents root has been deleted.\n\nPrefab: ") + m_PrefabAssetPath; if (m_PrefabContentsRoot.scene != scene) return L10n.Tr("Error: The root GameObject of the opened Prefab has been moved out of the Prefab Stage scene by a script.\n\nPrefab: ") + m_PrefabAssetPath; return null; } protected internal override GUIContent CreateHeaderContent() { var label = Path.GetFileNameWithoutExtension(m_PrefabAssetPath); var icon = AssetDatabase.GetCachedIcon(m_PrefabAssetPath); return new GUIContent(label, icon); } internal override BreadcrumbBar.Item CreateBreadcrumbItem() { GUIContent content = CreateHeaderContent(); var history = StageNavigationManager.instance.stageHistory; bool isLastCrumb = this == history.Last(); var style = isLastCrumb ? BreadcrumbBar.DefaultStyles.labelBold : BreadcrumbBar.DefaultStyles.label; var separatorstyle = mode == Mode.InIsolation ? BreadcrumbBar.SeparatorStyle.Line : BreadcrumbBar.SeparatorStyle.Arrow; if (isAssetMissing) { style = isLastCrumb ? BreadcrumbBar.DefaultStyles.labelBoldMissing : BreadcrumbBar.DefaultStyles.labelMissing; content.tooltip = L10n.Tr("Prefab Asset has been deleted."); } return new BreadcrumbBar.Item { content = content, guistyle = style, userdata = this, separatorstyle = separatorstyle }; } internal override void Tick() { if (!isValid) return; if (hasUnsavedChanges) { m_AnalyticsDidUserModify = true; if (!m_StageDirtiedFired) { m_StageDirtiedFired = true; if (prefabStageDirtied != null) prefabStageDirtied(this); } } UpdateEnvironmentHideFlagsIfNeeded(); HandleAutoSave(); HandlePrefabChangedOnDisk(); DetectSceneDirtinessChange(); DetectPrefabFileIconChange(); DetectPrefabRootTransformChange(); } void DetectPrefabRootTransformChange() { var currentTransform = m_PrefabContentsRoot.transform; if (currentTransform != m_LastRootTransform) { foreach (SceneView sceneView in SceneView.sceneViews) SyncSceneViewToStage(sceneView); var sceneHierarchyWindows = SceneHierarchyWindow.GetAllSceneHierarchyWindows(); foreach (SceneHierarchyWindow sceneHierarchyWindow in sceneHierarchyWindows) SyncSceneHierarchyToStage(sceneHierarchyWindow); } m_LastRootTransform = currentTransform; } void DetectPrefabFileIconChange() { var icon = DeterminePrefabFileIconFromInstanceRootGameObject(); if (icon != m_PrefabFileIcon) { m_PrefabFileIcon = icon; SceneView.RebuildBreadcrumbBarInAll(); SceneHierarchyWindow.RebuildStageHeaderInAll(); } } void DetectSceneDirtinessChange() { if (scene.dirtyID != m_LastSceneDirtyID) { // We want to make sure that all the new sortable components (e.g, canvas, renderer) being added have // the correct StagePriority assigned to them. Otherwise they won't be sorted accordingly when in // context/isolation mode. if (PrefabStageUtility.IsUIPrefab(m_PrefabAssetPath)) UpdateSortableComponentsWithStagePriority(StageNavigationManager.instance.stageHistory.IndexOf(this)); SceneView.RepaintAll(); } m_LastSceneDirtyID = scene.dirtyID; } void UpdateEnvironmentHideFlagsIfNeeded() { if (m_HideFlagUtility == null) m_HideFlagUtility = new HideFlagUtility(scene, m_PrefabContentsRoot); m_HideFlagUtility.UpdateEnvironmentHideFlagsIfNeeded(); } void UpdateEnvironmentHideFlags() { if (m_HideFlagUtility == null) m_HideFlagUtility = new HideFlagUtility(scene, m_PrefabContentsRoot); m_HideFlagUtility.UpdateEnvironmentHideFlags(); } void EnsureParentOfPrefabRootIsUnpacked() { var parent = m_PrefabContentsRoot.transform.parent; if (parent != null) { if (PrefabUtility.IsPartOfPrefabInstance(parent)) { var outerMostPrefabInstance = PrefabUtility.GetOutermostPrefabInstanceRoot(parent); PrefabUtility.UnpackPrefabInstance(outerMostPrefabInstance, PrefabUnpackMode.Completely, InteractionMode.AutomatedAction); } } } bool isTextFieldCaretShowing { get { return EditorGUI.IsEditingTextField() && !EditorGUIUtility.textFieldHasSelection; } } bool readyToAutoSave { get { return m_PrefabContentsRoot != null && hasUnsavedChanges && GUIUtility.hotControl == 0 && !isTextFieldCaretShowing && !EditorApplication.isCompiling; } } void HandleAutoSave() { if (IsPrefabInImmutableFolder()) return; if (autoSave && readyToAutoSave) { AutoSave(); } } void HandlePrefabChangedOnDisk() { if (m_PrefabWasChangedOnDisk) { m_PrefabWasChangedOnDisk = false; if (!isCurrentStage) { return; } if (!File.Exists(m_PrefabAssetPath)) return; if (hasUnsavedChanges) { var title = L10n.Tr("Prefab Has Been Changed on Disk"); var message = string.Format(L10n.Tr("You have modifications to the Prefab '{0}' that was changed on disk while in Prefab Mode. Do you want to keep your changes or reload the Prefab and discard your changes?"), m_PrefabContentsRoot.name); bool keepChanges = EditorUtility.DisplayDialog(title, message, L10n.Tr("Keep Changes"), L10n.Tr("Discard Changes")); if (!keepChanges) ReloadStage(); } else { ReloadStage(); } } } public void ClearDirtiness() { EditorSceneManager.ClearSceneDirtiness(scene); m_InitialSceneDirtyID = scene.dirtyID; m_StageDirtiedFired = false; } bool PromptIfMissingVariantParentForVariant() { if (PrefabUtility.IsPrefabAssetMissing(m_PrefabContentsRoot)) { string title = L10n.Tr("Saving Variant Failed"); string message = L10n.Tr("Can't save the Prefab Variant when its parent Prefab is missing. You have to unpack the root GameObject or recover the missing parent Prefab in order to save the Prefab Variant"); if (autoSave) message += L10n.Tr("\n\nAuto Save has been temporarily disabled."); EditorUtility.DisplayDialog(title, message, L10n.Tr("OK")); m_TemporarilyDisableAutoSave = true; return true; } return false; } // Returns true if we can continue. Either the user saved changes or user discarded changes. Returns false if the user cancelled switching stage. internal override bool AskUserToSaveModifiedStageBeforeSwitchingStage() { // Allow user to save any unsaved changes only after recompiling have finished so any new scripts can be // saved properly to the Prefab file (but only if the stage is valid) if (isValid) { if (EditorApplication.isCompiling && hasUnsavedChanges) { SceneView.ShowNotification("Compiling must finish before you can exit Prefab Mode"); SceneView.RepaintAll(); return false; } bool continueDestroyingScene = AskUserToSaveDirtySceneBeforeDestroyingScene(); if (!continueDestroyingScene) return false; } return true; } // Returns true if saved succesfully (internal so we can use it in Tests) internal bool SavePrefab() { if (!isValid) return false; m_AnalyticsDidUserSave = true; m_AnalyticsDidUserModify = true; if (SceneHierarchy.s_DebugPrefabStage) Debug.Log("SAVE PREFAB"); if (prefabSaving != null) prefabSaving(m_PrefabContentsRoot); var startTime = EditorApplication.timeSinceStartup; if (PromptIfMissingVariantParentForVariant()) return false; // The user can have deleted required folders var folder = Path.GetDirectoryName(m_PrefabAssetPath); if (!Directory.Exists(folder)) Directory.CreateDirectory(folder); bool savedSuccesfully; PrefabUtility.SaveAsPrefabAsset(m_PrefabContentsRoot, m_PrefabAssetPath, out savedSuccesfully); m_LastSavingDuration = (float)(EditorApplication.timeSinceStartup - startTime); if (savedSuccesfully) { ClearDirtiness(); if (prefabSaved != null) prefabSaved(m_PrefabContentsRoot); // After saving the Prefab any Prefab instances in the environment scene // that are dependent on the saved Prefab will have lost their hideflags // so here we set them again. UpdateEnvironmentHideFlags(); } else { string title = L10n.Tr("Saving Failed"); string message = L10n.Tr("Saving failed. Check the Console window to get more insight into what needs to be fixed."); if (autoSave) message += L10n.Tr("\n\nAuto Save has been temporarily disabled."); EditorUtility.DisplayDialog(title, message, L10n.Tr("OK")); m_TemporarilyDisableAutoSave = true; m_IgnoreNextAssetImportedEventForCurrentPrefab = false; } if (SceneHierarchy.s_DebugPrefabStage) Debug.Log("SAVE PREFAB ended"); showingSavingLabel = false; return savedSuccesfully; } internal bool SaveAsNew(string newPath, bool asCopy) { if (!isValid) return false; if (newPath == m_PrefabAssetPath) { throw new ArgumentException("Cannot save as new prefab using the same path"); } if (asCopy) { // Keep current open prefab and save copy at newPath string oldName = m_PrefabContentsRoot.name; m_PrefabContentsRoot.name = Path.GetFileNameWithoutExtension(newPath); PrefabUtility.SaveAsPrefabAsset(m_PrefabContentsRoot, newPath); m_PrefabContentsRoot.name = oldName; } else { // Change the current open prefab and save m_PrefabContentsRoot.name = Path.GetFileNameWithoutExtension(newPath); m_PrefabAssetPath = newPath; CachePrefabFolderInfo(); ClearDirtiness(); PrefabUtility.SaveAsPrefabAsset(m_PrefabContentsRoot, newPath); if (prefabStageSavedAsNewPrefab != null) prefabStageSavedAsNewPrefab(this); } return true; } internal override bool SaveAsNew() { Assert.IsTrue(m_PrefabContentsRoot != null, "We should have a valid m_PrefabContentsRoot when saving to prefab asset"); string directoryOfCurrentPrefab = Path.GetDirectoryName(m_PrefabAssetPath); string nameOfCurrentPrefab = Path.GetFileNameWithoutExtension(m_PrefabAssetPath); string relativePath; while (true) { relativePath = EditorUtility.SaveFilePanelInProject("Save Prefab", nameOfCurrentPrefab + " Copy", "prefab", "", directoryOfCurrentPrefab); // Cancel pressed if (string.IsNullOrEmpty(relativePath)) return false; if (relativePath == m_PrefabAssetPath) { if (EditorUtility.DisplayDialog(L10n.Tr("Save Prefab has failed"), L10n.Tr("Overwriting the same path as another open prefab is not allowed."), L10n.Tr("Try Again"), L10n.Tr("Cancel"))) continue; return false; } break; } return SaveAsNew(relativePath, false); } void PerformDelayedAutoSave() { EditorApplication.update -= PerformDelayedAutoSave; Save(); } void AutoSave() { showingSavingLabel = m_LastSavingDuration > kDurationBeforeShowingSavingBadge; if (showingSavingLabel) { // Save delayed if we want to show the save badge while saving. foreach (SceneView sceneView in SceneView.sceneViews) sceneView.Repaint(); EditorApplication.update += PerformDelayedAutoSave; } else { // Save directly if we don't want to show the saving badge Save(); } } // Returns true if prefab was saved. internal override bool Save() { if (m_PrefabContentsRoot == null) { Debug.LogError("We should have a valid m_PrefabContentsRoot when saving to prefab asset"); return false; } if (!PrefabUtility.PromptAndCheckoutPrefabIfNeeded(m_PrefabAssetPath, PrefabUtility.SaveVerb.Save)) { // If user doesn't want to check out prefab asset, or it cannot be, // it doesn't make sense to keep auto save on. m_TemporarilyDisableAutoSave = true; return false; } bool showCancelButton = !autoSave; if (!CheckRenamedPrefabRootWhenSaving(showCancelButton)) return false; return SavePrefab(); } internal override void DiscardChanges() { if (hasUnsavedChanges) ReloadStage(); } // Returns true if we should continue saving bool CheckRenamedPrefabRootWhenSaving(bool showCancelButton) { var prefabFilename = GetPrefabFileName(); if (m_PrefabContentsRoot.name != prefabFilename) { string folder = Path.GetDirectoryName(m_PrefabAssetPath); string extension = Path.GetExtension(m_PrefabAssetPath); string newPath = Path.Combine(folder, m_PrefabContentsRoot.name + extension); string errorMsg = AssetDatabase.ValidateMoveAsset(m_PrefabAssetPath, newPath); if (!string.IsNullOrEmpty(errorMsg)) { var t = L10n.Tr("Rename Prefab File Not Possible"); var m = string.Format(L10n.Tr("The Prefab file name must match the Prefab root GameObject name but there is already a Prefab asset with the file name '{0}' in the same folder. The root GameObject name will therefore be changed back to match the Prefab file name when saving."), m_PrefabContentsRoot.name); if (showCancelButton) { if (EditorUtility.DisplayDialog(t, m, L10n.Tr("OK"), L10n.Tr("Cancel Save"))) { RenameInstanceRootToMatchPrefabFile(); return true; } else { return false; // Cancel saving } } EditorUtility.DisplayDialog(t, m, L10n.Tr("OK")); RenameInstanceRootToMatchPrefabFile(); return true; } var title = L10n.Tr("Rename Prefab File?"); var message = string.Format(L10n.Tr("The Prefab file name must match the Prefab root GameObject name. Do you want to rename the file to '{0}' or use the old name '{1}' for both?"), m_PrefabContentsRoot.name, prefabFilename); if (showCancelButton) { int option = EditorUtility.DisplayDialogComplex(title, message, L10n.Tr("Rename File"), L10n.Tr("Use Old Name"), L10n.Tr("Cancel Save")); switch (option) { // Rename prefab file case 0: RenamePrefabFileToMatchPrefabInstanceName(); return true; // Rename the root GameObject to file name case 1: RenameInstanceRootToMatchPrefabFile(); return true; // Cancel saving case 2: return false; } } else { bool renameFile = EditorUtility.DisplayDialog(title, message, L10n.Tr("Rename File"), L10n.Tr("Use Old Name")); if (renameFile) RenamePrefabFileToMatchPrefabInstanceName(); else RenameInstanceRootToMatchPrefabFile(); return true; } } return true; } internal void RenameInstanceRootToMatchPrefabFile() { m_PrefabContentsRoot.name = GetPrefabFileName(); } internal void RenamePrefabFileToMatchPrefabInstanceName() { string newPrefabFileName = m_PrefabContentsRoot.name; if (SceneHierarchy.s_DebugPrefabStage) Debug.LogFormat("RENAME Prefab Asset: '{0} to '{1}'", m_PrefabAssetPath, newPrefabFileName); // If we don't ignore the next import event we will reload the current prefab and hereby loosing the current selection (inspector goes blank) // Since we have made the change ourselves (rename) we don't need to reload our instances. m_IgnoreNextAssetImportedEventForCurrentPrefab = true; string errorMsg = AssetDatabase.RenameAsset(m_PrefabAssetPath, newPrefabFileName); if (!string.IsNullOrEmpty(errorMsg)) Debug.LogError(errorMsg); if (SceneHierarchy.s_DebugPrefabStage) Debug.Log("RENAME done"); } // Returns false if the user clicked Cancel to save otherwise returns true (ok to continue to destroying scene) internal bool AskUserToSaveDirtySceneBeforeDestroyingScene() { if (!hasUnsavedChanges || m_PrefabContentsRoot == null) return true; // no changes to save or no root to save; continue if (IsPrefabInImmutableFolder()) { var header = L10n.Tr("Immutable Prefab"); var message = L10n.Tr("The Prefab was changed in Prefab Mode but is in a read-only folder so the changes cannot be saved."); var buttonOK = L10n.Tr("OK"); var buttonCancel = L10n.Tr("Cancel"); if (EditorUtility.DisplayDialog(header, message, buttonOK, buttonCancel)) return true; // OK: continue to close stage return false; // Cancel closing stage } // Rare condition. Prefab should have already been saved if auto-save is enabled, // but it's possible it hasn't, so save when exiting just in case. if (autoSave) return Save(); int dialogResult = EditorUtility.DisplayDialogComplex("Prefab Has Been Modified", "Do you want to save the changes you made in Prefab Mode? Your changes will be lost if you don't save them.", "Save", "Discard Changes", "Cancel"); switch (dialogResult) { case 0: return Save(); // save changes and continue current operation case 1: // The user have accepted to discard changes if (hasUnsavedChanges && !m_IsAssetMissing) ReloadStage(); return true; // continue current operation case 2: return false; // cancel and discontinue current operation default: throw new InvalidOperationException("Unhandled dialog result " + dialogResult); } } internal void OnSavingPrefab(GameObject gameObject, string path) { // We care about 'irrelevant prefab paths' since the 'irrelevant' prefab could be a nested prefab to the // current prefab being edited (this would result in our current prefab being reimported due to the dependency). // For nested prefabs the prefab merging code will take care of updating the current GameObjects loaded // so in this case do not reload the prefab even though the path shows up in AssetsChangedOnHDD event. bool savedBySelf = gameObject == m_PrefabContentsRoot; bool irrelevantPath = path != m_PrefabAssetPath; if (savedBySelf || irrelevantPath) { m_IgnoreNextAssetImportedEventForCurrentPrefab = true; } } bool UpdateLastPrefabSourceFileHashIfNeeded() { var guid = AssetDatabase.AssetPathToGUID(m_PrefabAssetPath); var prefabSourceFileHash = AssetDatabase.GetSourceAssetFileHash(guid); if (m_LastPrefabSourceFileHash != prefabSourceFileHash) { m_LastPrefabSourceFileHash = prefabSourceFileHash; return true; } return false; } internal void OnAssetsChangedOnHDD(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { if (SceneHierarchy.s_DebugPrefabStage) Debug.LogFormat("AssetDatabase Event: Current Prefab: {0}, *ImportedAssets: {1}, *DeletedAssets: {2}, *MovedAssets: {3}, *MovedFromAssetPaths: {4}", m_PrefabAssetPath, DebugUtils.ListToString(importedAssets), DebugUtils.ListToString(deletedAssets), DebugUtils.ListToString(movedAssets), DebugUtils.ListToString(movedFromAssetPaths)); // Prefab was moved (update cached path) for (int i = 0; i < movedFromAssetPaths.Length; ++i) { if (movedFromAssetPaths[i].Equals(m_PrefabAssetPath, StringComparison.OrdinalIgnoreCase)) { m_PrefabAssetPath = movedAssets[i]; break; } } for (int i = 0; i < deletedAssets.Length; ++i) { if (deletedAssets[i] == m_PrefabAssetPath) { m_IsAssetMissing = true; break; } } // Detect if our Prefab was modified on HDD outside Prefab Mode (in that case we should ask the user if he wants to reload it) for (int i = 0; i < importedAssets.Length; ++i) { if (importedAssets[i] == m_PrefabAssetPath) { m_IsAssetMissing = false; if (UpdateLastPrefabSourceFileHashIfNeeded() && !m_IgnoreNextAssetImportedEventForCurrentPrefab) { if (isCurrentStage) { m_PrefabWasChangedOnDisk = true; } else { m_NeedsReloadingWhenReturningToStage = true; } } // Reset the ignore flag when we finally have imported the saved prefab (We set this flag when saving the Prefab from Prefab Mode) // Note we can get multiple OnAssetsChangedOnHDD events before the Prefab imported event if e.g folders of the Prefab path needs to be reimported first. m_IgnoreNextAssetImportedEventForCurrentPrefab = false; break; } } } // This method is not called from the SceneView if the SceneView does not support stage handling internal override void OnPreSceneViewRender(SceneView sceneView) { StaticOcclusionCullingVisualization.showOcclusionCulling = false; if (mode != Mode.InContext) return; StageUtility.EnableHidingForInContextEditingInSceneView(true); StageUtility.SetFocusedScene(scene); StageUtility.SetFocusedSceneContextRenderMode(StageNavigationManager.instance.contextRenderMode); sceneView.SetSceneViewFilteringForStages(StageNavigationManager.instance.contextRenderMode == StageUtility.ContextRenderMode.GreyedOut); } // This method is not called from the SceneView if the SceneView does not support stage handling internal override void OnPostSceneViewRender(SceneView sceneView) { StaticOcclusionCullingVisualization.showOcclusionCulling = OcclusionCullingWindow.isVisible; if (mode != Mode.InContext) return; StageUtility.EnableHidingForInContextEditingInSceneView(false); StageUtility.SetFocusedScene(default(Scene)); StageUtility.SetFocusedSceneContextRenderMode(StageUtility.ContextRenderMode.Normal); sceneView.SetSceneViewFilteringForStages(false); } Texture2D DeterminePrefabFileIconFromInstanceRootGameObject() { bool partOfInstance = PrefabUtility.IsPartOfNonAssetPrefabInstance(prefabContentsRoot); if (partOfInstance) return Icons.prefabVariantIcon; return Icons.prefabIcon; } internal override void OnControlsGUI(SceneView sceneView) { GUILayout.Space(15); if (mode == Mode.InContext) { InContextModeSelector(sceneView); GUILayout.Space(15); VisualizeOverridesToggle(); GUILayout.Space(15); } SaveButtons(sceneView); } internal override void PlaceGameObjectInStage(GameObject rootGameObject) { if (this != null && isValid) rootGameObject.transform.SetParent(prefabContentsRoot.transform, true); } 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 PrefabStageHierarchyState(); state.SaveStateFromHierarchy(hierarchyWindow, this); s_StateCache.SetState(key, state); } PrefabStageHierarchyState 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); } void InitContextRenderModeSelector() { if (m_Mode != Mode.InContext) return; List<ExposablePopupMenu.ItemData> buttonData = new List<ExposablePopupMenu.ItemData>(); GUIStyle onStyle = Styles.exposablePopupItem; GUIStyle offStyle = Styles.exposablePopupItem; var currentState = StageNavigationManager.instance.contextRenderMode; for (int i = 0; i < Styles.contextRenderModeTexts.Length; ++i) { bool on = currentState == Styles.contextRenderModeOptions[i]; buttonData.Add(new ExposablePopupMenu.ItemData(Styles.contextRenderModeTexts[i], on ? onStyle : offStyle, on, true, Styles.contextRenderModeOptions[i])); } GUIContent popupButtonContent = Styles.contextRenderModeTexts[(int)currentState]; ExposablePopupMenu.PopupButtonData popListData = new ExposablePopupMenu.PopupButtonData(popupButtonContent, Styles.exposablePopup); s_ContextRenderModeSelector.Init(Styles.contextLabel, buttonData, 4f, 50, popListData, ContextRenderModeClickedCallback); s_ContextRenderModeSelector.rightAligned = true; } void ContextRenderModeClickedCallback(ExposablePopupMenu.ItemData itemClicked) { // Behave like radio buttons: a button that is on cannot be turned off if (!itemClicked.m_On) { var selectedMode = (StageUtility.ContextRenderMode)itemClicked.m_UserData; StageNavigationManager.instance.contextRenderMode = selectedMode; // Ensure to recalc widths and selected texts InitContextRenderModeSelector(); } } void InContextModeSelector(SceneView sceneView) { if (s_ContextRenderModeSelector == null) { s_ContextRenderModeSelector = new ExposablePopupMenu(); InitContextRenderModeSelector(); } EditorGUI.BeginChangeCheck(); var rect = GUILayoutUtility.GetRect(s_ContextRenderModeSelector.widthOfPopupAndLabel, s_ContextRenderModeSelector.widthOfButtonsAndLabel, 0, 22); s_ContextRenderModeSelector.OnGUI(rect); if (EditorGUI.EndChangeCheck()) { SceneView.RepaintAll(); } } internal bool showOverrides { get { return s_PatchAllOverriddenProperties.value && !m_TemporarilyDisablePatchAllOverridenProperties; } set { if (m_TemporarilyDisablePatchAllOverridenProperties) return; if (value == s_PatchAllOverriddenProperties.value) return; s_PatchAllOverriddenProperties.value = value; var stageHistory = StageNavigationManager.instance.stageHistory; foreach (var stage in stageHistory) { PrefabStage prefabStage = stage as PrefabStage; if (prefabStage != null) prefabStage.RefreshPatchedProperties(); } PropertyEditor.ClearAndRebuildAll(); } } void RefreshPatchedProperties() { DrivenPropertyManager.UnregisterProperties(this); RecordPatchedPropertiesForContent(); ApplyPatchedPropertiesToContent(); } void VisualizeOverridesToggle() { using (new EditorGUI.DisabledScope(!IsOpenedFromInstanceObjectValid() || m_TemporarilyDisablePatchAllOverridenProperties)) { EditorGUI.BeginChangeCheck(); var content = m_TemporarilyDisablePatchAllOverridenProperties ? Styles.showOverridesLabelWithTooManyOverridesTooltip : Styles.showOverridesLabel; bool patchAll = GUILayout.Toggle(showOverrides, content); if (EditorGUI.EndChangeCheck()) showOverrides = patchAll; } } void CachePrefabFolderInfo() { bool isRootFolder; m_IsPrefabInValidAssetFolder = AssetDatabase.TryGetAssetFolderInfo(m_PrefabAssetPath, out isRootFolder, out m_IsPrefabInImmutableFolder); } bool IsPrefabInImmutableFolder() { return !m_IsPrefabInValidAssetFolder || m_IsPrefabInImmutableFolder; } void SaveButtons(SceneView sceneView) { if (IsPrefabInImmutableFolder()) { GUILayout.Label(Styles.immutablePrefabContent, EditorStyles.boldLabel); return; } StatusQueryOptions opts = EditorUserSettings.allowAsyncStatusUpdate ? StatusQueryOptions.UseCachedAsync : StatusQueryOptions.UseCachedIfPossible; bool openForEdit = AssetDatabase.IsOpenForEdit(assetPath, opts); if (showingSavingLabel) { GUILayout.Label(Styles.autoSavingBadgeContent, Styles.savingBadge); GUILayout.Space(4); } if (!autoSave) { using (new EditorGUI.DisabledScope((!openForEdit || !hasUnsavedChanges) && !isAssetMissing)) { if (GUILayout.Button(Styles.saveButtonContent, Styles.button)) Save(); } } if (EditorSettings.prefabModeAllowAutoSave) { bool autoSaveForScene = autoSave; EditorGUI.BeginChangeCheck(); autoSaveForScene = GUILayout.Toggle(autoSaveForScene, Styles.autoSaveGUIContent, Styles.saveToggle); if (EditorGUI.EndChangeCheck()) autoSave = autoSaveForScene; } if (!openForEdit) { if (GUILayout.Button(Styles.checkoutButtonContent, Styles.button)) AssetDatabase.MakeEditable(assetPath); } } internal const HideFlags kVisibleEnvironmentObjectHideFlags = HideFlags.DontSave | HideFlags.NotEditable; internal const HideFlags kNotVisibleEnvironmentObjectHideFlags = HideFlags.DontSave | HideFlags.NotEditable | HideFlags.HideInHierarchy; class HideFlagUtility { int m_LastSceneDirtyID = -1; List<GameObject> m_Roots = new List<GameObject>(); GameObject m_PrefabInstanceRoot; Scene m_Scene; public HideFlagUtility(Scene scene, GameObject prefabInstanceRoot) { m_Scene = scene; m_PrefabInstanceRoot = prefabInstanceRoot; } public void UpdateEnvironmentHideFlagsIfNeeded() { if (m_LastSceneDirtyID == m_Scene.dirtyID) return; m_LastSceneDirtyID = m_Scene.dirtyID; UpdateEnvironmentHideFlags(); } public void UpdateEnvironmentHideFlags() { ValidatePreviewSceneConsistency(); // We use hideflags to hide all environment objects (and make them non-editable since the user cannot save them) GameObject rootOfPrefabInstance = GetRoot(m_PrefabInstanceRoot); // Set all environment root hierarchies m_Scene.GetRootGameObjects(m_Roots); foreach (GameObject go in m_Roots) { if (go == rootOfPrefabInstance) continue; SetHideFlagsRecursively(go.transform, kNotVisibleEnvironmentObjectHideFlags); } if (rootOfPrefabInstance != m_PrefabInstanceRoot) { // Our prefab instance root might be a child of an environment object. Here we set those environment objects hidden (leaving the root prefab instance unchanged) SetHideFlagsRecursivelyWithIgnore(rootOfPrefabInstance.transform, m_PrefabInstanceRoot.transform, kNotVisibleEnvironmentObjectHideFlags); // And finally we ensure the ancestors of the prefab root are visible Transform current = m_PrefabInstanceRoot.transform.parent; while (current != null) { if (current.hideFlags != kVisibleEnvironmentObjectHideFlags) current.gameObject.hideFlags = kVisibleEnvironmentObjectHideFlags; current = current.parent; } } } static GameObject GetRoot(GameObject go) { Transform current = go.transform; while (true) { if (current.parent == null) return current.gameObject; current = current.parent; } } static void SetHideFlagsRecursively(Transform transform, HideFlags hideFlags) { if (transform.hideFlags != hideFlags) transform.gameObject.hideFlags = hideFlags; for (int i = 0; i < transform.childCount; i++) SetHideFlagsRecursively(transform.GetChild(i), hideFlags); } static void SetHideFlagsRecursivelyWithIgnore(Transform transform, Transform ignoreThisTransform, HideFlags hideFlags) { if (transform == ignoreThisTransform) return; if (transform.gameObject.hideFlags != hideFlags) transform.gameObject.hideFlags = hideFlags; // GameObject also sets all components so check before setting for (int i = 0; i < transform.childCount; i++) SetHideFlagsRecursivelyWithIgnore(transform.GetChild(i), ignoreThisTransform, hideFlags); } void ValidatePreviewSceneConsistency() { if (!ValidatePreviewSceneState.ValidatePreviewSceneObjectState(m_PrefabInstanceRoot)) { ValidatePreviewSceneState.LogErrors(); } } } static class ValidatePreviewSceneState { static List<string> m_Errors = new List<string>(); public static void LogErrors() { string combinedErrors = string.Join("\n", m_Errors.ToArray()); Debug.LogError("Inconsistent preview object state:\n" + combinedErrors); } static public bool ValidatePreviewSceneObjectState(GameObject root) { m_Errors.Clear(); TransformVisitor visitor = new TransformVisitor(); visitor.VisitAll(root.transform, ValidateGameObject, null); return m_Errors.Count == 0; } static void ValidateGameObject(Transform transform, object userData) { GameObject go = transform.gameObject; if (!EditorSceneManager.IsPreviewSceneObject(go)) { m_Errors.Add(" GameObject not correctly marked as PreviewScene object: " + go.name); } var components = go.GetComponents<Component>(); foreach (var c in components) { if (c == null) { // This can happen if a monobehaviour has a missing script. // In this case the check can not be made. Could be fixed // by moving the component iteration to native code. continue; } if (!EditorSceneManager.IsPreviewSceneObject(c)) m_Errors.Add(string.Format(" Component {0} not correctly marked as PreviewScene object: (GameObject: {1})", c.GetType().Name, go.name)); } } } void OnPlayModeStateChanged(PlayModeStateChange playmodeState) { if (playmodeState == PlayModeStateChange.ExitingEditMode) { bool blockPrefabModeInPlaymode = PrefabStageUtility.CheckIfAnyComponentShouldBlockPrefabModeInPlayMode(assetPath); if (blockPrefabModeInPlaymode) { StageNavigationManager.instance.GoToMainStage(StageNavigationManager.Analytics.ChangeType.GoToMainViaPlayModeBlocking); } } if (playmodeState == PlayModeStateChange.EnteredEditMode) { // When exiting play mode we reload scenes and if we are in in Prefab Mode in Context we need to reconstruct the hidden state // for the the instance in the previous stage (this is setup when entering Prefab Mode in Context) if (mode == Mode.InContext && m_OpenedFromInstanceRoot != null) SetPrefabInstanceHiddenForInContextEditing(true); } } [OnOpenAsset] static bool OnOpenAsset(int instanceID, int line) { string assetPath = AssetDatabase.GetAssetPath(instanceID); if (assetPath.EndsWith(".prefab", StringComparison.OrdinalIgnoreCase)) { // The 'line' parameter can be used for passing an instanceID of a prefab instance GameObject instanceRoot = line == -1 ? null : EditorUtility.InstanceIDToObject(line) as GameObject; var prefabStageMode = instanceRoot != null ? PrefabStage.Mode.InContext : PrefabStage.Mode.InIsolation; PrefabStageUtility.OpenPrefab(assetPath, instanceRoot, prefabStageMode, StageNavigationManager.Analytics.ChangeType.EnterViaAssetOpened); return true; } return false; } } }
UnityCsReference/Editor/Mono/SceneManagement/StageManager/PrefabStage/PrefabStage.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/SceneManagement/StageManager/PrefabStage/PrefabStage.cs", "repo_id": "UnityCsReference", "token_count": 45296 }
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; namespace UnityEditor { internal class LightingWindowBakeSettings { bool m_LightingSettingsReadOnlyMode; SerializedObject m_LightingSettings; SharedLightingSettingsEditor m_LightingSettingsEditor; SerializedObject lightingSettings { get { // if we set a new scene as the active scene, we need to make sure to respond to those changes if (m_LightingSettings == null || m_LightingSettings.targetObject == null || m_LightingSettings.targetObject != Lightmapping.lightingSettingsInternal) { var targetObject = Lightmapping.lightingSettingsInternal; m_LightingSettingsReadOnlyMode = false; if (targetObject == null) { targetObject = Lightmapping.lightingSettingsDefaults; m_LightingSettingsReadOnlyMode = true; } SerializedObject lso = m_LightingSettings = new SerializedObject(targetObject); if (lso != null) { m_LightingSettingsEditor.UpdateSettings(lso); } } return m_LightingSettings; } } public void OnEnable() { if (m_LightingSettingsEditor == null) m_LightingSettingsEditor = new SharedLightingSettingsEditor(); m_LightingSettingsEditor.OnEnable(); } public void OnDisable() { if (m_LightingSettings != null) m_LightingSettings.Dispose(); } public void OnGUI() { lightingSettings.Update(); using (new EditorGUI.DisabledScope(m_LightingSettingsReadOnlyMode)) { m_LightingSettingsEditor.OnGUI(false, false); } lightingSettings.ApplyModifiedProperties(); } } }
UnityCsReference/Editor/Mono/SceneModeWindows/LightingWindowBakeSettings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/SceneModeWindows/LightingWindowBakeSettings.cs", "repo_id": "UnityCsReference", "token_count": 1043 }
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.Overlays; using UnityEngine; using Object = UnityEngine.Object; namespace UnityEditor { sealed class LegacyOverlay : IMGUIOverlay, ITransientOverlay { public OverlayWindow data { get; set; } public bool showRequested {get; set; } public override void OnGUI() { data?.sceneViewFunc?.Invoke(data.target, (SceneView)containerWindow); } public bool visible => showRequested; } // Deprecated. Use `TransientSceneViewOverlay` instead. class SceneViewOverlay { // This enum is for better overview of the ordering of our builtin overlays public enum Ordering { // Lower order is below high order when showed together Camera = -100, ClothConstraints = 0, ClothSelfAndInterCollision = 100, OcclusionCulling = 200, Lightmapping = 300, NavMesh = 400, PhysicsDebug = 450, TilemapRenderer = 500, ParticleEffect = 600 } public enum WindowDisplayOption { MultipleWindowsPerTarget, OneWindowPerTarget, OneWindowPerTitle } public delegate void WindowFunction(Object target, SceneView sceneView); public SceneViewOverlay(SceneView sceneView) {} public void Begin() {} public void End() {} const string k_ObsoleteMessage = "Please use UnityEditor.Overlays.TransientSceneViewOverlay in place of SceneViewOverlay."; [Obsolete(k_ObsoleteMessage)] // pass window parameter to render in sceneviews that are not the active view. public static void Window(GUIContent title, WindowFunction sceneViewFunc, int order, WindowDisplayOption option) { Window(title, sceneViewFunc, order, null, option); } [Obsolete(k_ObsoleteMessage)] // pass window parameter to render in sceneviews that are not the active view. public static void Window(GUIContent title, WindowFunction sceneViewFunc, int order, Object target, WindowDisplayOption option, EditorWindow window = null) { if (Event.current.type != EventType.Layout) return; ShowWindow(new OverlayWindow(title, sceneViewFunc, order, target, option)); } [Obsolete(k_ObsoleteMessage)] public static void ShowWindow(OverlayWindow window) { if (Event.current.type != EventType.Layout) return; if (SceneView.currentDrawingSceneView == null) { Debug.Log("SceneViewOverlay.ShowWindow can only be called from the scene view GUI"); return; } SceneView.currentDrawingSceneView.ShowLegacyOverlay(window); } } class OverlayWindow : IComparable<OverlayWindow> { public OverlayWindow(GUIContent title, SceneViewOverlay.WindowFunction guiFunction, int primaryOrder, Object target, SceneViewOverlay.WindowDisplayOption option) { this.title = title; this.sceneViewFunc = guiFunction; this.primaryOrder = primaryOrder; this.option = option; this.target = target; this.canCollapse = true; this.expanded = true; } public SceneViewOverlay.WindowFunction sceneViewFunc { get; } public int primaryOrder { get; } public int secondaryOrder { get; set; } public Object target { get; } public EditorWindow editorWindow { get; set; } public SceneViewOverlay.WindowDisplayOption option { get; } = SceneViewOverlay.WindowDisplayOption.MultipleWindowsPerTarget; public bool canCollapse { get; set; } public bool expanded { get; set; } public GUIContent title { get; } public int CompareTo(OverlayWindow other) { return 0; } } }
UnityCsReference/Editor/Mono/SceneView/SceneViewOverlay.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/SceneView/SceneViewOverlay.cs", "repo_id": "UnityCsReference", "token_count": 1737 }
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 System; using System.IO; using UnityEditorInternal; namespace UnityEditor { // Use the FilePathAttribute when you want to have your scriptable singleton to persist between unity sessions. // Example: [FilePathAttribute("Library/SearchFilters.ssf", FilePathAttribute.Location.ProjectFolder)] // Ensure to call Save() from client code (derived instance) [AttributeUsage(AttributeTargets.Class)] public class FilePathAttribute : Attribute { public enum Location { PreferencesFolder, ProjectFolder } private string m_FilePath; private string m_RelativePath; private Location m_Location; internal string filepath { get { if (m_FilePath == null && m_RelativePath != null) { m_FilePath = CombineFilePath(m_RelativePath, m_Location); m_RelativePath = null; } return m_FilePath; } } public FilePathAttribute(string relativePath, Location location) { if (string.IsNullOrEmpty(relativePath)) { throw new ArgumentException("Invalid relative path (it is empty)"); } m_RelativePath = relativePath; m_Location = location; } static string CombineFilePath(string relativePath, Location location) { // We do not want a slash as first char if (relativePath[0] == '/') relativePath = relativePath.Substring(1); switch (location) { case Location.PreferencesFolder: return InternalEditorUtility.unityPreferencesFolder + "/" + relativePath; case Location.ProjectFolder: return relativePath; default: Debug.LogError("Unhandled enum: " + location); return relativePath; // fallback to ProjectFolder relative path } } } public class ScriptableSingleton<T> : ScriptableObject where T : ScriptableObject { static T s_Instance; public static T instance { get { if (s_Instance == null) CreateAndLoad(); return s_Instance; } } // On domain reload ScriptableObject objects gets reconstructed from a backup. We therefore set the s_Instance here protected ScriptableSingleton() { if (s_Instance != null) { Debug.LogError("ScriptableSingleton already exists. Did you query the singleton in a constructor?"); } else { object casted = this; s_Instance = casted as T; System.Diagnostics.Debug.Assert(s_Instance != null); } } private static void CreateAndLoad() { System.Diagnostics.Debug.Assert(s_Instance == null); // Load string filePath = GetFilePath(); if (!string.IsNullOrEmpty(filePath)) { // If a file exists then load it and deserialize it. // This creates an instance of T which will set s_Instance in the constructor. Then it will deserialize it and call relevant serialization callbacks. InternalEditorUtility.LoadSerializedFileAndForget(filePath); } if (s_Instance == null) { // Create T t = CreateInstance<T>(); // Editing should be allowed, but the user is responsible for calling Save() (case uum-40767) t.hideFlags = HideFlags.HideAndDontSave & ~HideFlags.NotEditable; } System.Diagnostics.Debug.Assert(s_Instance != null); } protected virtual void Save(bool saveAsText) { if (s_Instance == null) { Debug.LogError("Cannot save ScriptableSingleton: no instance!"); return; } string filePath = GetFilePath(); if (!string.IsNullOrEmpty(filePath)) { string folderPath = Path.GetDirectoryName(filePath); if (!Directory.Exists(folderPath)) Directory.CreateDirectory(folderPath); InternalEditorUtility.SaveToSerializedFileAndForget(new[] { s_Instance }, filePath, saveAsText); } else { Debug.LogWarning($"Saving has no effect. Your class '{GetType()}' is missing the FilePathAttribute. Use this attribute to specify where to save your ScriptableSingleton.\nOnly call Save() and use this attribute if you want your state to survive between sessions of Unity."); } } protected static string GetFilePath() { Type type = typeof(T); object[] attributes = type.GetCustomAttributes(true); foreach (object attr in attributes) { if (attr is FilePathAttribute) { FilePathAttribute f = attr as FilePathAttribute; return f.filepath; } } return string.Empty; } } }
UnityCsReference/Editor/Mono/ScriptableSingleton.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/ScriptableSingleton.cs", "repo_id": "UnityCsReference", "token_count": 2545 }
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 System.Collections.Generic; using System.IO; using UnityEditor.Scripting.ScriptCompilation; using UnityEngine; namespace UnityEditor.Scripting.Compilers { internal abstract class ResponseFileProvider { private const string k_AssetsFolder = "Assets"; public abstract string ResponseFileName { get; } public abstract string[] ObsoleteResponseFileNames { get; } public string ProjectPath { get; set; } protected ResponseFileProvider() { var dataPath = Application.dataPath; ProjectPath = Path.GetDirectoryName(dataPath); } public List<string> Get(string folderToLookForResponseFilesIn) { if (!string.IsNullOrEmpty(folderToLookForResponseFilesIn) && !Path.IsPathRooted(folderToLookForResponseFilesIn)) { folderToLookForResponseFilesIn = AssetPath.Combine(ProjectPath, folderToLookForResponseFilesIn); } var result = new List<string>(); var folderResponseFile = GetCompilerSpecific(folderToLookForResponseFilesIn); if (!string.IsNullOrEmpty(folderResponseFile)) { AddIfNotNull(result, folderResponseFile); } else { AddIfNotNull(result, GetDefaultResponseFiles()); } return result; } protected string GetCompilerSpecific(string path) { if (string.IsNullOrEmpty(path)) { return null; } //We only look for the specific response file in the folder. var responseFilePath = AssetPath.Combine(path, ResponseFileName); if (File.Exists(responseFilePath)) { return responseFilePath; } return null; } protected string GetDefaultResponseFiles() { var rootResponseFilePath = AssetPath.Combine(ProjectPath, k_AssetsFolder, ResponseFileName); if (File.Exists(rootResponseFilePath)) { return rootResponseFilePath; } foreach (var obsoleteResponseFileName in ObsoleteResponseFileNames) { var obsoleteResponseFilePath = AssetPath.Combine(ProjectPath, k_AssetsFolder, obsoleteResponseFileName); if (File.Exists(obsoleteResponseFilePath)) { return obsoleteResponseFilePath; } } return null; } private static void AddIfNotNull<T>(List<T> list, T element) { if (element != null) { list.Add(element); } } } }
UnityCsReference/Editor/Mono/Scripting/Compilers/ResponseFileProvider.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Scripting/Compilers/ResponseFileProvider.cs", "repo_id": "UnityCsReference", "token_count": 1360 }
344
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using Bee.BeeDriver; using BeeBuildProgramCommon.Data; using NiceIO; using UnityEditor.PackageManager; using UnityEditorInternal; using UnityEngine; using Debug = UnityEngine.Debug; namespace UnityEditor.Scripting.ScriptCompilation { static class UnityBeeDriver { internal static readonly string BeeBackendExecutable = new NPath($"{EditorApplication.applicationContentsPath}/bee_backend{BeeScriptCompilation.ExecutableExtension}").ToString(); internal static readonly string BeeCacheToolExecutable = $"{EditorApplication.applicationContentsPath}/Tools/BuildPipeline/BeeLocalCacheTool{BeeScriptCompilation.ExecutableExtension}"; internal static readonly string BeeCacheDirEnvVar = "BEE_CACHE_DIRECTORY"; internal static string BeeCacheDir => Environment.GetEnvironmentVariable(BeeCacheDirEnvVar) ?? new NPath($"{InternalEditorUtility.userAppDataFolder}/cache/bee").ToString(SlashMode.Native); [Serializable] internal class BeeBackendInfo { public string UnityVersion; public string BeeBackendHash; } internal static string BeeBackendHash { get { // Using SessionState, that way we won't need to rehash on domain reload. var hash = SessionState.GetString(nameof(BeeBackendHash), string.Empty); if (!string.IsNullOrEmpty(hash)) return hash; using var hasher = new SHA256Managed(); using var stream = File.OpenRead(BeeBackendExecutable); var bytes = hasher.ComputeHash(stream); var sb = new StringBuilder(); foreach (var b in bytes) sb.Append(b.ToString("x2", CultureInfo.InvariantCulture)); hash = sb.ToString(); SessionState.SetString(nameof(BeeBackendHash), hash); return hash; } } public static BeeBuildProgramCommon.Data.PackageInfo[] GetPackageInfos(string projectDirectory) { return PackageManager.PackageInfo.GetAllRegisteredPackages().Select(p => { NPath resolvedPath = new NPath(p.resolvedPath); if (resolvedPath.IsChildOf(projectDirectory)) resolvedPath = resolvedPath.RelativeTo(projectDirectory); return new BeeBuildProgramCommon.Data.PackageInfo() { Name = p.name, ResolvedPath = resolvedPath.ToString(), }; }).ToArray(); } private static void RecreateDagDirectoryIfNeeded(NPath dagDirectory) { var beeBackendInfoPath = dagDirectory.Combine("bee_backend.info"); var currentInfo = new BeeBackendInfo() { BeeBackendHash = BeeBackendHash, UnityVersion = Application.unityVersion }; var diskInfo = new BeeBackendInfo(); // Clear dag directory if it was produced with a different bee_backend, to avoid problem where bee_backend sometimes looses track of files. if (dagDirectory.Exists()) { // When used DeleteMode.Normal, it sometimes was causing an error on Windows: // Win32Exception: The directory is not empty. // at NiceIO.NPath + WindowsFileSystem.Directory_Delete(NiceIO.NPath path, System.Boolean recursive)[0x000f4] in C:\buildslave\unity\build\External\NiceIO\NiceIO.cs:1792 // Since we're recreating a directory anyways, using DeleteMode.Soft should be fine. var deleteMode = DeleteMode.Soft; if (beeBackendInfoPath.Exists()) { var contents = beeBackendInfoPath.ReadAllText(); EditorJsonUtility.FromJsonOverwrite(contents, diskInfo); // Note: We're clearing dag directory only when bee backend hash has changed, it's fine for Unity version to be different. // Unity version is used here for informational purposes, so we can clearly see from which Unity version the user was upgrading if (string.IsNullOrEmpty(diskInfo.BeeBackendHash) || !diskInfo.BeeBackendHash.Equals(currentInfo.BeeBackendHash)) { Console.WriteLine($"Clearing Bee directory '{dagDirectory}', since bee backend hash ('{beeBackendInfoPath}') is different, previous hash was {diskInfo.BeeBackendHash} (Unity version: {diskInfo.UnityVersion}), current hash is {currentInfo.BeeBackendHash} (Unity version: {currentInfo.UnityVersion})."); dagDirectory.Delete(deleteMode); } } else { Console.WriteLine($"Clearing Bee directory '{dagDirectory}', since bee backend information ('{beeBackendInfoPath}') is missing."); dagDirectory.Delete(deleteMode); } } dagDirectory.CreateDirectory(); // Update info, if at least of one the fields is different if (string.IsNullOrEmpty(diskInfo.BeeBackendHash) || string.IsNullOrEmpty(diskInfo.UnityVersion) || !diskInfo.BeeBackendHash.Equals(currentInfo.BeeBackendHash) || !diskInfo.UnityVersion.Equals(currentInfo.UnityVersion)) { beeBackendInfoPath.WriteAllText(EditorJsonUtility.ToJson(currentInfo, true)); } } public static BuildRequest BuildRequestFor(RunnableProgram buildProgram, EditorCompilation editorCompilation, string dagName, CacheMode cacheMode, string dagDirectory = null, bool useScriptUpdater = true) { return BuildRequestFor(buildProgram, dagName, dagDirectory, useScriptUpdater, editorCompilation.projectDirectory, new ILPostProcessingProgram(), cacheMode, StdOutModeForScriptCompilation); } public const StdOutMode StdOutModeForScriptCompilation = StdOutMode.LogStartArgumentsAndExitcode | StdOutMode.LogStdOutOnFinish; public const StdOutMode StdOutModeForPlayerBuilds = StdOutMode.LogStartArgumentsAndExitcode | StdOutMode.Stream; public static BuildRequest BuildRequestFor( RunnableProgram buildProgram, string dagName, string dagDirectory, bool useScriptUpdater, string projectDirectory, ILPostProcessingProgram ilpp, CacheMode cacheMode, StdOutMode stdoutMode, RunnableProgram beeBackendProgram = null) { // ensure ilpp server is running before staring the backend in defered validation mode. // getting the property value enforces that as it makes sure the server is running and answering a ping request var ilppNamedPipeOrSocket = ilpp.EnsureRunningAndGetSocketOrNamedPipe(); NPath dagDir = dagDirectory ?? "Library/Bee"; RecreateDagDirectoryIfNeeded(dagDir); var performingPlayerBuild = UnityBeeDriverProfilerSession.PerformingPlayerBuild; NPath profilerOutputFile = performingPlayerBuild ? UnityBeeDriverProfilerSession.GetTraceEventsOutputForPlayerBuild() : $"{dagDir}/fullprofile.json"; return new BuildRequest() { BuildProgram = buildProgram, BackendProgram = beeBackendProgram ?? UnityBeeBackendProgram(cacheMode, stdoutMode), ProjectRoot = projectDirectory, DagName = dagName, BuildStateDirectory = dagDir.EnsureDirectoryExists().ToString(), ProfilerOutputFile = profilerOutputFile.ToString(), // Use a null process name during a player build to avoid writing process metadata. The player profiler will take care of writing the process metadata ProfilerProcessName = performingPlayerBuild ? null : "BeeDriver", SourceFileUpdaters = useScriptUpdater ? new[] {new UnityScriptUpdater(projectDirectory)} : Array.Empty<SourceFileUpdaterBase>(), ProcessSourceFileUpdatersResult = new UnitySourceFileUpdatersResultHandler(), DataForBuildProgram = { () => new ConfigurationData { Il2CppDir = IL2CPPUtils.GetIl2CppFolder(), Il2CppPath = IL2CPPUtils.GetExePath("il2cpp"), UnityLinkerPath = IL2CPPUtils.GetExePath("UnityLinker"), NetCoreRunPath = NetCoreRunProgram.NetCoreRunPath, DotNetExe = NetCoreProgram.DotNetMuxerPath.ToString(), EditorContentsPath = EditorApplication.applicationContentsPath, Packages = GetPackageInfos(NPath.CurrentDirectory.ToString()), UnityVersion = Application.unityVersion, UnityVersionNumeric = new BeeBuildProgramCommon.Data.Version(Application.unityVersionVer, Application.unityVersionMaj, Application.unityVersionMin), UnitySourceCodePath = Unsupported.IsSourceBuild(false) ? Unsupported.GetBaseUnityDeveloperFolder() : null, AdvancedLicense = PlayerSettings.advancedLicense, Batchmode = InternalEditorUtility.inBatchMode, EmitDataForBeeWhy = (Debug.GetDiagnosticSwitch("EmitDataForBeeWhy").value as bool?)?? false, NamedPipeOrUnixSocket = ilppNamedPipeOrSocket, } } }; } public static void RunCleanBeeCache() { // Note that this size is spefied as the total number of used bytes for all the files in the cache // and not as the actual size of occupied blocks on the disk, which will add some overhead. long cacheSize = 256 * 1024 * 1024; var psi = new ProcessStartInfo() { FileName = BeeCacheToolExecutable, Arguments = $"clean {cacheSize}", UseShellExecute = false }; psi.EnvironmentVariables[BeeCacheDirEnvVar] = BeeCacheDir; Process.Start(psi); } public enum CacheMode { Off, ReadOnly, WriteOnly, ReadWrite, } internal static RunnableProgram UnityBeeBackendProgram(CacheMode cacheMode, StdOutMode stdoutMode) { var env = new Dictionary<string, string>() { { "BEE_CACHE_BEHAVIOUR", cacheMode switch { CacheMode.Off => "_", CacheMode.ReadOnly => "R", CacheMode.WriteOnly => "W", CacheMode.ReadWrite => "RW", _ => throw new ArgumentOutOfRangeException(nameof(cacheMode), cacheMode, null) }}, { "CACHE_SERVER_ADDRESS", "none_but_bee_still_wants_us_to_set_it" }, { "REAPI_CACHE_CLIENT", $"\"{BeeCacheToolExecutable}\"" }, { BeeCacheDirEnvVar, BeeCacheDir }, { "CHROMETRACE_TIMEOFFSET", "unixepoch" } }; return new SystemProcessRunnableProgram(BeeBackendExecutable, alwaysEnvironmentVariables: env, stdOutMode: stdoutMode); } } }
UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/BeeDriver/UnityBeeDriver.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/BeeDriver/UnityBeeDriver.cs", "repo_id": "UnityCsReference", "token_count": 5233 }
345
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; static class EnumerableExtensions { public static string SeparateWith(this IEnumerable<string> values, string separator) { return string.Join(separator, values); } public static (List<T> True, List<T> False) SplitBy<T>(this ICollection<T> collection, Func<T, bool> predicate) { (List<T> True, List<T> False)result = (new List<T>(collection.Count), new List<T>(collection.Count)); foreach (var item in collection) if (predicate(item)) result.True.Add(item); else result.False.Add(item); return result; } }
UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/EnumerableExtensions.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/EnumerableExtensions.cs", "repo_id": "UnityCsReference", "token_count": 329 }
346